blob: 656569cb66b96ac4a6d03514679d14eaa4511ccc [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 // First pass to measure the size of the dump.
425 size_t overall_size;
426 size_t max_length;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800427 {
Andreas Gampe3a913092015-01-10 00:26:17 -0800428 EndianOutput count_output;
429 ProcessHeap(&count_output, false);
430 overall_size = count_output.SumLength();
431 max_length = count_output.MaxLength();
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800432 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700433
Andreas Gampe3a913092015-01-10 00:26:17 -0800434 bool okay;
435 if (direct_to_ddms_) {
436 if (kDirectStream) {
437 okay = DumpToDdmsDirect(overall_size, max_length, CHUNK_TYPE("HPDS"));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700438 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800439 okay = DumpToDdmsBuffered(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700440 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800441 } else {
442 okay = DumpToFile(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700443 }
444
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700445 if (okay) {
446 uint64_t duration = NanoTime() - start_ns_;
Ian Rogers50b35e22012-10-04 10:09:15 -0700447 LOG(INFO) << "hprof: heap dump completed ("
Andreas Gampe3a913092015-01-10 00:26:17 -0800448 << PrettySize(RoundUp(overall_size, 1024))
Ian Rogers50b35e22012-10-04 10:09:15 -0700449 << ") in " << PrettyDuration(duration);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700450 }
451 }
452
453 private:
Andreas Gampe3a913092015-01-10 00:26:17 -0800454 struct Env {
455 Hprof* hprof;
456 EndianOutput* output;
457 };
458
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800459 static void RootVisitor(mirror::Object** obj, void* arg, const RootInfo& root_info)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700460 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800461 DCHECK(arg != nullptr);
462 DCHECK(obj != nullptr);
463 DCHECK(*obj != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800464 Env* env = reinterpret_cast<Env*>(arg);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800465 env->hprof->VisitRoot(*obj, root_info, env->output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700466 }
467
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800468 static void VisitObjectCallback(mirror::Object* obj, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700469 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800470 DCHECK(obj != nullptr);
471 DCHECK(arg != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800472 Env* env = reinterpret_cast<Env*>(arg);
473 env->hprof->DumpHeapObject(obj, env->output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700474 }
475
Andreas Gampe3a913092015-01-10 00:26:17 -0800476 void DumpHeapObject(mirror::Object* obj, EndianOutput* output)
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800477 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700478
Andreas Gampe3a913092015-01-10 00:26:17 -0800479 void DumpHeapClass(mirror::Class* klass, EndianOutput* output)
480 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700481
Andreas Gampe3a913092015-01-10 00:26:17 -0800482 void DumpHeapArray(mirror::Array* obj, mirror::Class* klass, EndianOutput* output)
483 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
484
485 void DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass, EndianOutput* output)
486 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
487
488 void ProcessHeap(EndianOutput* output, bool header_first)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800489 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800490 // Reset current heap and object count.
491 current_heap_ = HPROF_HEAP_DEFAULT;
492 objects_in_segment_ = 0;
493
494 if (header_first) {
495 ProcessHeader(output);
496 ProcessBody(output);
497 } else {
498 ProcessBody(output);
499 ProcessHeader(output);
500 }
501 }
502
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800503 void ProcessBody(EndianOutput* output) EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800504 Runtime* runtime = Runtime::Current();
505 // Walk the roots and the heap.
506 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
507
508 Env env = { this, output };
509 runtime->VisitRoots(RootVisitor, &env);
Mathieu Chartier461687d2015-03-31 12:05:24 -0700510 runtime->VisitImageRoots(RootVisitor, &env);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800511 runtime->GetHeap()->VisitObjectsPaused(VisitObjectCallback, &env);
Andreas Gampe3a913092015-01-10 00:26:17 -0800512
513 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_END, kHprofTime);
514 output->EndRecord();
515 }
516
517 void ProcessHeader(EndianOutput* output) EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
518 // Write the header.
519 WriteFixedHeader(output);
520 // Write the string and class tables, and any stack traces, to the header.
521 // (jhat requires that these appear before any of the data in the body that refers to them.)
522 WriteStringTable(output);
523 WriteClassTable(output);
524 WriteStackTraces(output);
525 output->EndRecord();
526 }
527
528 void WriteClassTable(EndianOutput* output) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700529 uint32_t nextSerialNumber = 1;
530
Ian Rogersef7d42f2014-01-06 12:55:46 -0800531 for (mirror::Class* c : classes_) {
532 CHECK(c != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800533 output->StartNewRecord(HPROF_TAG_LOAD_CLASS, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700534 // LOAD CLASS format:
535 // U4: class serial number (always > 0)
536 // ID: class object ID. We use the address of the class object structure as its ID.
537 // U4: stack trace serial number
538 // ID: class name string ID
Andreas Gampe3a913092015-01-10 00:26:17 -0800539 __ AddU4(nextSerialNumber++);
540 __ AddObjectId(c);
541 __ AddU4(kHprofNullStackTrace);
542 __ AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700543 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700544 }
545
Andreas Gampe3a913092015-01-10 00:26:17 -0800546 void WriteStringTable(EndianOutput* output) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800547 for (const std::pair<std::string, HprofStringId>& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800548 const std::string& string = p.first;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800549 const size_t id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700550
Andreas Gampe3a913092015-01-10 00:26:17 -0800551 output->StartNewRecord(HPROF_TAG_STRING, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700552
553 // STRING format:
554 // ID: ID for this string
555 // U1*: UTF8 characters for string (NOT NULL terminated)
556 // (the record format encodes the length)
Andreas Gampe3a913092015-01-10 00:26:17 -0800557 __ AddU4(id);
558 __ AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700559 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700560 }
561
Andreas Gampe3a913092015-01-10 00:26:17 -0800562 void StartNewHeapDumpSegment(EndianOutput* output) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700563 // This flushes the old segment and starts a new one.
Andreas Gampe3a913092015-01-10 00:26:17 -0800564 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700565 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700566 // Starting a new HEAP_DUMP resets the heap to default.
567 current_heap_ = HPROF_HEAP_DEFAULT;
568 }
569
Andreas Gampe3a913092015-01-10 00:26:17 -0800570 void CheckHeapSegmentConstraints(EndianOutput* output) {
571 if (objects_in_segment_ >= kMaxObjectsPerSegment || output->Length() >= kMaxBytesPerSegment) {
572 StartNewHeapDumpSegment(output);
573 }
574 }
575
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800576 void VisitRoot(const mirror::Object* obj, const RootInfo& root_info, EndianOutput* output)
Andreas Gampe3a913092015-01-10 00:26:17 -0800577 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
578 void MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
579 uint32_t thread_serial, EndianOutput* output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700580
Ian Rogersef7d42f2014-01-06 12:55:46 -0800581 HprofClassObjectId LookupClassId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800582 if (c != nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800583 auto result = classes_.insert(c);
584 const mirror::Class* present = *result.first;
585 CHECK_EQ(present, c);
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800586 // Make sure that we've assigned a string ID for this class' name
587 LookupClassNameId(c);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800588 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800589 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700590 }
591
Ian Rogersef7d42f2014-01-06 12:55:46 -0800592 HprofStringId LookupStringId(mirror::String* string) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700593 return LookupStringId(string->ToModifiedUtf8());
594 }
595
596 HprofStringId LookupStringId(const char* string) {
597 return LookupStringId(std::string(string));
598 }
599
600 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800601 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700602 if (it != strings_.end()) {
603 return it->second;
604 }
605 HprofStringId id = next_string_id_++;
606 strings_.Put(string, id);
607 return id;
608 }
609
Ian Rogersef7d42f2014-01-06 12:55:46 -0800610 HprofStringId LookupClassNameId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700611 return LookupStringId(PrettyDescriptor(c));
612 }
613
Andreas Gampe3a913092015-01-10 00:26:17 -0800614 void WriteFixedHeader(EndianOutput* output) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500615 // Write the file header.
616 // U1: NUL-terminated magic string.
Andreas Gampe3a913092015-01-10 00:26:17 -0800617 const char magic[] = "JAVA PROFILE 1.0.3";
618 __ AddU1List(reinterpret_cast<const uint8_t*>(magic), sizeof(magic));
619
Calin Juravle32805172014-07-04 16:24:03 +0100620 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
621 // as uint32_t.
622 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800623 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
624 "Unexpected HeapReference size");
Andreas Gampe3a913092015-01-10 00:26:17 -0800625 __ AddU4(sizeof(uint32_t));
626
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500627 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700628 timeval now;
Andreas Gampe3a913092015-01-10 00:26:17 -0800629 const uint64_t nowMs = (gettimeofday(&now, nullptr) < 0) ? 0 :
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800630 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Andreas Gampe3a913092015-01-10 00:26:17 -0800631 // TODO: It seems it would be correct to use U8.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500632 // U4: high word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800633 __ AddU4(static_cast<uint32_t>(nowMs >> 32));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500634 // U4: low word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800635 __ AddU4(static_cast<uint32_t>(nowMs & 0xFFFFFFFF));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500636 }
637
Andreas Gampe3a913092015-01-10 00:26:17 -0800638 void WriteStackTraces(EndianOutput* output) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700639 // Write a dummy stack trace record so the analysis tools don't freak out.
Andreas Gampe3a913092015-01-10 00:26:17 -0800640 output->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
641 __ AddU4(kHprofNullStackTrace);
642 __ AddU4(kHprofNullThread);
643 __ AddU4(0); // no frames
644 }
645
646 bool DumpToDdmsBuffered(size_t overall_size ATTRIBUTE_UNUSED, size_t max_length ATTRIBUTE_UNUSED)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800647 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800648 LOG(FATAL) << "Unimplemented";
649 UNREACHABLE();
650 // // Send the data off to DDMS.
651 // iovec iov[2];
652 // iov[0].iov_base = header_data_ptr_;
653 // iov[0].iov_len = header_data_size_;
654 // iov[1].iov_base = body_data_ptr_;
655 // iov[1].iov_len = body_data_size_;
656 // Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
657 }
658
659 bool DumpToFile(size_t overall_size, size_t max_length)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800660 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800661 // Where exactly are we writing to?
662 int out_fd;
663 if (fd_ >= 0) {
664 out_fd = dup(fd_);
665 if (out_fd < 0) {
666 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
667 return false;
668 }
669 } else {
670 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
671 if (out_fd < 0) {
672 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
673 strerror(errno));
674 return false;
675 }
676 }
677
678 std::unique_ptr<File> file(new File(out_fd, filename_, true));
679 bool okay;
680 {
681 FileEndianOutput file_output(file.get(), max_length);
682 ProcessHeap(&file_output, true);
683 okay = !file_output.Errors();
684
685 if (okay) {
686 // Check for expected size.
687 CHECK_EQ(file_output.SumLength(), overall_size);
688 }
689 }
690
691 if (okay) {
692 okay = file->FlushCloseOrErase() == 0;
693 } else {
694 file->Erase();
695 }
696 if (!okay) {
697 std::string msg(StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
698 filename_.c_str(), strerror(errno)));
699 ThrowRuntimeException("%s", msg.c_str());
700 LOG(ERROR) << msg;
701 }
702
703 return okay;
704 }
705
706 bool DumpToDdmsDirect(size_t overall_size, size_t max_length, uint32_t chunk_type)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800707 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800708 CHECK(direct_to_ddms_);
709 JDWP::JdwpState* state = Dbg::GetJdwpState();
710 CHECK(state != nullptr);
711 JDWP::JdwpNetStateBase* net_state = state->netState;
712 CHECK(net_state != nullptr);
713
714 // Hold the socket lock for the whole time since we want this to be atomic.
715 MutexLock mu(Thread::Current(), *net_state->GetSocketLock());
716
717 // Prepare the Ddms chunk.
718 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
719 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
720 state->SetupChunkHeader(chunk_type, overall_size, kChunkHeaderSize, chunk_header);
721
722 // Prepare the output and send the chunk header.
723 NetStateEndianOutput net_output(net_state, max_length);
724 net_output.AddU1List(chunk_header, kChunkHeaderSize);
725
726 // Write the dump.
727 ProcessHeap(&net_output, true);
728
729 // Check for expected size.
730 CHECK_EQ(net_output.SumLength(), overall_size + kChunkHeaderSize);
731
732 return true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700733 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500734
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700735 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
736 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
737 // only be used for debug messages.
738 std::string filename_;
739 int fd_;
740 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500741
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700742 uint64_t start_ns_;
743
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700744 HprofHeapId current_heap_; // Which heap we're currently dumping.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700745 size_t objects_in_segment_;
746
Ian Rogersef7d42f2014-01-06 12:55:46 -0800747 std::set<mirror::Class*> classes_;
748 HprofStringId next_string_id_;
749 SafeMap<std::string, HprofStringId> strings_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700750
751 DISALLOW_COPY_AND_ASSIGN(Hprof);
752};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500753
Andreas Gampe3a913092015-01-10 00:26:17 -0800754static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* size_out) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500755 char c = sig[0];
756 HprofBasicType ret;
757 size_t size;
758
759 switch (c) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800760 case '[':
761 case 'L':
762 ret = hprof_basic_object;
763 size = 4;
764 break;
765 case 'Z':
766 ret = hprof_basic_boolean;
767 size = 1;
768 break;
769 case 'C':
770 ret = hprof_basic_char;
771 size = 2;
772 break;
773 case 'F':
774 ret = hprof_basic_float;
775 size = 4;
776 break;
777 case 'D':
778 ret = hprof_basic_double;
779 size = 8;
780 break;
781 case 'B':
782 ret = hprof_basic_byte;
783 size = 1;
784 break;
785 case 'S':
786 ret = hprof_basic_short;
787 size = 2;
788 break;
789 case 'I':
790 ret = hprof_basic_int;
791 size = 4;
792 break;
793 case 'J':
794 ret = hprof_basic_long;
795 size = 8;
796 break;
797 default:
798 LOG(FATAL) << "UNREACHABLE";
799 UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500800 }
801
Andreas Gampe3a913092015-01-10 00:26:17 -0800802 if (size_out != nullptr) {
803 *size_out = size;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500804 }
805
806 return ret;
807}
808
809// Always called when marking objects, but only does
810// something when ctx->gc_scan_state_ is non-zero, which is usually
811// only true when marking the root set or unreachable
812// objects. Used to add rootset references to obj.
Andreas Gampe3a913092015-01-10 00:26:17 -0800813void Hprof::MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
814 uint32_t thread_serial, EndianOutput* output) {
815 if (heap_tag == 0) {
816 return;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500817 }
818
Andreas Gampe3a913092015-01-10 00:26:17 -0800819 CheckHeapSegmentConstraints(output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500820
Andreas Gampe3a913092015-01-10 00:26:17 -0800821 switch (heap_tag) {
822 // ID: object ID
823 case HPROF_ROOT_UNKNOWN:
824 case HPROF_ROOT_STICKY_CLASS:
825 case HPROF_ROOT_MONITOR_USED:
826 case HPROF_ROOT_INTERNED_STRING:
827 case HPROF_ROOT_DEBUGGER:
828 case HPROF_ROOT_VM_INTERNAL:
829 __ AddU1(heap_tag);
830 __ AddObjectId(obj);
831 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500832
Andreas Gampe3a913092015-01-10 00:26:17 -0800833 // ID: object ID
834 // ID: JNI global ref ID
835 case HPROF_ROOT_JNI_GLOBAL:
836 __ AddU1(heap_tag);
837 __ AddObjectId(obj);
838 __ AddJniGlobalRefId(jni_obj);
839 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500840
Andreas Gampe3a913092015-01-10 00:26:17 -0800841 // ID: object ID
842 // U4: thread serial number
843 // U4: frame number in stack trace (-1 for empty)
844 case HPROF_ROOT_JNI_LOCAL:
845 case HPROF_ROOT_JNI_MONITOR:
846 case HPROF_ROOT_JAVA_FRAME:
847 __ AddU1(heap_tag);
848 __ AddObjectId(obj);
849 __ AddU4(thread_serial);
850 __ AddU4((uint32_t)-1);
851 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500852
Andreas Gampe3a913092015-01-10 00:26:17 -0800853 // ID: object ID
854 // U4: thread serial number
855 case HPROF_ROOT_NATIVE_STACK:
856 case HPROF_ROOT_THREAD_BLOCK:
857 __ AddU1(heap_tag);
858 __ AddObjectId(obj);
859 __ AddU4(thread_serial);
860 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500861
Andreas Gampe3a913092015-01-10 00:26:17 -0800862 // ID: thread object ID
863 // U4: thread serial number
864 // U4: stack trace serial number
865 case HPROF_ROOT_THREAD_OBJECT:
866 __ AddU1(heap_tag);
867 __ AddObjectId(obj);
868 __ AddU4(thread_serial);
869 __ AddU4((uint32_t)-1); // xxx
870 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500871
Andreas Gampe3a913092015-01-10 00:26:17 -0800872 case HPROF_CLASS_DUMP:
873 case HPROF_INSTANCE_DUMP:
874 case HPROF_OBJECT_ARRAY_DUMP:
875 case HPROF_PRIMITIVE_ARRAY_DUMP:
876 case HPROF_HEAP_DUMP_INFO:
877 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
878 // Ignored.
879 break;
Elliott Hughes73e66f72012-05-09 09:34:45 -0700880
Andreas Gampe3a913092015-01-10 00:26:17 -0800881 case HPROF_ROOT_FINALIZING:
882 case HPROF_ROOT_REFERENCE_CLEANUP:
883 case HPROF_UNREACHABLE:
884 LOG(FATAL) << "obsolete tag " << static_cast<int>(heap_tag);
885 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500886 }
887
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700888 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500889}
890
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800891static int StackTraceSerialNumber(const mirror::Object* /*obj*/) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800892 return kHprofNullStackTrace;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500893}
894
Andreas Gampe3a913092015-01-10 00:26:17 -0800895void Hprof::DumpHeapObject(mirror::Object* obj, EndianOutput* output) {
896 // Ignore classes that are retired.
897 if (obj->IsClass() && obj->AsClass()->IsRetired()) {
898 return;
899 }
900
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700901 gc::space::ContinuousSpace* space =
902 Runtime::Current()->GetHeap()->FindContinuousSpaceFromObject(obj, true);
903 HprofHeapId heap_type = HPROF_HEAP_APP;
904 if (space != nullptr) {
905 if (space->IsZygoteSpace()) {
906 heap_type = HPROF_HEAP_ZYGOTE;
907 } else if (space->IsImageSpace()) {
908 heap_type = HPROF_HEAP_IMAGE;
909 }
910 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800911 CheckHeapSegmentConstraints(output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500912
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700913 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500914 HprofStringId nameId;
915
916 // This object is in a different heap than the current one.
917 // Emit a HEAP_DUMP_INFO tag to change heaps.
Andreas Gampe3a913092015-01-10 00:26:17 -0800918 __ AddU1(HPROF_HEAP_DUMP_INFO);
919 __ AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700920 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500921 case HPROF_HEAP_APP:
922 nameId = LookupStringId("app");
923 break;
924 case HPROF_HEAP_ZYGOTE:
925 nameId = LookupStringId("zygote");
926 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700927 case HPROF_HEAP_IMAGE:
928 nameId = LookupStringId("image");
929 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500930 default:
931 // Internal error
932 LOG(ERROR) << "Unexpected desiredHeap";
933 nameId = LookupStringId("<ILLEGAL>");
934 break;
935 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800936 __ AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700937 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500938 }
939
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800940 mirror::Class* c = obj->GetClass();
Andreas Gampe3a913092015-01-10 00:26:17 -0800941 if (c == nullptr) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500942 // This object will bother HprofReader, because it has a NULL
943 // class, so just don't dump it. It could be
944 // gDvm.unlinkedJavaLangClass or it could be an object just
945 // allocated which hasn't been initialized yet.
946 } else {
947 if (obj->IsClass()) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800948 DumpHeapClass(obj->AsClass(), output);
Elliott Hughese84278b2012-03-22 10:06:53 -0700949 } else if (c->IsArrayClass()) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800950 DumpHeapArray(obj->AsArray(), c, output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500951 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800952 DumpHeapInstanceObject(obj, c, output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500953 }
954 }
955
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700956 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500957}
958
Andreas Gampe3a913092015-01-10 00:26:17 -0800959void Hprof::DumpHeapClass(mirror::Class* klass, EndianOutput* output) {
960 size_t sFieldCount = klass->NumStaticFields();
961 if (sFieldCount != 0) {
962 int byteLength = sFieldCount * sizeof(JValue); // TODO bogus; fields are packed
963 // Create a byte array to reflect the allocation of the
964 // StaticField array at the end of this class.
965 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
966 __ AddClassStaticsId(klass);
967 __ AddU4(StackTraceSerialNumber(klass));
968 __ AddU4(byteLength);
969 __ AddU1(hprof_basic_byte);
970 for (int i = 0; i < byteLength; ++i) {
971 __ AddU1(0);
972 }
973 }
974
975 __ AddU1(HPROF_CLASS_DUMP);
976 __ AddClassId(LookupClassId(klass));
977 __ AddU4(StackTraceSerialNumber(klass));
978 __ AddClassId(LookupClassId(klass->GetSuperClass()));
979 __ AddObjectId(klass->GetClassLoader());
980 __ AddObjectId(nullptr); // no signer
981 __ AddObjectId(nullptr); // no prot domain
982 __ AddObjectId(nullptr); // reserved
983 __ AddObjectId(nullptr); // reserved
984 if (klass->IsClassClass()) {
985 // ClassObjects have their static fields appended, so aren't all the same size.
986 // But they're at least this size.
987 __ AddU4(sizeof(mirror::Class)); // instance size
988 } else if (klass->IsArrayClass() || klass->IsPrimitive()) {
989 __ AddU4(0);
990 } else {
991 __ AddU4(klass->GetObjectSize()); // instance size
992 }
993
994 __ AddU2(0); // empty const pool
995
996 // Static fields
997 if (sFieldCount == 0) {
998 __ AddU2((uint16_t)0);
999 } else {
1000 __ AddU2((uint16_t)(sFieldCount+1));
1001 __ AddStringId(LookupStringId(kStaticOverheadName));
1002 __ AddU1(hprof_basic_object);
1003 __ AddClassStaticsId(klass);
1004
1005 for (size_t i = 0; i < sFieldCount; ++i) {
1006 mirror::ArtField* f = klass->GetStaticField(i);
1007
1008 size_t size;
1009 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1010 __ AddStringId(LookupStringId(f->GetName()));
1011 __ AddU1(t);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001012 switch (t) {
1013 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001014 __ AddU1(f->GetByte(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001015 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001016 case hprof_basic_boolean:
1017 __ AddU1(f->GetBoolean(klass));
1018 break;
1019 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001020 __ AddU2(f->GetChar(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001021 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001022 case hprof_basic_short:
1023 __ AddU2(f->GetShort(klass));
1024 break;
1025 case hprof_basic_float:
1026 case hprof_basic_int:
1027 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001028 __ AddU4(f->Get32(klass));
1029 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001030 case hprof_basic_double:
1031 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001032 __ AddU8(f->Get64(klass));
1033 break;
1034 default:
1035 LOG(FATAL) << "Unexpected size " << size;
1036 UNREACHABLE();
1037 }
1038 }
1039 }
1040
1041 // Instance fields for this class (no superclass fields)
1042 int iFieldCount = klass->IsObjectClass() ? 0 : klass->NumInstanceFields();
1043 __ AddU2((uint16_t)iFieldCount);
1044 for (int i = 0; i < iFieldCount; ++i) {
1045 mirror::ArtField* f = klass->GetInstanceField(i);
1046 __ AddStringId(LookupStringId(f->GetName()));
1047 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), nullptr);
1048 __ AddU1(t);
1049 }
1050}
1051
1052void Hprof::DumpHeapArray(mirror::Array* obj, mirror::Class* klass, EndianOutput* output) {
1053 uint32_t length = obj->GetLength();
1054
1055 if (obj->IsObjectArray()) {
1056 // obj is an object array.
1057 __ AddU1(HPROF_OBJECT_ARRAY_DUMP);
1058
1059 __ AddObjectId(obj);
1060 __ AddU4(StackTraceSerialNumber(obj));
1061 __ AddU4(length);
1062 __ AddClassId(LookupClassId(klass));
1063
1064 // Dump the elements, which are always objects or NULL.
1065 __ AddIdList(obj->AsObjectArray<mirror::Object>());
1066 } else {
1067 size_t size;
1068 HprofBasicType t = SignatureToBasicTypeAndSize(
1069 Primitive::Descriptor(klass->GetComponentType()->GetPrimitiveType()), &size);
1070
1071 // obj is a primitive array.
1072 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1073
1074 __ AddObjectId(obj);
1075 __ AddU4(StackTraceSerialNumber(obj));
1076 __ AddU4(length);
1077 __ AddU1(t);
1078
1079 // Dump the raw, packed element values.
1080 if (size == 1) {
1081 __ AddU1List(reinterpret_cast<const uint8_t*>(obj->GetRawData(sizeof(uint8_t), 0)), length);
1082 } else if (size == 2) {
1083 __ AddU2List(reinterpret_cast<const uint16_t*>(obj->GetRawData(sizeof(uint16_t), 0)), length);
1084 } else if (size == 4) {
1085 __ AddU4List(reinterpret_cast<const uint32_t*>(obj->GetRawData(sizeof(uint32_t), 0)), length);
1086 } else if (size == 8) {
1087 __ AddU8List(reinterpret_cast<const uint64_t*>(obj->GetRawData(sizeof(uint64_t), 0)), length);
1088 }
1089 }
1090}
1091
1092void Hprof::DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass,
1093 EndianOutput* output) {
1094 // obj is an instance object.
1095 __ AddU1(HPROF_INSTANCE_DUMP);
1096 __ AddObjectId(obj);
1097 __ AddU4(StackTraceSerialNumber(obj));
1098 __ AddClassId(LookupClassId(klass));
1099
1100 // Reserve some space for the length of the instance data, which we won't
1101 // know until we're done writing it.
1102 size_t size_patch_offset = output->Length();
1103 __ AddU4(0x77777777);
1104
1105 // Write the instance data; fields for this class, followed by super class fields,
1106 // and so on. Don't write the klass or monitor fields of Object.class.
1107 while (!klass->IsObjectClass()) {
1108 int ifieldCount = klass->NumInstanceFields();
1109 for (int i = 0; i < ifieldCount; ++i) {
1110 mirror::ArtField* f = klass->GetInstanceField(i);
1111 size_t size;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001112 auto t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1113 switch (t) {
1114 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001115 __ AddU1(f->GetByte(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001116 break;
1117 case hprof_basic_boolean:
1118 __ AddU1(f->GetBoolean(obj));
1119 break;
1120 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001121 __ AddU2(f->GetChar(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001122 break;
1123 case hprof_basic_short:
1124 __ AddU2(f->GetShort(obj));
1125 break;
1126 case hprof_basic_float:
1127 case hprof_basic_int:
1128 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001129 __ AddU4(f->Get32(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001130 break;
1131 case hprof_basic_double:
1132 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001133 __ AddU8(f->Get64(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001134 break;
Andreas Gampe3a913092015-01-10 00:26:17 -08001135 }
1136 }
1137
1138 klass = klass->GetSuperClass();
1139 }
1140
1141 // Patch the instance field length.
1142 __ UpdateU4(size_patch_offset, output->Length() - (size_patch_offset + 4));
1143}
1144
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001145void Hprof::VisitRoot(const mirror::Object* obj, const RootInfo& info, EndianOutput* output) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001146 static const HprofHeapTag xlate[] = {
1147 HPROF_ROOT_UNKNOWN,
1148 HPROF_ROOT_JNI_GLOBAL,
1149 HPROF_ROOT_JNI_LOCAL,
1150 HPROF_ROOT_JAVA_FRAME,
1151 HPROF_ROOT_NATIVE_STACK,
1152 HPROF_ROOT_STICKY_CLASS,
1153 HPROF_ROOT_THREAD_BLOCK,
1154 HPROF_ROOT_MONITOR_USED,
1155 HPROF_ROOT_THREAD_OBJECT,
1156 HPROF_ROOT_INTERNED_STRING,
1157 HPROF_ROOT_FINALIZING,
1158 HPROF_ROOT_DEBUGGER,
1159 HPROF_ROOT_REFERENCE_CLEANUP,
1160 HPROF_ROOT_VM_INTERNAL,
1161 HPROF_ROOT_JNI_MONITOR,
1162 };
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001163 CHECK_LT(info.GetType(), sizeof(xlate) / sizeof(HprofHeapTag));
Andreas Gampe3a913092015-01-10 00:26:17 -08001164 if (obj == nullptr) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001165 return;
1166 }
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001167 MarkRootObject(obj, 0, xlate[info.GetType()], info.GetThreadId(), output);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001168}
1169
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001170// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1171// sent directly to DDMS.
1172// If "fd" is >= 0, the output will be written to that file descriptor.
1173// Otherwise, "filename" is used to create an output file.
1174void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001175 CHECK(filename != nullptr);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001176
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001177 Thread* self = Thread::Current();
1178 gc::Heap* heap = Runtime::Current()->GetHeap();
1179 if (heap->IsGcConcurrentAndMoving()) {
1180 // Need to take a heap dump while GC isn't running. See the
1181 // comment in Heap::VisitObjects().
1182 heap->IncrementDisableMovingGC(self);
1183 }
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001184 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001185 Hprof hprof(filename, fd, direct_to_ddms);
1186 hprof.Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001187 Runtime::Current()->GetThreadList()->ResumeAll();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001188 if (heap->IsGcConcurrentAndMoving()) {
1189 heap->DecrementDisableMovingGC(self);
1190 }
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001191}
1192
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001193} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001194} // namespace art