blob: 040757bdb1e41ccec9685caffa4e28aec057c14f [file] [log] [blame]
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Preparation and completion of hprof data generation. The output is
19 * written into two files and then combined. This is necessary because
20 * we generate some of the data (strings and classes) while we dump the
21 * heap, and some analysis tools require that the class and string data
22 * appear first.
23 */
24
25#include "hprof.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080026
Elliott Hughes622a6982012-06-08 17:58:54 -070027#include <cutils/open_memstream.h>
28#include <errno.h>
29#include <fcntl.h>
30#include <stdio.h>
31#include <string.h>
32#include <sys/time.h>
33#include <sys/uio.h>
34#include <time.h>
35#include <time.h>
36#include <unistd.h>
37
38#include <set>
39
Elliott Hughes07ed66b2012-12-12 18:34:25 -080040#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080041#include "base/stringprintf.h"
Elliott Hughes76160052012-12-12 16:31:20 -080042#include "base/unix_file/fd_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080043#include "class_linker.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080044#include "common_throws.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040045#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070046#include "dex_file-inl.h"
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -080047#include "gc_root.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070048#include "gc/accounting/heap_bitmap.h"
49#include "gc/heap.h"
50#include "gc/space/space.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070051#include "globals.h"
Mathieu Chartierad466ad2015-01-08 16:28:08 -080052#include "jdwp/jdwp.h"
53#include "jdwp/jdwp_priv.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070054#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/class.h"
56#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object-inl.h"
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -070058#include "os.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070059#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070060#include "scoped_thread_state_change.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070061#include "thread_list.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040062
63namespace art {
64
65namespace hprof {
66
Mathieu Chartierad466ad2015-01-08 16:28:08 -080067static constexpr bool kDirectStream = true;
Jesse Wilson0c54ac12011-11-09 15:14:05 -050068
Andreas Gampe3a913092015-01-10 00:26:17 -080069static constexpr uint32_t kHprofTime = 0;
70static constexpr uint32_t kHprofNullStackTrace = 0;
71static constexpr uint32_t kHprofNullThread = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -070072
Andreas Gampe3a913092015-01-10 00:26:17 -080073static constexpr size_t kMaxObjectsPerSegment = 128;
74static constexpr size_t kMaxBytesPerSegment = 4096;
Elliott Hughes622a6982012-06-08 17:58:54 -070075
Andreas Gampe3a913092015-01-10 00:26:17 -080076// The static field-name for the synthetic object generated to account for class static overhead.
77static constexpr const char* kStaticOverheadName = "$staticOverhead";
Elliott Hughes622a6982012-06-08 17:58:54 -070078
79enum HprofTag {
80 HPROF_TAG_STRING = 0x01,
81 HPROF_TAG_LOAD_CLASS = 0x02,
82 HPROF_TAG_UNLOAD_CLASS = 0x03,
83 HPROF_TAG_STACK_FRAME = 0x04,
84 HPROF_TAG_STACK_TRACE = 0x05,
85 HPROF_TAG_ALLOC_SITES = 0x06,
86 HPROF_TAG_HEAP_SUMMARY = 0x07,
87 HPROF_TAG_START_THREAD = 0x0A,
88 HPROF_TAG_END_THREAD = 0x0B,
89 HPROF_TAG_HEAP_DUMP = 0x0C,
90 HPROF_TAG_HEAP_DUMP_SEGMENT = 0x1C,
91 HPROF_TAG_HEAP_DUMP_END = 0x2C,
92 HPROF_TAG_CPU_SAMPLES = 0x0D,
93 HPROF_TAG_CONTROL_SETTINGS = 0x0E,
94};
95
96// Values for the first byte of HEAP_DUMP and HEAP_DUMP_SEGMENT records:
97enum HprofHeapTag {
98 // Traditional.
99 HPROF_ROOT_UNKNOWN = 0xFF,
100 HPROF_ROOT_JNI_GLOBAL = 0x01,
101 HPROF_ROOT_JNI_LOCAL = 0x02,
102 HPROF_ROOT_JAVA_FRAME = 0x03,
103 HPROF_ROOT_NATIVE_STACK = 0x04,
104 HPROF_ROOT_STICKY_CLASS = 0x05,
105 HPROF_ROOT_THREAD_BLOCK = 0x06,
106 HPROF_ROOT_MONITOR_USED = 0x07,
107 HPROF_ROOT_THREAD_OBJECT = 0x08,
108 HPROF_CLASS_DUMP = 0x20,
109 HPROF_INSTANCE_DUMP = 0x21,
110 HPROF_OBJECT_ARRAY_DUMP = 0x22,
111 HPROF_PRIMITIVE_ARRAY_DUMP = 0x23,
112
113 // Android.
114 HPROF_HEAP_DUMP_INFO = 0xfe,
115 HPROF_ROOT_INTERNED_STRING = 0x89,
116 HPROF_ROOT_FINALIZING = 0x8a, // Obsolete.
117 HPROF_ROOT_DEBUGGER = 0x8b,
118 HPROF_ROOT_REFERENCE_CLEANUP = 0x8c, // Obsolete.
119 HPROF_ROOT_VM_INTERNAL = 0x8d,
120 HPROF_ROOT_JNI_MONITOR = 0x8e,
121 HPROF_UNREACHABLE = 0x90, // Obsolete.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700122 HPROF_PRIMITIVE_ARRAY_NODATA_DUMP = 0xc3, // Obsolete.
Elliott Hughes622a6982012-06-08 17:58:54 -0700123};
124
125enum HprofHeapId {
126 HPROF_HEAP_DEFAULT = 0,
127 HPROF_HEAP_ZYGOTE = 'Z',
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700128 HPROF_HEAP_APP = 'A',
129 HPROF_HEAP_IMAGE = 'I',
Elliott Hughes622a6982012-06-08 17:58:54 -0700130};
131
132enum HprofBasicType {
133 hprof_basic_object = 2,
134 hprof_basic_boolean = 4,
135 hprof_basic_char = 5,
136 hprof_basic_float = 6,
137 hprof_basic_double = 7,
138 hprof_basic_byte = 8,
139 hprof_basic_short = 9,
140 hprof_basic_int = 10,
141 hprof_basic_long = 11,
142};
143
Ian Rogersef7d42f2014-01-06 12:55:46 -0800144typedef uint32_t HprofStringId;
145typedef uint32_t HprofClassObjectId;
Elliott Hughes622a6982012-06-08 17:58:54 -0700146
Andreas Gampe3a913092015-01-10 00:26:17 -0800147class EndianOutput {
Elliott Hughes622a6982012-06-08 17:58:54 -0700148 public:
Andreas Gampe3a913092015-01-10 00:26:17 -0800149 EndianOutput() : length_(0), sum_length_(0), max_length_(0), started_(false) {}
150 virtual ~EndianOutput() {}
151
152 void StartNewRecord(uint8_t tag, uint32_t time) {
153 if (length_ > 0) {
154 EndRecord();
155 }
156 DCHECK_EQ(length_, 0U);
157 AddU1(tag);
158 AddU4(time);
159 AddU4(0xdeaddead); // Length, replaced on flush.
160 started_ = true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700161 }
162
Andreas Gampe3a913092015-01-10 00:26:17 -0800163 void EndRecord() {
164 // Replace length in header.
165 if (started_) {
166 UpdateU4(sizeof(uint8_t) + sizeof(uint32_t),
167 length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
168 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700169
Andreas Gampe3a913092015-01-10 00:26:17 -0800170 HandleEndRecord();
171
172 sum_length_ += length_;
173 max_length_ = std::max(max_length_, length_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700174 length_ = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -0800175 started_ = false;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700176 }
177
Andreas Gampe3a913092015-01-10 00:26:17 -0800178 void AddU1(uint8_t value) {
179 AddU1List(&value, 1);
180 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800181 void AddU2(uint16_t value) {
182 AddU2List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700183 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800184 void AddU4(uint32_t value) {
185 AddU4List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700186 }
187
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800188 void AddU8(uint64_t value) {
189 AddU8List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700190 }
191
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800192 void AddObjectId(const mirror::Object* value) {
193 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800194 }
195
196 // The ID for the synthetic object generated to account for class static overhead.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800197 void AddClassStaticsId(const mirror::Class* value) {
198 AddU4(1 | PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800199 }
200
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800201 void AddJniGlobalRefId(jobject value) {
202 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800203 }
204
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800205 void AddClassId(HprofClassObjectId value) {
206 AddU4(value);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800207 }
208
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800209 void AddStringId(HprofStringId value) {
210 AddU4(value);
Elliott Hughes622a6982012-06-08 17:58:54 -0700211 }
212
Andreas Gampe3a913092015-01-10 00:26:17 -0800213 void AddU1List(const uint8_t* values, size_t count) {
214 HandleU1List(values, count);
215 length_ += count;
216 }
217 void AddU2List(const uint16_t* values, size_t count) {
218 HandleU2List(values, count);
219 length_ += count * sizeof(uint16_t);
220 }
221 void AddU4List(const uint32_t* values, size_t count) {
222 HandleU4List(values, count);
223 length_ += count * sizeof(uint32_t);
224 }
225 virtual void UpdateU4(size_t offset ATTRIBUTE_UNUSED, uint32_t new_value ATTRIBUTE_UNUSED) {
226 DCHECK_LE(offset, length_ - 4);
227 }
228 void AddU8List(const uint64_t* values, size_t count) {
229 HandleU8List(values, count);
230 length_ += count * sizeof(uint64_t);
231 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700232
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800233 void AddIdList(mirror::ObjectArray<mirror::Object>* values)
Andreas Gampe3a913092015-01-10 00:26:17 -0800234 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800235 const int32_t length = values->GetLength();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800236 for (int32_t i = 0; i < length; ++i) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800237 AddObjectId(values->GetWithoutChecks(i));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800238 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700239 }
240
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800241 void AddUtf8String(const char* str) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700242 // The terminating NUL character is NOT written.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800243 AddU1List((const uint8_t*)str, strlen(str));
Elliott Hughes622a6982012-06-08 17:58:54 -0700244 }
245
Andreas Gampe3a913092015-01-10 00:26:17 -0800246 size_t Length() const {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700247 return length_;
248 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700249
Andreas Gampe3a913092015-01-10 00:26:17 -0800250 size_t SumLength() const {
251 return sum_length_;
Elliott Hughes622a6982012-06-08 17:58:54 -0700252 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700253
Andreas Gampe3a913092015-01-10 00:26:17 -0800254 size_t MaxLength() const {
255 return max_length_;
256 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700257
Andreas Gampe3a913092015-01-10 00:26:17 -0800258 protected:
259 virtual void HandleU1List(const uint8_t* values ATTRIBUTE_UNUSED,
260 size_t count ATTRIBUTE_UNUSED) {
261 }
262 virtual void HandleU2List(const uint16_t* values ATTRIBUTE_UNUSED,
263 size_t count ATTRIBUTE_UNUSED) {
264 }
265 virtual void HandleU4List(const uint32_t* values ATTRIBUTE_UNUSED,
266 size_t count ATTRIBUTE_UNUSED) {
267 }
268 virtual void HandleU8List(const uint64_t* values ATTRIBUTE_UNUSED,
269 size_t count ATTRIBUTE_UNUSED) {
270 }
271 virtual void HandleEndRecord() {
272 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700273
Andreas Gampe3a913092015-01-10 00:26:17 -0800274 size_t length_; // Current record size.
275 size_t sum_length_; // Size of all data.
276 size_t max_length_; // Maximum seen length.
277 bool started_; // Was StartRecord called?
Elliott Hughes622a6982012-06-08 17:58:54 -0700278};
279
Andreas Gampe3a913092015-01-10 00:26:17 -0800280// This keeps things buffered until flushed.
281class EndianOutputBuffered : public EndianOutput {
282 public:
283 explicit EndianOutputBuffered(size_t reserve_size) {
284 buffer_.reserve(reserve_size);
285 }
286 virtual ~EndianOutputBuffered() {}
287
288 void UpdateU4(size_t offset, uint32_t new_value) OVERRIDE {
289 DCHECK_LE(offset, length_ - 4);
290 buffer_[offset + 0] = static_cast<uint8_t>((new_value >> 24) & 0xFF);
291 buffer_[offset + 1] = static_cast<uint8_t>((new_value >> 16) & 0xFF);
292 buffer_[offset + 2] = static_cast<uint8_t>((new_value >> 8) & 0xFF);
293 buffer_[offset + 3] = static_cast<uint8_t>((new_value >> 0) & 0xFF);
294 }
295
296 protected:
297 void HandleU1List(const uint8_t* values, size_t count) OVERRIDE {
298 DCHECK_EQ(length_, buffer_.size());
299 buffer_.insert(buffer_.end(), values, values + count);
300 }
301
302 void HandleU2List(const uint16_t* values, size_t count) OVERRIDE {
303 DCHECK_EQ(length_, buffer_.size());
304 for (size_t i = 0; i < count; ++i) {
305 uint16_t value = *values;
306 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
307 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
308 values++;
309 }
310 }
311
312 void HandleU4List(const uint32_t* values, size_t count) OVERRIDE {
313 DCHECK_EQ(length_, buffer_.size());
314 for (size_t i = 0; i < count; ++i) {
315 uint32_t value = *values;
316 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
317 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
318 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
319 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
320 values++;
321 }
322 }
323
324 void HandleU8List(const uint64_t* values, size_t count) OVERRIDE {
325 DCHECK_EQ(length_, buffer_.size());
326 for (size_t i = 0; i < count; ++i) {
327 uint64_t value = *values;
328 buffer_.push_back(static_cast<uint8_t>((value >> 56) & 0xFF));
329 buffer_.push_back(static_cast<uint8_t>((value >> 48) & 0xFF));
330 buffer_.push_back(static_cast<uint8_t>((value >> 40) & 0xFF));
331 buffer_.push_back(static_cast<uint8_t>((value >> 32) & 0xFF));
332 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
333 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
334 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
335 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
336 values++;
337 }
338 }
339
340 void HandleEndRecord() OVERRIDE {
341 DCHECK_EQ(buffer_.size(), length_);
342 if (kIsDebugBuild && started_) {
343 uint32_t stored_length =
344 static_cast<uint32_t>(buffer_[5]) << 24 |
345 static_cast<uint32_t>(buffer_[6]) << 16 |
346 static_cast<uint32_t>(buffer_[7]) << 8 |
347 static_cast<uint32_t>(buffer_[8]);
348 DCHECK_EQ(stored_length, length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
349 }
350 HandleFlush(buffer_.data(), length_);
351 buffer_.clear();
352 }
353
354 virtual void HandleFlush(const uint8_t* buffer ATTRIBUTE_UNUSED, size_t length ATTRIBUTE_UNUSED) {
355 }
356
357 std::vector<uint8_t> buffer_;
358};
359
360class FileEndianOutput FINAL : public EndianOutputBuffered {
361 public:
362 FileEndianOutput(File* fp, size_t reserved_size)
363 : EndianOutputBuffered(reserved_size), fp_(fp), errors_(false) {
364 DCHECK(fp != nullptr);
365 }
366 ~FileEndianOutput() {
367 }
368
369 bool Errors() {
370 return errors_;
371 }
372
373 protected:
374 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
375 if (!errors_) {
376 errors_ = !fp_->WriteFully(buffer, length);
377 }
378 }
379
380 private:
381 File* fp_;
382 bool errors_;
383};
384
385class NetStateEndianOutput FINAL : public EndianOutputBuffered {
386 public:
387 NetStateEndianOutput(JDWP::JdwpNetStateBase* net_state, size_t reserved_size)
388 : EndianOutputBuffered(reserved_size), net_state_(net_state) {
389 DCHECK(net_state != nullptr);
390 }
391 ~NetStateEndianOutput() {}
392
393 protected:
394 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
395 std::vector<iovec> iov;
396 iov.push_back(iovec());
397 iov[0].iov_base = const_cast<void*>(reinterpret_cast<const void*>(buffer));
398 iov[0].iov_len = length;
399 net_state_->WriteBufferedPacketLocked(iov);
400 }
401
402 private:
403 JDWP::JdwpNetStateBase* net_state_;
404};
405
406#define __ output->
407
Elliott Hughes622a6982012-06-08 17:58:54 -0700408class Hprof {
409 public:
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700410 Hprof(const char* output_filename, int fd, bool direct_to_ddms)
411 : filename_(output_filename),
412 fd_(fd),
413 direct_to_ddms_(direct_to_ddms),
414 start_ns_(NanoTime()),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700415 current_heap_(HPROF_HEAP_DEFAULT),
416 objects_in_segment_(0),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700417 next_string_id_(0x400000) {
418 LOG(INFO) << "hprof: heap dump \"" << filename_ << "\" starting...";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500419 }
420
Andreas Gampe3a913092015-01-10 00:26:17 -0800421 void Dump()
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800422 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800423 LOCKS_EXCLUDED(Locks::heap_bitmap_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800424 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
425 // First pass to measure the size of the dump.
426 size_t overall_size;
427 size_t max_length;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800428 {
Andreas Gampe3a913092015-01-10 00:26:17 -0800429 EndianOutput count_output;
430 ProcessHeap(&count_output, false);
431 overall_size = count_output.SumLength();
432 max_length = count_output.MaxLength();
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800433 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700434
Andreas Gampe3a913092015-01-10 00:26:17 -0800435 bool okay;
436 if (direct_to_ddms_) {
437 if (kDirectStream) {
438 okay = DumpToDdmsDirect(overall_size, max_length, CHUNK_TYPE("HPDS"));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700439 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800440 okay = DumpToDdmsBuffered(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700441 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800442 } else {
443 okay = DumpToFile(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700444 }
445
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700446 if (okay) {
447 uint64_t duration = NanoTime() - start_ns_;
Ian Rogers50b35e22012-10-04 10:09:15 -0700448 LOG(INFO) << "hprof: heap dump completed ("
Andreas Gampe3a913092015-01-10 00:26:17 -0800449 << PrettySize(RoundUp(overall_size, 1024))
Ian Rogers50b35e22012-10-04 10:09:15 -0700450 << ") in " << PrettyDuration(duration);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700451 }
452 }
453
454 private:
Andreas Gampe3a913092015-01-10 00:26:17 -0800455 struct Env {
456 Hprof* hprof;
457 EndianOutput* output;
458 };
459
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800460 static void RootVisitor(mirror::Object** obj, void* arg, const RootInfo& root_info)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700461 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800462 DCHECK(arg != nullptr);
463 DCHECK(obj != nullptr);
464 DCHECK(*obj != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800465 Env* env = reinterpret_cast<Env*>(arg);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800466 env->hprof->VisitRoot(*obj, root_info, env->output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700467 }
468
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800469 static void VisitObjectCallback(mirror::Object* obj, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700470 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800471 DCHECK(obj != nullptr);
472 DCHECK(arg != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800473 Env* env = reinterpret_cast<Env*>(arg);
474 env->hprof->DumpHeapObject(obj, env->output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700475 }
476
Andreas Gampe3a913092015-01-10 00:26:17 -0800477 void DumpHeapObject(mirror::Object* obj, EndianOutput* output)
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800478 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700479
Andreas Gampe3a913092015-01-10 00:26:17 -0800480 void DumpHeapClass(mirror::Class* klass, EndianOutput* output)
481 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700482
Andreas Gampe3a913092015-01-10 00:26:17 -0800483 void DumpHeapArray(mirror::Array* obj, mirror::Class* klass, EndianOutput* output)
484 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
485
486 void DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass, EndianOutput* output)
487 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
488
489 void ProcessHeap(EndianOutput* output, bool header_first)
490 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
491 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
492 // Reset current heap and object count.
493 current_heap_ = HPROF_HEAP_DEFAULT;
494 objects_in_segment_ = 0;
495
496 if (header_first) {
497 ProcessHeader(output);
498 ProcessBody(output);
499 } else {
500 ProcessBody(output);
501 ProcessHeader(output);
502 }
503 }
504
505 void ProcessBody(EndianOutput* output) EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
506 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
507 Runtime* runtime = Runtime::Current();
508 // Walk the roots and the heap.
509 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
510
511 Env env = { this, output };
512 runtime->VisitRoots(RootVisitor, &env);
513 runtime->GetHeap()->VisitObjects(VisitObjectCallback, &env);
514
515 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_END, kHprofTime);
516 output->EndRecord();
517 }
518
519 void ProcessHeader(EndianOutput* output) EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
520 // Write the header.
521 WriteFixedHeader(output);
522 // Write the string and class tables, and any stack traces, to the header.
523 // (jhat requires that these appear before any of the data in the body that refers to them.)
524 WriteStringTable(output);
525 WriteClassTable(output);
526 WriteStackTraces(output);
527 output->EndRecord();
528 }
529
530 void WriteClassTable(EndianOutput* output) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700531 uint32_t nextSerialNumber = 1;
532
Ian Rogersef7d42f2014-01-06 12:55:46 -0800533 for (mirror::Class* c : classes_) {
534 CHECK(c != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800535 output->StartNewRecord(HPROF_TAG_LOAD_CLASS, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700536 // LOAD CLASS format:
537 // U4: class serial number (always > 0)
538 // ID: class object ID. We use the address of the class object structure as its ID.
539 // U4: stack trace serial number
540 // ID: class name string ID
Andreas Gampe3a913092015-01-10 00:26:17 -0800541 __ AddU4(nextSerialNumber++);
542 __ AddObjectId(c);
543 __ AddU4(kHprofNullStackTrace);
544 __ AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700545 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700546 }
547
Andreas Gampe3a913092015-01-10 00:26:17 -0800548 void WriteStringTable(EndianOutput* output) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800549 for (const std::pair<std::string, HprofStringId>& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800550 const std::string& string = p.first;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800551 const size_t id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700552
Andreas Gampe3a913092015-01-10 00:26:17 -0800553 output->StartNewRecord(HPROF_TAG_STRING, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700554
555 // STRING format:
556 // ID: ID for this string
557 // U1*: UTF8 characters for string (NOT NULL terminated)
558 // (the record format encodes the length)
Andreas Gampe3a913092015-01-10 00:26:17 -0800559 __ AddU4(id);
560 __ AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700561 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700562 }
563
Andreas Gampe3a913092015-01-10 00:26:17 -0800564 void StartNewHeapDumpSegment(EndianOutput* output) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700565 // This flushes the old segment and starts a new one.
Andreas Gampe3a913092015-01-10 00:26:17 -0800566 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700567 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700568 // Starting a new HEAP_DUMP resets the heap to default.
569 current_heap_ = HPROF_HEAP_DEFAULT;
570 }
571
Andreas Gampe3a913092015-01-10 00:26:17 -0800572 void CheckHeapSegmentConstraints(EndianOutput* output) {
573 if (objects_in_segment_ >= kMaxObjectsPerSegment || output->Length() >= kMaxBytesPerSegment) {
574 StartNewHeapDumpSegment(output);
575 }
576 }
577
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800578 void VisitRoot(const mirror::Object* obj, const RootInfo& root_info, EndianOutput* output)
Andreas Gampe3a913092015-01-10 00:26:17 -0800579 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
580 void MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
581 uint32_t thread_serial, EndianOutput* output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700582
Ian Rogersef7d42f2014-01-06 12:55:46 -0800583 HprofClassObjectId LookupClassId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800584 if (c != nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800585 auto result = classes_.insert(c);
586 const mirror::Class* present = *result.first;
587 CHECK_EQ(present, c);
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800588 // Make sure that we've assigned a string ID for this class' name
589 LookupClassNameId(c);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800590 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800591 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700592 }
593
Ian Rogersef7d42f2014-01-06 12:55:46 -0800594 HprofStringId LookupStringId(mirror::String* string) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700595 return LookupStringId(string->ToModifiedUtf8());
596 }
597
598 HprofStringId LookupStringId(const char* string) {
599 return LookupStringId(std::string(string));
600 }
601
602 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800603 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700604 if (it != strings_.end()) {
605 return it->second;
606 }
607 HprofStringId id = next_string_id_++;
608 strings_.Put(string, id);
609 return id;
610 }
611
Ian Rogersef7d42f2014-01-06 12:55:46 -0800612 HprofStringId LookupClassNameId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700613 return LookupStringId(PrettyDescriptor(c));
614 }
615
Andreas Gampe3a913092015-01-10 00:26:17 -0800616 void WriteFixedHeader(EndianOutput* output) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500617 // Write the file header.
618 // U1: NUL-terminated magic string.
Andreas Gampe3a913092015-01-10 00:26:17 -0800619 const char magic[] = "JAVA PROFILE 1.0.3";
620 __ AddU1List(reinterpret_cast<const uint8_t*>(magic), sizeof(magic));
621
Calin Juravle32805172014-07-04 16:24:03 +0100622 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
623 // as uint32_t.
624 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800625 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
626 "Unexpected HeapReference size");
Andreas Gampe3a913092015-01-10 00:26:17 -0800627 __ AddU4(sizeof(uint32_t));
628
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500629 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700630 timeval now;
Andreas Gampe3a913092015-01-10 00:26:17 -0800631 const uint64_t nowMs = (gettimeofday(&now, nullptr) < 0) ? 0 :
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800632 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Andreas Gampe3a913092015-01-10 00:26:17 -0800633 // TODO: It seems it would be correct to use U8.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500634 // U4: high word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800635 __ AddU4(static_cast<uint32_t>(nowMs >> 32));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500636 // U4: low word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800637 __ AddU4(static_cast<uint32_t>(nowMs & 0xFFFFFFFF));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500638 }
639
Andreas Gampe3a913092015-01-10 00:26:17 -0800640 void WriteStackTraces(EndianOutput* output) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700641 // Write a dummy stack trace record so the analysis tools don't freak out.
Andreas Gampe3a913092015-01-10 00:26:17 -0800642 output->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
643 __ AddU4(kHprofNullStackTrace);
644 __ AddU4(kHprofNullThread);
645 __ AddU4(0); // no frames
646 }
647
648 bool DumpToDdmsBuffered(size_t overall_size ATTRIBUTE_UNUSED, size_t max_length ATTRIBUTE_UNUSED)
649 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
650 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
651 LOG(FATAL) << "Unimplemented";
652 UNREACHABLE();
653 // // Send the data off to DDMS.
654 // iovec iov[2];
655 // iov[0].iov_base = header_data_ptr_;
656 // iov[0].iov_len = header_data_size_;
657 // iov[1].iov_base = body_data_ptr_;
658 // iov[1].iov_len = body_data_size_;
659 // Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
660 }
661
662 bool DumpToFile(size_t overall_size, size_t max_length)
663 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
664 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
665 // Where exactly are we writing to?
666 int out_fd;
667 if (fd_ >= 0) {
668 out_fd = dup(fd_);
669 if (out_fd < 0) {
670 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
671 return false;
672 }
673 } else {
674 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
675 if (out_fd < 0) {
676 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
677 strerror(errno));
678 return false;
679 }
680 }
681
682 std::unique_ptr<File> file(new File(out_fd, filename_, true));
683 bool okay;
684 {
685 FileEndianOutput file_output(file.get(), max_length);
686 ProcessHeap(&file_output, true);
687 okay = !file_output.Errors();
688
689 if (okay) {
690 // Check for expected size.
691 CHECK_EQ(file_output.SumLength(), overall_size);
692 }
693 }
694
695 if (okay) {
696 okay = file->FlushCloseOrErase() == 0;
697 } else {
698 file->Erase();
699 }
700 if (!okay) {
701 std::string msg(StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
702 filename_.c_str(), strerror(errno)));
703 ThrowRuntimeException("%s", msg.c_str());
704 LOG(ERROR) << msg;
705 }
706
707 return okay;
708 }
709
710 bool DumpToDdmsDirect(size_t overall_size, size_t max_length, uint32_t chunk_type)
711 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
712 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
713 CHECK(direct_to_ddms_);
714 JDWP::JdwpState* state = Dbg::GetJdwpState();
715 CHECK(state != nullptr);
716 JDWP::JdwpNetStateBase* net_state = state->netState;
717 CHECK(net_state != nullptr);
718
719 // Hold the socket lock for the whole time since we want this to be atomic.
720 MutexLock mu(Thread::Current(), *net_state->GetSocketLock());
721
722 // Prepare the Ddms chunk.
723 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
724 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
725 state->SetupChunkHeader(chunk_type, overall_size, kChunkHeaderSize, chunk_header);
726
727 // Prepare the output and send the chunk header.
728 NetStateEndianOutput net_output(net_state, max_length);
729 net_output.AddU1List(chunk_header, kChunkHeaderSize);
730
731 // Write the dump.
732 ProcessHeap(&net_output, true);
733
734 // Check for expected size.
735 CHECK_EQ(net_output.SumLength(), overall_size + kChunkHeaderSize);
736
737 return true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700738 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500739
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700740 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
741 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
742 // only be used for debug messages.
743 std::string filename_;
744 int fd_;
745 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500746
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700747 uint64_t start_ns_;
748
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700749 HprofHeapId current_heap_; // Which heap we're currently dumping.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700750 size_t objects_in_segment_;
751
Ian Rogersef7d42f2014-01-06 12:55:46 -0800752 std::set<mirror::Class*> classes_;
753 HprofStringId next_string_id_;
754 SafeMap<std::string, HprofStringId> strings_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700755
756 DISALLOW_COPY_AND_ASSIGN(Hprof);
757};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500758
Andreas Gampe3a913092015-01-10 00:26:17 -0800759static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* size_out) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500760 char c = sig[0];
761 HprofBasicType ret;
762 size_t size;
763
764 switch (c) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800765 case '[':
766 case 'L':
767 ret = hprof_basic_object;
768 size = 4;
769 break;
770 case 'Z':
771 ret = hprof_basic_boolean;
772 size = 1;
773 break;
774 case 'C':
775 ret = hprof_basic_char;
776 size = 2;
777 break;
778 case 'F':
779 ret = hprof_basic_float;
780 size = 4;
781 break;
782 case 'D':
783 ret = hprof_basic_double;
784 size = 8;
785 break;
786 case 'B':
787 ret = hprof_basic_byte;
788 size = 1;
789 break;
790 case 'S':
791 ret = hprof_basic_short;
792 size = 2;
793 break;
794 case 'I':
795 ret = hprof_basic_int;
796 size = 4;
797 break;
798 case 'J':
799 ret = hprof_basic_long;
800 size = 8;
801 break;
802 default:
803 LOG(FATAL) << "UNREACHABLE";
804 UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500805 }
806
Andreas Gampe3a913092015-01-10 00:26:17 -0800807 if (size_out != nullptr) {
808 *size_out = size;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500809 }
810
811 return ret;
812}
813
814// Always called when marking objects, but only does
815// something when ctx->gc_scan_state_ is non-zero, which is usually
816// only true when marking the root set or unreachable
817// objects. Used to add rootset references to obj.
Andreas Gampe3a913092015-01-10 00:26:17 -0800818void Hprof::MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
819 uint32_t thread_serial, EndianOutput* output) {
820 if (heap_tag == 0) {
821 return;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500822 }
823
Andreas Gampe3a913092015-01-10 00:26:17 -0800824 CheckHeapSegmentConstraints(output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500825
Andreas Gampe3a913092015-01-10 00:26:17 -0800826 switch (heap_tag) {
827 // ID: object ID
828 case HPROF_ROOT_UNKNOWN:
829 case HPROF_ROOT_STICKY_CLASS:
830 case HPROF_ROOT_MONITOR_USED:
831 case HPROF_ROOT_INTERNED_STRING:
832 case HPROF_ROOT_DEBUGGER:
833 case HPROF_ROOT_VM_INTERNAL:
834 __ AddU1(heap_tag);
835 __ AddObjectId(obj);
836 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500837
Andreas Gampe3a913092015-01-10 00:26:17 -0800838 // ID: object ID
839 // ID: JNI global ref ID
840 case HPROF_ROOT_JNI_GLOBAL:
841 __ AddU1(heap_tag);
842 __ AddObjectId(obj);
843 __ AddJniGlobalRefId(jni_obj);
844 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500845
Andreas Gampe3a913092015-01-10 00:26:17 -0800846 // ID: object ID
847 // U4: thread serial number
848 // U4: frame number in stack trace (-1 for empty)
849 case HPROF_ROOT_JNI_LOCAL:
850 case HPROF_ROOT_JNI_MONITOR:
851 case HPROF_ROOT_JAVA_FRAME:
852 __ AddU1(heap_tag);
853 __ AddObjectId(obj);
854 __ AddU4(thread_serial);
855 __ AddU4((uint32_t)-1);
856 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500857
Andreas Gampe3a913092015-01-10 00:26:17 -0800858 // ID: object ID
859 // U4: thread serial number
860 case HPROF_ROOT_NATIVE_STACK:
861 case HPROF_ROOT_THREAD_BLOCK:
862 __ AddU1(heap_tag);
863 __ AddObjectId(obj);
864 __ AddU4(thread_serial);
865 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500866
Andreas Gampe3a913092015-01-10 00:26:17 -0800867 // ID: thread object ID
868 // U4: thread serial number
869 // U4: stack trace serial number
870 case HPROF_ROOT_THREAD_OBJECT:
871 __ AddU1(heap_tag);
872 __ AddObjectId(obj);
873 __ AddU4(thread_serial);
874 __ AddU4((uint32_t)-1); // xxx
875 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500876
Andreas Gampe3a913092015-01-10 00:26:17 -0800877 case HPROF_CLASS_DUMP:
878 case HPROF_INSTANCE_DUMP:
879 case HPROF_OBJECT_ARRAY_DUMP:
880 case HPROF_PRIMITIVE_ARRAY_DUMP:
881 case HPROF_HEAP_DUMP_INFO:
882 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
883 // Ignored.
884 break;
Elliott Hughes73e66f72012-05-09 09:34:45 -0700885
Andreas Gampe3a913092015-01-10 00:26:17 -0800886 case HPROF_ROOT_FINALIZING:
887 case HPROF_ROOT_REFERENCE_CLEANUP:
888 case HPROF_UNREACHABLE:
889 LOG(FATAL) << "obsolete tag " << static_cast<int>(heap_tag);
890 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500891 }
892
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700893 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500894}
895
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800896static int StackTraceSerialNumber(const mirror::Object* /*obj*/) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800897 return kHprofNullStackTrace;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500898}
899
Andreas Gampe3a913092015-01-10 00:26:17 -0800900void Hprof::DumpHeapObject(mirror::Object* obj, EndianOutput* output) {
901 // Ignore classes that are retired.
902 if (obj->IsClass() && obj->AsClass()->IsRetired()) {
903 return;
904 }
905
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700906 gc::space::ContinuousSpace* space =
907 Runtime::Current()->GetHeap()->FindContinuousSpaceFromObject(obj, true);
908 HprofHeapId heap_type = HPROF_HEAP_APP;
909 if (space != nullptr) {
910 if (space->IsZygoteSpace()) {
911 heap_type = HPROF_HEAP_ZYGOTE;
912 } else if (space->IsImageSpace()) {
913 heap_type = HPROF_HEAP_IMAGE;
914 }
915 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800916 CheckHeapSegmentConstraints(output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500917
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700918 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500919 HprofStringId nameId;
920
921 // This object is in a different heap than the current one.
922 // Emit a HEAP_DUMP_INFO tag to change heaps.
Andreas Gampe3a913092015-01-10 00:26:17 -0800923 __ AddU1(HPROF_HEAP_DUMP_INFO);
924 __ AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700925 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500926 case HPROF_HEAP_APP:
927 nameId = LookupStringId("app");
928 break;
929 case HPROF_HEAP_ZYGOTE:
930 nameId = LookupStringId("zygote");
931 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700932 case HPROF_HEAP_IMAGE:
933 nameId = LookupStringId("image");
934 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500935 default:
936 // Internal error
937 LOG(ERROR) << "Unexpected desiredHeap";
938 nameId = LookupStringId("<ILLEGAL>");
939 break;
940 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800941 __ AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700942 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500943 }
944
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800945 mirror::Class* c = obj->GetClass();
Andreas Gampe3a913092015-01-10 00:26:17 -0800946 if (c == nullptr) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500947 // This object will bother HprofReader, because it has a NULL
948 // class, so just don't dump it. It could be
949 // gDvm.unlinkedJavaLangClass or it could be an object just
950 // allocated which hasn't been initialized yet.
951 } else {
952 if (obj->IsClass()) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800953 DumpHeapClass(obj->AsClass(), output);
Elliott Hughese84278b2012-03-22 10:06:53 -0700954 } else if (c->IsArrayClass()) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800955 DumpHeapArray(obj->AsArray(), c, output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500956 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800957 DumpHeapInstanceObject(obj, c, output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500958 }
959 }
960
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700961 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500962}
963
Andreas Gampe3a913092015-01-10 00:26:17 -0800964void Hprof::DumpHeapClass(mirror::Class* klass, EndianOutput* output) {
965 size_t sFieldCount = klass->NumStaticFields();
966 if (sFieldCount != 0) {
967 int byteLength = sFieldCount * sizeof(JValue); // TODO bogus; fields are packed
968 // Create a byte array to reflect the allocation of the
969 // StaticField array at the end of this class.
970 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
971 __ AddClassStaticsId(klass);
972 __ AddU4(StackTraceSerialNumber(klass));
973 __ AddU4(byteLength);
974 __ AddU1(hprof_basic_byte);
975 for (int i = 0; i < byteLength; ++i) {
976 __ AddU1(0);
977 }
978 }
979
980 __ AddU1(HPROF_CLASS_DUMP);
981 __ AddClassId(LookupClassId(klass));
982 __ AddU4(StackTraceSerialNumber(klass));
983 __ AddClassId(LookupClassId(klass->GetSuperClass()));
984 __ AddObjectId(klass->GetClassLoader());
985 __ AddObjectId(nullptr); // no signer
986 __ AddObjectId(nullptr); // no prot domain
987 __ AddObjectId(nullptr); // reserved
988 __ AddObjectId(nullptr); // reserved
989 if (klass->IsClassClass()) {
990 // ClassObjects have their static fields appended, so aren't all the same size.
991 // But they're at least this size.
992 __ AddU4(sizeof(mirror::Class)); // instance size
993 } else if (klass->IsArrayClass() || klass->IsPrimitive()) {
994 __ AddU4(0);
995 } else {
996 __ AddU4(klass->GetObjectSize()); // instance size
997 }
998
999 __ AddU2(0); // empty const pool
1000
1001 // Static fields
1002 if (sFieldCount == 0) {
1003 __ AddU2((uint16_t)0);
1004 } else {
1005 __ AddU2((uint16_t)(sFieldCount+1));
1006 __ AddStringId(LookupStringId(kStaticOverheadName));
1007 __ AddU1(hprof_basic_object);
1008 __ AddClassStaticsId(klass);
1009
1010 for (size_t i = 0; i < sFieldCount; ++i) {
1011 mirror::ArtField* f = klass->GetStaticField(i);
1012
1013 size_t size;
1014 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1015 __ AddStringId(LookupStringId(f->GetName()));
1016 __ AddU1(t);
1017 switch (size) {
1018 case 1:
1019 __ AddU1(static_cast<uint8_t>(f->Get32(klass)));
1020 break;
1021 case 2:
1022 __ AddU2(static_cast<uint16_t>(f->Get32(klass)));
1023 break;
1024 case 4:
1025 __ AddU4(f->Get32(klass));
1026 break;
1027 case 8:
1028 __ AddU8(f->Get64(klass));
1029 break;
1030 default:
1031 LOG(FATAL) << "Unexpected size " << size;
1032 UNREACHABLE();
1033 }
1034 }
1035 }
1036
1037 // Instance fields for this class (no superclass fields)
1038 int iFieldCount = klass->IsObjectClass() ? 0 : klass->NumInstanceFields();
1039 __ AddU2((uint16_t)iFieldCount);
1040 for (int i = 0; i < iFieldCount; ++i) {
1041 mirror::ArtField* f = klass->GetInstanceField(i);
1042 __ AddStringId(LookupStringId(f->GetName()));
1043 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), nullptr);
1044 __ AddU1(t);
1045 }
1046}
1047
1048void Hprof::DumpHeapArray(mirror::Array* obj, mirror::Class* klass, EndianOutput* output) {
1049 uint32_t length = obj->GetLength();
1050
1051 if (obj->IsObjectArray()) {
1052 // obj is an object array.
1053 __ AddU1(HPROF_OBJECT_ARRAY_DUMP);
1054
1055 __ AddObjectId(obj);
1056 __ AddU4(StackTraceSerialNumber(obj));
1057 __ AddU4(length);
1058 __ AddClassId(LookupClassId(klass));
1059
1060 // Dump the elements, which are always objects or NULL.
1061 __ AddIdList(obj->AsObjectArray<mirror::Object>());
1062 } else {
1063 size_t size;
1064 HprofBasicType t = SignatureToBasicTypeAndSize(
1065 Primitive::Descriptor(klass->GetComponentType()->GetPrimitiveType()), &size);
1066
1067 // obj is a primitive array.
1068 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1069
1070 __ AddObjectId(obj);
1071 __ AddU4(StackTraceSerialNumber(obj));
1072 __ AddU4(length);
1073 __ AddU1(t);
1074
1075 // Dump the raw, packed element values.
1076 if (size == 1) {
1077 __ AddU1List(reinterpret_cast<const uint8_t*>(obj->GetRawData(sizeof(uint8_t), 0)), length);
1078 } else if (size == 2) {
1079 __ AddU2List(reinterpret_cast<const uint16_t*>(obj->GetRawData(sizeof(uint16_t), 0)), length);
1080 } else if (size == 4) {
1081 __ AddU4List(reinterpret_cast<const uint32_t*>(obj->GetRawData(sizeof(uint32_t), 0)), length);
1082 } else if (size == 8) {
1083 __ AddU8List(reinterpret_cast<const uint64_t*>(obj->GetRawData(sizeof(uint64_t), 0)), length);
1084 }
1085 }
1086}
1087
1088void Hprof::DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass,
1089 EndianOutput* output) {
1090 // obj is an instance object.
1091 __ AddU1(HPROF_INSTANCE_DUMP);
1092 __ AddObjectId(obj);
1093 __ AddU4(StackTraceSerialNumber(obj));
1094 __ AddClassId(LookupClassId(klass));
1095
1096 // Reserve some space for the length of the instance data, which we won't
1097 // know until we're done writing it.
1098 size_t size_patch_offset = output->Length();
1099 __ AddU4(0x77777777);
1100
1101 // Write the instance data; fields for this class, followed by super class fields,
1102 // and so on. Don't write the klass or monitor fields of Object.class.
1103 while (!klass->IsObjectClass()) {
1104 int ifieldCount = klass->NumInstanceFields();
1105 for (int i = 0; i < ifieldCount; ++i) {
1106 mirror::ArtField* f = klass->GetInstanceField(i);
1107 size_t size;
1108 SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1109 if (size == 1) {
1110 __ AddU1(f->Get32(obj));
1111 } else if (size == 2) {
1112 __ AddU2(f->Get32(obj));
1113 } else if (size == 4) {
1114 __ AddU4(f->Get32(obj));
1115 } else {
1116 CHECK_EQ(size, 8U);
1117 __ AddU8(f->Get64(obj));
1118 }
1119 }
1120
1121 klass = klass->GetSuperClass();
1122 }
1123
1124 // Patch the instance field length.
1125 __ UpdateU4(size_patch_offset, output->Length() - (size_patch_offset + 4));
1126}
1127
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001128void Hprof::VisitRoot(const mirror::Object* obj, const RootInfo& info, EndianOutput* output) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001129 static const HprofHeapTag xlate[] = {
1130 HPROF_ROOT_UNKNOWN,
1131 HPROF_ROOT_JNI_GLOBAL,
1132 HPROF_ROOT_JNI_LOCAL,
1133 HPROF_ROOT_JAVA_FRAME,
1134 HPROF_ROOT_NATIVE_STACK,
1135 HPROF_ROOT_STICKY_CLASS,
1136 HPROF_ROOT_THREAD_BLOCK,
1137 HPROF_ROOT_MONITOR_USED,
1138 HPROF_ROOT_THREAD_OBJECT,
1139 HPROF_ROOT_INTERNED_STRING,
1140 HPROF_ROOT_FINALIZING,
1141 HPROF_ROOT_DEBUGGER,
1142 HPROF_ROOT_REFERENCE_CLEANUP,
1143 HPROF_ROOT_VM_INTERNAL,
1144 HPROF_ROOT_JNI_MONITOR,
1145 };
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001146 CHECK_LT(info.GetType(), sizeof(xlate) / sizeof(HprofHeapTag));
Andreas Gampe3a913092015-01-10 00:26:17 -08001147 if (obj == nullptr) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001148 return;
1149 }
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001150 MarkRootObject(obj, 0, xlate[info.GetType()], info.GetThreadId(), output);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001151}
1152
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001153// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1154// sent directly to DDMS.
1155// If "fd" is >= 0, the output will be written to that file descriptor.
1156// Otherwise, "filename" is used to create an output file.
1157void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001158 CHECK(filename != nullptr);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001159
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001160 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001161 Hprof hprof(filename, fd, direct_to_ddms);
1162 hprof.Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001163 Runtime::Current()->GetThreadList()->ResumeAll();
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001164}
1165
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001166} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001167} // namespace art