blob: 133502e6a34c124d4a22c28baba8db15b75a25fc [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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080040#include "android-base/stringprintf.h"
41
Mathieu Chartierc7853442015-03-27 14:35:38 -070042#include "art_field-inl.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080043#include "base/logging.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010044#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080045#include "base/unix_file/fd_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080046#include "class_linker.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080047#include "common_throws.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040048#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070049#include "dex_file-inl.h"
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -080050#include "gc_root.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070051#include "gc/accounting/heap_bitmap.h"
Man Cao8c2ff642015-05-27 17:25:30 -070052#include "gc/allocation_record.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070053#include "gc/heap.h"
54#include "gc/space/space.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070055#include "globals.h"
Mathieu Chartierad466ad2015-01-08 16:28:08 -080056#include "jdwp/jdwp.h"
57#include "jdwp/jdwp_priv.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "mirror/class.h"
59#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/object-inl.h"
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -070061#include "os.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070062#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070063#include "scoped_thread_state_change-inl.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070064#include "thread_list.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040065
66namespace art {
67
68namespace hprof {
69
Mathieu Chartierad466ad2015-01-08 16:28:08 -080070static constexpr bool kDirectStream = true;
Jesse Wilson0c54ac12011-11-09 15:14:05 -050071
Andreas Gampe3a913092015-01-10 00:26:17 -080072static constexpr uint32_t kHprofTime = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -080073static constexpr uint32_t kHprofNullThread = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -070074
Andreas Gampe3a913092015-01-10 00:26:17 -080075static constexpr size_t kMaxObjectsPerSegment = 128;
76static constexpr size_t kMaxBytesPerSegment = 4096;
Elliott Hughes622a6982012-06-08 17:58:54 -070077
Andreas Gampe3a913092015-01-10 00:26:17 -080078// The static field-name for the synthetic object generated to account for class static overhead.
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -070079static constexpr const char* kClassOverheadName = "$classOverhead";
Elliott Hughes622a6982012-06-08 17:58:54 -070080
81enum HprofTag {
82 HPROF_TAG_STRING = 0x01,
83 HPROF_TAG_LOAD_CLASS = 0x02,
84 HPROF_TAG_UNLOAD_CLASS = 0x03,
85 HPROF_TAG_STACK_FRAME = 0x04,
86 HPROF_TAG_STACK_TRACE = 0x05,
87 HPROF_TAG_ALLOC_SITES = 0x06,
88 HPROF_TAG_HEAP_SUMMARY = 0x07,
89 HPROF_TAG_START_THREAD = 0x0A,
90 HPROF_TAG_END_THREAD = 0x0B,
91 HPROF_TAG_HEAP_DUMP = 0x0C,
92 HPROF_TAG_HEAP_DUMP_SEGMENT = 0x1C,
93 HPROF_TAG_HEAP_DUMP_END = 0x2C,
94 HPROF_TAG_CPU_SAMPLES = 0x0D,
95 HPROF_TAG_CONTROL_SETTINGS = 0x0E,
96};
97
98// Values for the first byte of HEAP_DUMP and HEAP_DUMP_SEGMENT records:
99enum HprofHeapTag {
100 // Traditional.
101 HPROF_ROOT_UNKNOWN = 0xFF,
102 HPROF_ROOT_JNI_GLOBAL = 0x01,
103 HPROF_ROOT_JNI_LOCAL = 0x02,
104 HPROF_ROOT_JAVA_FRAME = 0x03,
105 HPROF_ROOT_NATIVE_STACK = 0x04,
106 HPROF_ROOT_STICKY_CLASS = 0x05,
107 HPROF_ROOT_THREAD_BLOCK = 0x06,
108 HPROF_ROOT_MONITOR_USED = 0x07,
109 HPROF_ROOT_THREAD_OBJECT = 0x08,
110 HPROF_CLASS_DUMP = 0x20,
111 HPROF_INSTANCE_DUMP = 0x21,
112 HPROF_OBJECT_ARRAY_DUMP = 0x22,
113 HPROF_PRIMITIVE_ARRAY_DUMP = 0x23,
114
115 // Android.
116 HPROF_HEAP_DUMP_INFO = 0xfe,
117 HPROF_ROOT_INTERNED_STRING = 0x89,
118 HPROF_ROOT_FINALIZING = 0x8a, // Obsolete.
119 HPROF_ROOT_DEBUGGER = 0x8b,
120 HPROF_ROOT_REFERENCE_CLEANUP = 0x8c, // Obsolete.
121 HPROF_ROOT_VM_INTERNAL = 0x8d,
122 HPROF_ROOT_JNI_MONITOR = 0x8e,
123 HPROF_UNREACHABLE = 0x90, // Obsolete.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700124 HPROF_PRIMITIVE_ARRAY_NODATA_DUMP = 0xc3, // Obsolete.
Elliott Hughes622a6982012-06-08 17:58:54 -0700125};
126
127enum HprofHeapId {
128 HPROF_HEAP_DEFAULT = 0,
129 HPROF_HEAP_ZYGOTE = 'Z',
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700130 HPROF_HEAP_APP = 'A',
131 HPROF_HEAP_IMAGE = 'I',
Elliott Hughes622a6982012-06-08 17:58:54 -0700132};
133
134enum HprofBasicType {
135 hprof_basic_object = 2,
136 hprof_basic_boolean = 4,
137 hprof_basic_char = 5,
138 hprof_basic_float = 6,
139 hprof_basic_double = 7,
140 hprof_basic_byte = 8,
141 hprof_basic_short = 9,
142 hprof_basic_int = 10,
143 hprof_basic_long = 11,
144};
145
Ian Rogersef7d42f2014-01-06 12:55:46 -0800146typedef uint32_t HprofStringId;
147typedef uint32_t HprofClassObjectId;
Man Cao8c2ff642015-05-27 17:25:30 -0700148typedef uint32_t HprofClassSerialNumber;
149typedef uint32_t HprofStackTraceSerialNumber;
150typedef uint32_t HprofStackFrameId;
151static constexpr HprofStackTraceSerialNumber kHprofNullStackTrace = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -0700152
Andreas Gampe3a913092015-01-10 00:26:17 -0800153class EndianOutput {
Elliott Hughes622a6982012-06-08 17:58:54 -0700154 public:
Andreas Gampe3a913092015-01-10 00:26:17 -0800155 EndianOutput() : length_(0), sum_length_(0), max_length_(0), started_(false) {}
156 virtual ~EndianOutput() {}
157
158 void StartNewRecord(uint8_t tag, uint32_t time) {
159 if (length_ > 0) {
160 EndRecord();
161 }
162 DCHECK_EQ(length_, 0U);
163 AddU1(tag);
164 AddU4(time);
165 AddU4(0xdeaddead); // Length, replaced on flush.
166 started_ = true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700167 }
168
Andreas Gampe3a913092015-01-10 00:26:17 -0800169 void EndRecord() {
170 // Replace length in header.
171 if (started_) {
172 UpdateU4(sizeof(uint8_t) + sizeof(uint32_t),
173 length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
174 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700175
Andreas Gampe3a913092015-01-10 00:26:17 -0800176 HandleEndRecord();
177
178 sum_length_ += length_;
179 max_length_ = std::max(max_length_, length_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700180 length_ = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -0800181 started_ = false;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700182 }
183
Andreas Gampe3a913092015-01-10 00:26:17 -0800184 void AddU1(uint8_t value) {
185 AddU1List(&value, 1);
186 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800187 void AddU2(uint16_t value) {
188 AddU2List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700189 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800190 void AddU4(uint32_t value) {
191 AddU4List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700192 }
193
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800194 void AddU8(uint64_t value) {
195 AddU8List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700196 }
197
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800198 void AddObjectId(const mirror::Object* value) {
199 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800200 }
201
Man Cao8c2ff642015-05-27 17:25:30 -0700202 void AddStackTraceSerialNumber(HprofStackTraceSerialNumber value) {
203 AddU4(value);
204 }
205
Ian Rogersef7d42f2014-01-06 12:55:46 -0800206 // The ID for the synthetic object generated to account for class static overhead.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800207 void AddClassStaticsId(const mirror::Class* value) {
208 AddU4(1 | PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800209 }
210
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800211 void AddJniGlobalRefId(jobject value) {
212 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800213 }
214
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800215 void AddClassId(HprofClassObjectId value) {
216 AddU4(value);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800217 }
218
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800219 void AddStringId(HprofStringId value) {
220 AddU4(value);
Elliott Hughes622a6982012-06-08 17:58:54 -0700221 }
222
Andreas Gampe3a913092015-01-10 00:26:17 -0800223 void AddU1List(const uint8_t* values, size_t count) {
224 HandleU1List(values, count);
225 length_ += count;
226 }
227 void AddU2List(const uint16_t* values, size_t count) {
228 HandleU2List(values, count);
229 length_ += count * sizeof(uint16_t);
230 }
231 void AddU4List(const uint32_t* values, size_t count) {
232 HandleU4List(values, count);
233 length_ += count * sizeof(uint32_t);
234 }
Andreas Gampeca714582015-04-03 19:41:34 -0700235 virtual void UpdateU4(size_t offset, uint32_t new_value ATTRIBUTE_UNUSED) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800236 DCHECK_LE(offset, length_ - 4);
237 }
238 void AddU8List(const uint64_t* values, size_t count) {
239 HandleU8List(values, count);
240 length_ += count * sizeof(uint64_t);
241 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700242
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800243 void AddIdList(mirror::ObjectArray<mirror::Object>* values)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700244 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800245 const int32_t length = values->GetLength();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800246 for (int32_t i = 0; i < length; ++i) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800247 AddObjectId(values->GetWithoutChecks(i));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800248 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700249 }
250
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800251 void AddUtf8String(const char* str) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700252 // The terminating NUL character is NOT written.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800253 AddU1List((const uint8_t*)str, strlen(str));
Elliott Hughes622a6982012-06-08 17:58:54 -0700254 }
255
Andreas Gampe3a913092015-01-10 00:26:17 -0800256 size_t Length() const {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700257 return length_;
258 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700259
Andreas Gampe3a913092015-01-10 00:26:17 -0800260 size_t SumLength() const {
261 return sum_length_;
Elliott Hughes622a6982012-06-08 17:58:54 -0700262 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700263
Andreas Gampe3a913092015-01-10 00:26:17 -0800264 size_t MaxLength() const {
265 return max_length_;
266 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700267
Andreas Gampe3a913092015-01-10 00:26:17 -0800268 protected:
269 virtual void HandleU1List(const uint8_t* values ATTRIBUTE_UNUSED,
270 size_t count ATTRIBUTE_UNUSED) {
271 }
jessicahandojo3aaa37b2016-07-29 14:46:37 -0700272 virtual void HandleU1AsU2List(const uint8_t* values ATTRIBUTE_UNUSED,
273 size_t count ATTRIBUTE_UNUSED) {
274 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800275 virtual void HandleU2List(const uint16_t* values ATTRIBUTE_UNUSED,
276 size_t count ATTRIBUTE_UNUSED) {
277 }
278 virtual void HandleU4List(const uint32_t* values ATTRIBUTE_UNUSED,
279 size_t count ATTRIBUTE_UNUSED) {
280 }
281 virtual void HandleU8List(const uint64_t* values ATTRIBUTE_UNUSED,
282 size_t count ATTRIBUTE_UNUSED) {
283 }
284 virtual void HandleEndRecord() {
285 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700286
Andreas Gampe3a913092015-01-10 00:26:17 -0800287 size_t length_; // Current record size.
288 size_t sum_length_; // Size of all data.
289 size_t max_length_; // Maximum seen length.
290 bool started_; // Was StartRecord called?
Elliott Hughes622a6982012-06-08 17:58:54 -0700291};
292
Andreas Gampe3a913092015-01-10 00:26:17 -0800293// This keeps things buffered until flushed.
294class EndianOutputBuffered : public EndianOutput {
295 public:
296 explicit EndianOutputBuffered(size_t reserve_size) {
297 buffer_.reserve(reserve_size);
298 }
299 virtual ~EndianOutputBuffered() {}
300
301 void UpdateU4(size_t offset, uint32_t new_value) OVERRIDE {
302 DCHECK_LE(offset, length_ - 4);
303 buffer_[offset + 0] = static_cast<uint8_t>((new_value >> 24) & 0xFF);
304 buffer_[offset + 1] = static_cast<uint8_t>((new_value >> 16) & 0xFF);
305 buffer_[offset + 2] = static_cast<uint8_t>((new_value >> 8) & 0xFF);
306 buffer_[offset + 3] = static_cast<uint8_t>((new_value >> 0) & 0xFF);
307 }
308
309 protected:
310 void HandleU1List(const uint8_t* values, size_t count) OVERRIDE {
311 DCHECK_EQ(length_, buffer_.size());
312 buffer_.insert(buffer_.end(), values, values + count);
313 }
314
jessicahandojo3aaa37b2016-07-29 14:46:37 -0700315 void HandleU1AsU2List(const uint8_t* values, size_t count) OVERRIDE {
316 DCHECK_EQ(length_, buffer_.size());
317 // All 8-bits are grouped in 2 to make 16-bit block like Java Char
318 if (count & 1) {
319 buffer_.push_back(0);
320 }
321 for (size_t i = 0; i < count; ++i) {
322 uint8_t value = *values;
323 buffer_.push_back(value);
324 values++;
325 }
326 }
327
Andreas Gampe3a913092015-01-10 00:26:17 -0800328 void HandleU2List(const uint16_t* values, size_t count) OVERRIDE {
329 DCHECK_EQ(length_, buffer_.size());
330 for (size_t i = 0; i < count; ++i) {
331 uint16_t value = *values;
332 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
333 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
334 values++;
335 }
336 }
337
338 void HandleU4List(const uint32_t* values, size_t count) OVERRIDE {
339 DCHECK_EQ(length_, buffer_.size());
340 for (size_t i = 0; i < count; ++i) {
341 uint32_t value = *values;
342 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
343 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
344 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
345 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
346 values++;
347 }
348 }
349
350 void HandleU8List(const uint64_t* values, size_t count) OVERRIDE {
351 DCHECK_EQ(length_, buffer_.size());
352 for (size_t i = 0; i < count; ++i) {
353 uint64_t value = *values;
354 buffer_.push_back(static_cast<uint8_t>((value >> 56) & 0xFF));
355 buffer_.push_back(static_cast<uint8_t>((value >> 48) & 0xFF));
356 buffer_.push_back(static_cast<uint8_t>((value >> 40) & 0xFF));
357 buffer_.push_back(static_cast<uint8_t>((value >> 32) & 0xFF));
358 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
359 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
360 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
361 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
362 values++;
363 }
364 }
365
366 void HandleEndRecord() OVERRIDE {
367 DCHECK_EQ(buffer_.size(), length_);
368 if (kIsDebugBuild && started_) {
369 uint32_t stored_length =
370 static_cast<uint32_t>(buffer_[5]) << 24 |
371 static_cast<uint32_t>(buffer_[6]) << 16 |
372 static_cast<uint32_t>(buffer_[7]) << 8 |
373 static_cast<uint32_t>(buffer_[8]);
374 DCHECK_EQ(stored_length, length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
375 }
376 HandleFlush(buffer_.data(), length_);
377 buffer_.clear();
378 }
379
380 virtual void HandleFlush(const uint8_t* buffer ATTRIBUTE_UNUSED, size_t length ATTRIBUTE_UNUSED) {
381 }
382
383 std::vector<uint8_t> buffer_;
384};
385
386class FileEndianOutput FINAL : public EndianOutputBuffered {
387 public:
388 FileEndianOutput(File* fp, size_t reserved_size)
389 : EndianOutputBuffered(reserved_size), fp_(fp), errors_(false) {
390 DCHECK(fp != nullptr);
391 }
392 ~FileEndianOutput() {
393 }
394
395 bool Errors() {
396 return errors_;
397 }
398
399 protected:
400 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
401 if (!errors_) {
402 errors_ = !fp_->WriteFully(buffer, length);
403 }
404 }
405
406 private:
407 File* fp_;
408 bool errors_;
409};
410
411class NetStateEndianOutput FINAL : public EndianOutputBuffered {
412 public:
413 NetStateEndianOutput(JDWP::JdwpNetStateBase* net_state, size_t reserved_size)
414 : EndianOutputBuffered(reserved_size), net_state_(net_state) {
415 DCHECK(net_state != nullptr);
416 }
417 ~NetStateEndianOutput() {}
418
419 protected:
420 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
421 std::vector<iovec> iov;
422 iov.push_back(iovec());
423 iov[0].iov_base = const_cast<void*>(reinterpret_cast<const void*>(buffer));
424 iov[0].iov_len = length;
425 net_state_->WriteBufferedPacketLocked(iov);
426 }
427
428 private:
429 JDWP::JdwpNetStateBase* net_state_;
430};
431
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700432#define __ output_->
Andreas Gampe3a913092015-01-10 00:26:17 -0800433
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700434class Hprof : public SingleRootVisitor {
Elliott Hughes622a6982012-06-08 17:58:54 -0700435 public:
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700436 Hprof(const char* output_filename, int fd, bool direct_to_ddms)
437 : filename_(output_filename),
438 fd_(fd),
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800439 direct_to_ddms_(direct_to_ddms) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700440 LOG(INFO) << "hprof: heap dump \"" << filename_ << "\" starting...";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500441 }
442
Andreas Gampe3a913092015-01-10 00:26:17 -0800443 void Dump()
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800444 REQUIRES(Locks::mutator_lock_)
445 REQUIRES(!Locks::heap_bitmap_lock_, !Locks::alloc_tracker_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700446 {
447 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
448 if (Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
449 PopulateAllocationTrackingTraces();
450 }
451 }
452
Andreas Gampe3a913092015-01-10 00:26:17 -0800453 // First pass to measure the size of the dump.
454 size_t overall_size;
455 size_t max_length;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800456 {
Andreas Gampe3a913092015-01-10 00:26:17 -0800457 EndianOutput count_output;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700458 output_ = &count_output;
459 ProcessHeap(false);
Andreas Gampe3a913092015-01-10 00:26:17 -0800460 overall_size = count_output.SumLength();
461 max_length = count_output.MaxLength();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700462 output_ = nullptr;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800463 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700464
Andreas Gampe3a913092015-01-10 00:26:17 -0800465 bool okay;
466 if (direct_to_ddms_) {
467 if (kDirectStream) {
468 okay = DumpToDdmsDirect(overall_size, max_length, CHUNK_TYPE("HPDS"));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700469 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800470 okay = DumpToDdmsBuffered(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700471 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800472 } else {
473 okay = DumpToFile(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700474 }
475
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700476 if (okay) {
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800477 const uint64_t duration = NanoTime() - start_ns_;
478 LOG(INFO) << "hprof: heap dump completed (" << PrettySize(RoundUp(overall_size, KB))
479 << ") in " << PrettyDuration(duration)
480 << " objects " << total_objects_
481 << " objects with stack traces " << total_objects_with_stack_trace_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700482 }
483 }
484
485 private:
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800486 static void VisitObjectCallback(mirror::Object* obj, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700487 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800488 DCHECK(obj != nullptr);
489 DCHECK(arg != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700490 reinterpret_cast<Hprof*>(arg)->DumpHeapObject(obj);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700491 }
492
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700493 void DumpHeapObject(mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700494 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700495
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700496 void DumpHeapClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700497 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700498
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700499 void DumpHeapArray(mirror::Array* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700500 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800501
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700502 void DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700503 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800504
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700505 void ProcessHeap(bool header_first)
Mathieu Chartier90443472015-07-16 20:32:27 -0700506 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800507 // Reset current heap and object count.
508 current_heap_ = HPROF_HEAP_DEFAULT;
509 objects_in_segment_ = 0;
510
511 if (header_first) {
Man Cao8c2ff642015-05-27 17:25:30 -0700512 ProcessHeader(true);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700513 ProcessBody();
Andreas Gampe3a913092015-01-10 00:26:17 -0800514 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700515 ProcessBody();
Man Cao8c2ff642015-05-27 17:25:30 -0700516 ProcessHeader(false);
Andreas Gampe3a913092015-01-10 00:26:17 -0800517 }
518 }
519
Mathieu Chartier90443472015-07-16 20:32:27 -0700520 void ProcessBody() REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700521 Runtime* const runtime = Runtime::Current();
Andreas Gampe3a913092015-01-10 00:26:17 -0800522 // Walk the roots and the heap.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700523 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Andreas Gampe3a913092015-01-10 00:26:17 -0800524
Richard Uhler4b767552016-04-26 13:28:59 -0700525 simple_roots_.clear();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700526 runtime->VisitRoots(this);
527 runtime->VisitImageRoots(this);
528 runtime->GetHeap()->VisitObjectsPaused(VisitObjectCallback, this);
Andreas Gampe3a913092015-01-10 00:26:17 -0800529
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700530 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_END, kHprofTime);
531 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800532 }
533
Mathieu Chartier90443472015-07-16 20:32:27 -0700534 void ProcessHeader(bool string_first) REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800535 // Write the header.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700536 WriteFixedHeader();
Andreas Gampe3a913092015-01-10 00:26:17 -0800537 // Write the string and class tables, and any stack traces, to the header.
538 // (jhat requires that these appear before any of the data in the body that refers to them.)
Man Cao8c2ff642015-05-27 17:25:30 -0700539 // jhat also requires the string table appear before class table and stack traces.
540 // However, WriteStackTraces() can modify the string table, so it's necessary to call
541 // WriteStringTable() last in the first pass, to compute the correct length of the output.
542 if (string_first) {
543 WriteStringTable();
544 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700545 WriteClassTable();
546 WriteStackTraces();
Man Cao8c2ff642015-05-27 17:25:30 -0700547 if (!string_first) {
548 WriteStringTable();
549 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700550 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800551 }
552
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700553 void WriteClassTable() REQUIRES_SHARED(Locks::mutator_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700554 for (const auto& p : classes_) {
555 mirror::Class* c = p.first;
556 HprofClassSerialNumber sn = p.second;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800557 CHECK(c != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700558 output_->StartNewRecord(HPROF_TAG_LOAD_CLASS, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700559 // LOAD CLASS format:
560 // U4: class serial number (always > 0)
561 // ID: class object ID. We use the address of the class object structure as its ID.
562 // U4: stack trace serial number
563 // ID: class name string ID
Man Cao8c2ff642015-05-27 17:25:30 -0700564 __ AddU4(sn);
Andreas Gampe3a913092015-01-10 00:26:17 -0800565 __ AddObjectId(c);
Man Cao8c2ff642015-05-27 17:25:30 -0700566 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(c));
Andreas Gampe3a913092015-01-10 00:26:17 -0800567 __ AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700568 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700569 }
570
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700571 void WriteStringTable() {
Andreas Gampe1eeb00c2016-11-03 08:19:01 -0700572 for (const auto& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800573 const std::string& string = p.first;
Andreas Gampe1eeb00c2016-11-03 08:19:01 -0700574 const HprofStringId id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700575
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700576 output_->StartNewRecord(HPROF_TAG_STRING, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700577
578 // STRING format:
579 // ID: ID for this string
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700580 // U1*: UTF8 characters for string (NOT null terminated)
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700581 // (the record format encodes the length)
Andreas Gampe3a913092015-01-10 00:26:17 -0800582 __ AddU4(id);
583 __ AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700584 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700585 }
586
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700587 void StartNewHeapDumpSegment() {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700588 // This flushes the old segment and starts a new one.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700589 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700590 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700591 // Starting a new HEAP_DUMP resets the heap to default.
592 current_heap_ = HPROF_HEAP_DEFAULT;
593 }
594
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700595 void CheckHeapSegmentConstraints() {
596 if (objects_in_segment_ >= kMaxObjectsPerSegment || output_->Length() >= kMaxBytesPerSegment) {
597 StartNewHeapDumpSegment();
Andreas Gampe3a913092015-01-10 00:26:17 -0800598 }
599 }
600
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700601 void VisitRoot(mirror::Object* obj, const RootInfo& root_info)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700602 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800603 void MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700604 uint32_t thread_serial);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700605
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700606 HprofClassObjectId LookupClassId(mirror::Class* c) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800607 if (c != nullptr) {
Man Cao8c2ff642015-05-27 17:25:30 -0700608 auto it = classes_.find(c);
609 if (it == classes_.end()) {
610 // first time to see this class
611 HprofClassSerialNumber sn = next_class_serial_number_++;
612 classes_.Put(c, sn);
613 // Make sure that we've assigned a string ID for this class' name
614 LookupClassNameId(c);
615 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800616 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800617 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700618 }
619
Man Cao8c2ff642015-05-27 17:25:30 -0700620 HprofStackTraceSerialNumber LookupStackTraceSerialNumber(const mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700621 REQUIRES_SHARED(Locks::mutator_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700622 auto r = allocation_records_.find(obj);
623 if (r == allocation_records_.end()) {
624 return kHprofNullStackTrace;
625 } else {
626 const gc::AllocRecordStackTrace* trace = r->second;
627 auto result = traces_.find(trace);
628 CHECK(result != traces_.end());
629 return result->second;
630 }
631 }
632
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700633 HprofStringId LookupStringId(mirror::String* string) REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700634 return LookupStringId(string->ToModifiedUtf8());
635 }
636
637 HprofStringId LookupStringId(const char* string) {
638 return LookupStringId(std::string(string));
639 }
640
641 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800642 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700643 if (it != strings_.end()) {
644 return it->second;
645 }
646 HprofStringId id = next_string_id_++;
647 strings_.Put(string, id);
648 return id;
649 }
650
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700651 HprofStringId LookupClassNameId(mirror::Class* c) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700652 return LookupStringId(c->PrettyDescriptor());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700653 }
654
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700655 void WriteFixedHeader() {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500656 // Write the file header.
657 // U1: NUL-terminated magic string.
Andreas Gampe3a913092015-01-10 00:26:17 -0800658 const char magic[] = "JAVA PROFILE 1.0.3";
659 __ AddU1List(reinterpret_cast<const uint8_t*>(magic), sizeof(magic));
660
Calin Juravle32805172014-07-04 16:24:03 +0100661 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
662 // as uint32_t.
663 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800664 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
665 "Unexpected HeapReference size");
Andreas Gampe3a913092015-01-10 00:26:17 -0800666 __ AddU4(sizeof(uint32_t));
667
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500668 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700669 timeval now;
Andreas Gampe3a913092015-01-10 00:26:17 -0800670 const uint64_t nowMs = (gettimeofday(&now, nullptr) < 0) ? 0 :
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800671 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Andreas Gampe3a913092015-01-10 00:26:17 -0800672 // TODO: It seems it would be correct to use U8.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500673 // U4: high word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800674 __ AddU4(static_cast<uint32_t>(nowMs >> 32));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500675 // U4: low word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800676 __ AddU4(static_cast<uint32_t>(nowMs & 0xFFFFFFFF));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500677 }
678
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700679 void WriteStackTraces() REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700680 // Write a dummy stack trace record so the analysis tools don't freak out.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700681 output_->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
Man Cao8c2ff642015-05-27 17:25:30 -0700682 __ AddStackTraceSerialNumber(kHprofNullStackTrace);
Andreas Gampe3a913092015-01-10 00:26:17 -0800683 __ AddU4(kHprofNullThread);
684 __ AddU4(0); // no frames
Man Cao8c2ff642015-05-27 17:25:30 -0700685
686 // TODO: jhat complains "WARNING: Stack trace not found for serial # -1", but no trace should
687 // have -1 as its serial number (as long as HprofStackTraceSerialNumber doesn't overflow).
688 for (const auto& it : traces_) {
689 const gc::AllocRecordStackTrace* trace = it.first;
690 HprofStackTraceSerialNumber trace_sn = it.second;
691 size_t depth = trace->GetDepth();
692
693 // First write stack frames of the trace
694 for (size_t i = 0; i < depth; ++i) {
695 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
696 ArtMethod* method = frame->GetMethod();
697 CHECK(method != nullptr);
698 output_->StartNewRecord(HPROF_TAG_STACK_FRAME, kHprofTime);
699 // STACK FRAME format:
700 // ID: stack frame ID. We use the address of the AllocRecordStackTraceElement object as its ID.
701 // ID: method name string ID
702 // ID: method signature string ID
703 // ID: source file name string ID
704 // U4: class serial number
705 // U4: >0, line number; 0, no line information available; -1, unknown location
706 auto frame_result = frames_.find(frame);
707 CHECK(frame_result != frames_.end());
708 __ AddU4(frame_result->second);
709 __ AddStringId(LookupStringId(method->GetName()));
710 __ AddStringId(LookupStringId(method->GetSignature().ToString()));
711 const char* source_file = method->GetDeclaringClassSourceFile();
712 if (source_file == nullptr) {
713 source_file = "";
714 }
715 __ AddStringId(LookupStringId(source_file));
716 auto class_result = classes_.find(method->GetDeclaringClass());
717 CHECK(class_result != classes_.end());
718 __ AddU4(class_result->second);
719 __ AddU4(frame->ComputeLineNumber());
720 }
721
722 // Then write the trace itself
723 output_->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
724 // STACK TRACE format:
725 // U4: stack trace serial number. We use the address of the AllocRecordStackTrace object as its serial number.
726 // U4: thread serial number. We use Thread::GetTid().
727 // U4: number of frames
728 // [ID]*: series of stack frame ID's
729 __ AddStackTraceSerialNumber(trace_sn);
730 __ AddU4(trace->GetTid());
731 __ AddU4(depth);
732 for (size_t i = 0; i < depth; ++i) {
733 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
734 auto frame_result = frames_.find(frame);
735 CHECK(frame_result != frames_.end());
736 __ AddU4(frame_result->second);
737 }
738 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800739 }
740
741 bool DumpToDdmsBuffered(size_t overall_size ATTRIBUTE_UNUSED, size_t max_length ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700742 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800743 LOG(FATAL) << "Unimplemented";
744 UNREACHABLE();
745 // // Send the data off to DDMS.
746 // iovec iov[2];
747 // iov[0].iov_base = header_data_ptr_;
748 // iov[0].iov_len = header_data_size_;
749 // iov[1].iov_base = body_data_ptr_;
750 // iov[1].iov_len = body_data_size_;
751 // Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
752 }
753
754 bool DumpToFile(size_t overall_size, size_t max_length)
Mathieu Chartier90443472015-07-16 20:32:27 -0700755 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800756 // Where exactly are we writing to?
757 int out_fd;
758 if (fd_ >= 0) {
759 out_fd = dup(fd_);
760 if (out_fd < 0) {
761 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
762 return false;
763 }
764 } else {
765 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
766 if (out_fd < 0) {
767 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
768 strerror(errno));
769 return false;
770 }
771 }
772
773 std::unique_ptr<File> file(new File(out_fd, filename_, true));
774 bool okay;
775 {
776 FileEndianOutput file_output(file.get(), max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700777 output_ = &file_output;
778 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800779 okay = !file_output.Errors();
780
781 if (okay) {
Andreas Gampec515f212015-08-28 18:15:27 -0700782 // Check for expected size. Output is expected to be less-or-equal than first phase, see
783 // b/23521263.
784 DCHECK_LE(file_output.SumLength(), overall_size);
Andreas Gampe3a913092015-01-10 00:26:17 -0800785 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700786 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800787 }
788
789 if (okay) {
790 okay = file->FlushCloseOrErase() == 0;
791 } else {
792 file->Erase();
793 }
794 if (!okay) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800795 std::string msg(android::base::StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
796 filename_.c_str(),
797 strerror(errno)));
Andreas Gampe3a913092015-01-10 00:26:17 -0800798 ThrowRuntimeException("%s", msg.c_str());
799 LOG(ERROR) << msg;
800 }
801
802 return okay;
803 }
804
805 bool DumpToDdmsDirect(size_t overall_size, size_t max_length, uint32_t chunk_type)
Mathieu Chartier90443472015-07-16 20:32:27 -0700806 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800807 CHECK(direct_to_ddms_);
808 JDWP::JdwpState* state = Dbg::GetJdwpState();
809 CHECK(state != nullptr);
810 JDWP::JdwpNetStateBase* net_state = state->netState;
811 CHECK(net_state != nullptr);
812
813 // Hold the socket lock for the whole time since we want this to be atomic.
814 MutexLock mu(Thread::Current(), *net_state->GetSocketLock());
815
816 // Prepare the Ddms chunk.
817 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
818 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
819 state->SetupChunkHeader(chunk_type, overall_size, kChunkHeaderSize, chunk_header);
820
821 // Prepare the output and send the chunk header.
822 NetStateEndianOutput net_output(net_state, max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700823 output_ = &net_output;
Andreas Gampe3a913092015-01-10 00:26:17 -0800824 net_output.AddU1List(chunk_header, kChunkHeaderSize);
825
826 // Write the dump.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700827 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800828
Andreas Gampec515f212015-08-28 18:15:27 -0700829 // Check for expected size. See DumpToFile for comment.
830 DCHECK_LE(net_output.SumLength(), overall_size + kChunkHeaderSize);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700831 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800832
833 return true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700834 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500835
Man Cao8c2ff642015-05-27 17:25:30 -0700836 void PopulateAllocationTrackingTraces()
Mathieu Chartier90443472015-07-16 20:32:27 -0700837 REQUIRES(Locks::mutator_lock_, Locks::alloc_tracker_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700838 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
839 CHECK(records != nullptr);
840 HprofStackTraceSerialNumber next_trace_sn = kHprofNullStackTrace + 1;
841 HprofStackFrameId next_frame_id = 0;
Man Cao42c3c332015-06-23 16:38:25 -0700842 size_t count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -0700843
844 for (auto it = records->Begin(), end = records->End(); it != end; ++it) {
845 const mirror::Object* obj = it->first.Read();
Man Cao42c3c332015-06-23 16:38:25 -0700846 if (obj == nullptr) {
847 continue;
848 }
849 ++count;
Mathieu Chartier458b1052016-03-29 14:02:55 -0700850 const gc::AllocRecordStackTrace* trace = it->second.GetStackTrace();
Man Cao8c2ff642015-05-27 17:25:30 -0700851
852 // Copy the pair into a real hash map to speed up look up.
853 auto records_result = allocation_records_.emplace(obj, trace);
854 // The insertion should always succeed, i.e. no duplicate object pointers in "records"
855 CHECK(records_result.second);
856
857 // Generate serial numbers for traces, and IDs for frames.
858 auto traces_result = traces_.find(trace);
859 if (traces_result == traces_.end()) {
860 traces_.emplace(trace, next_trace_sn++);
861 // only check frames if the trace is newly discovered
862 for (size_t i = 0, depth = trace->GetDepth(); i < depth; ++i) {
863 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
864 auto frames_result = frames_.find(frame);
865 if (frames_result == frames_.end()) {
866 frames_.emplace(frame, next_frame_id++);
867 }
868 }
869 }
870 }
871 CHECK_EQ(traces_.size(), next_trace_sn - kHprofNullStackTrace - 1);
872 CHECK_EQ(frames_.size(), next_frame_id);
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800873 total_objects_with_stack_trace_ = count;
Man Cao8c2ff642015-05-27 17:25:30 -0700874 }
875
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700876 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
877 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
878 // only be used for debug messages.
879 std::string filename_;
880 int fd_;
881 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500882
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800883 uint64_t start_ns_ = NanoTime();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700884
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800885 EndianOutput* output_ = nullptr;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700886
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800887 HprofHeapId current_heap_ = HPROF_HEAP_DEFAULT; // Which heap we're currently dumping.
888 size_t objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700889
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800890 size_t total_objects_ = 0u;
891 size_t total_objects_with_stack_trace_ = 0u;
892
893 HprofStringId next_string_id_ = 0x400000;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800894 SafeMap<std::string, HprofStringId> strings_;
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800895 HprofClassSerialNumber next_class_serial_number_ = 1;
Man Cao8c2ff642015-05-27 17:25:30 -0700896 SafeMap<mirror::Class*, HprofClassSerialNumber> classes_;
897
898 std::unordered_map<const gc::AllocRecordStackTrace*, HprofStackTraceSerialNumber,
899 gc::HashAllocRecordTypesPtr<gc::AllocRecordStackTrace>,
900 gc::EqAllocRecordTypesPtr<gc::AllocRecordStackTrace>> traces_;
901 std::unordered_map<const gc::AllocRecordStackTraceElement*, HprofStackFrameId,
902 gc::HashAllocRecordTypesPtr<gc::AllocRecordStackTraceElement>,
903 gc::EqAllocRecordTypesPtr<gc::AllocRecordStackTraceElement>> frames_;
904 std::unordered_map<const mirror::Object*, const gc::AllocRecordStackTrace*> allocation_records_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700905
Richard Uhler4b767552016-04-26 13:28:59 -0700906 // Set used to keep track of what simple root records we have already
907 // emitted, to avoid emitting duplicate entries. The simple root records are
908 // those that contain no other information than the root type and the object
909 // id. A pair of root type and object id is packed into a uint64_t, with
910 // the root type in the upper 32 bits and the object id in the lower 32
911 // bits.
912 std::unordered_set<uint64_t> simple_roots_;
913
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700914 friend class GcRootVisitor;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700915 DISALLOW_COPY_AND_ASSIGN(Hprof);
916};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500917
Andreas Gampe3a913092015-01-10 00:26:17 -0800918static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* size_out) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500919 char c = sig[0];
920 HprofBasicType ret;
921 size_t size;
922
923 switch (c) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800924 case '[':
925 case 'L':
926 ret = hprof_basic_object;
927 size = 4;
928 break;
929 case 'Z':
930 ret = hprof_basic_boolean;
931 size = 1;
932 break;
933 case 'C':
934 ret = hprof_basic_char;
935 size = 2;
936 break;
937 case 'F':
938 ret = hprof_basic_float;
939 size = 4;
940 break;
941 case 'D':
942 ret = hprof_basic_double;
943 size = 8;
944 break;
945 case 'B':
946 ret = hprof_basic_byte;
947 size = 1;
948 break;
949 case 'S':
950 ret = hprof_basic_short;
951 size = 2;
952 break;
953 case 'I':
954 ret = hprof_basic_int;
955 size = 4;
956 break;
957 case 'J':
958 ret = hprof_basic_long;
959 size = 8;
960 break;
961 default:
962 LOG(FATAL) << "UNREACHABLE";
963 UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500964 }
965
Andreas Gampe3a913092015-01-10 00:26:17 -0800966 if (size_out != nullptr) {
967 *size_out = size;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500968 }
969
970 return ret;
971}
972
973// Always called when marking objects, but only does
974// something when ctx->gc_scan_state_ is non-zero, which is usually
975// only true when marking the root set or unreachable
976// objects. Used to add rootset references to obj.
Andreas Gampe3a913092015-01-10 00:26:17 -0800977void Hprof::MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700978 uint32_t thread_serial) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800979 if (heap_tag == 0) {
980 return;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500981 }
982
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700983 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500984
Andreas Gampe3a913092015-01-10 00:26:17 -0800985 switch (heap_tag) {
986 // ID: object ID
987 case HPROF_ROOT_UNKNOWN:
988 case HPROF_ROOT_STICKY_CLASS:
989 case HPROF_ROOT_MONITOR_USED:
990 case HPROF_ROOT_INTERNED_STRING:
991 case HPROF_ROOT_DEBUGGER:
Richard Uhler4b767552016-04-26 13:28:59 -0700992 case HPROF_ROOT_VM_INTERNAL: {
993 uint64_t key = (static_cast<uint64_t>(heap_tag) << 32) | PointerToLowMemUInt32(obj);
994 if (simple_roots_.insert(key).second) {
995 __ AddU1(heap_tag);
996 __ AddObjectId(obj);
997 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800998 break;
Richard Uhler4b767552016-04-26 13:28:59 -0700999 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001000
Andreas Gampe3a913092015-01-10 00:26:17 -08001001 // ID: object ID
1002 // ID: JNI global ref ID
1003 case HPROF_ROOT_JNI_GLOBAL:
1004 __ AddU1(heap_tag);
1005 __ AddObjectId(obj);
1006 __ AddJniGlobalRefId(jni_obj);
1007 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001008
Andreas Gampe3a913092015-01-10 00:26:17 -08001009 // ID: object ID
1010 // U4: thread serial number
1011 // U4: frame number in stack trace (-1 for empty)
1012 case HPROF_ROOT_JNI_LOCAL:
1013 case HPROF_ROOT_JNI_MONITOR:
1014 case HPROF_ROOT_JAVA_FRAME:
1015 __ AddU1(heap_tag);
1016 __ AddObjectId(obj);
1017 __ AddU4(thread_serial);
1018 __ AddU4((uint32_t)-1);
1019 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001020
Andreas Gampe3a913092015-01-10 00:26:17 -08001021 // ID: object ID
1022 // U4: thread serial number
1023 case HPROF_ROOT_NATIVE_STACK:
1024 case HPROF_ROOT_THREAD_BLOCK:
1025 __ AddU1(heap_tag);
1026 __ AddObjectId(obj);
1027 __ AddU4(thread_serial);
1028 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001029
Andreas Gampe3a913092015-01-10 00:26:17 -08001030 // ID: thread object ID
1031 // U4: thread serial number
1032 // U4: stack trace serial number
1033 case HPROF_ROOT_THREAD_OBJECT:
1034 __ AddU1(heap_tag);
1035 __ AddObjectId(obj);
1036 __ AddU4(thread_serial);
1037 __ AddU4((uint32_t)-1); // xxx
1038 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001039
Andreas Gampe3a913092015-01-10 00:26:17 -08001040 case HPROF_CLASS_DUMP:
1041 case HPROF_INSTANCE_DUMP:
1042 case HPROF_OBJECT_ARRAY_DUMP:
1043 case HPROF_PRIMITIVE_ARRAY_DUMP:
1044 case HPROF_HEAP_DUMP_INFO:
1045 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
1046 // Ignored.
1047 break;
Elliott Hughes73e66f72012-05-09 09:34:45 -07001048
Andreas Gampe3a913092015-01-10 00:26:17 -08001049 case HPROF_ROOT_FINALIZING:
1050 case HPROF_ROOT_REFERENCE_CLEANUP:
1051 case HPROF_UNREACHABLE:
1052 LOG(FATAL) << "obsolete tag " << static_cast<int>(heap_tag);
1053 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001054 }
1055
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001056 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001057}
1058
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001059// Use for visiting the GcRoots held live by ArtFields, ArtMethods, and ClassLoaders.
1060class GcRootVisitor {
1061 public:
1062 explicit GcRootVisitor(Hprof* hprof) : hprof_(hprof) {}
1063
1064 void operator()(mirror::Object* obj ATTRIBUTE_UNUSED,
1065 MemberOffset offset ATTRIBUTE_UNUSED,
1066 bool is_static ATTRIBUTE_UNUSED) const {}
1067
1068 // Note that these don't have read barriers. Its OK however since the GC is guaranteed to not be
1069 // running during the hprof dumping process.
1070 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001071 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001072 if (!root->IsNull()) {
1073 VisitRoot(root);
1074 }
1075 }
1076
1077 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001078 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001079 mirror::Object* obj = root->AsMirrorPtr();
1080 // The two cases are either classes or dex cache arrays. If it is a dex cache array, then use
1081 // VM internal. Otherwise the object is a declaring class of an ArtField or ArtMethod or a
1082 // class from a ClassLoader.
1083 hprof_->VisitRoot(obj, RootInfo(obj->IsClass() ? kRootStickyClass : kRootVMInternal));
1084 }
1085
1086
1087 private:
1088 Hprof* const hprof_;
1089};
1090
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001091void Hprof::DumpHeapObject(mirror::Object* obj) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001092 // Ignore classes that are retired.
1093 if (obj->IsClass() && obj->AsClass()->IsRetired()) {
1094 return;
1095 }
1096
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -08001097 ++total_objects_;
1098
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001099 GcRootVisitor visitor(this);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001100 obj->VisitReferences(visitor, VoidFunctor());
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001101
Mathieu Chartiere7158112015-06-03 13:32:15 -07001102 gc::Heap* const heap = Runtime::Current()->GetHeap();
1103 const gc::space::ContinuousSpace* const space = heap->FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001104 HprofHeapId heap_type = HPROF_HEAP_APP;
1105 if (space != nullptr) {
1106 if (space->IsZygoteSpace()) {
1107 heap_type = HPROF_HEAP_ZYGOTE;
1108 } else if (space->IsImageSpace()) {
1109 heap_type = HPROF_HEAP_IMAGE;
1110 }
Mathieu Chartiere7158112015-06-03 13:32:15 -07001111 } else {
1112 const auto* los = heap->GetLargeObjectsSpace();
1113 if (los->Contains(obj) && los->IsZygoteLargeObject(Thread::Current(), obj)) {
1114 heap_type = HPROF_HEAP_ZYGOTE;
1115 }
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001116 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001117 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001118
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001119 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001120 HprofStringId nameId;
1121
1122 // This object is in a different heap than the current one.
1123 // Emit a HEAP_DUMP_INFO tag to change heaps.
Andreas Gampe3a913092015-01-10 00:26:17 -08001124 __ AddU1(HPROF_HEAP_DUMP_INFO);
1125 __ AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001126 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001127 case HPROF_HEAP_APP:
1128 nameId = LookupStringId("app");
1129 break;
1130 case HPROF_HEAP_ZYGOTE:
1131 nameId = LookupStringId("zygote");
1132 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001133 case HPROF_HEAP_IMAGE:
1134 nameId = LookupStringId("image");
1135 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001136 default:
1137 // Internal error
1138 LOG(ERROR) << "Unexpected desiredHeap";
1139 nameId = LookupStringId("<ILLEGAL>");
1140 break;
1141 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001142 __ AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001143 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001144 }
1145
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001146 mirror::Class* c = obj->GetClass();
Andreas Gampe3a913092015-01-10 00:26:17 -08001147 if (c == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001148 // This object will bother HprofReader, because it has a null
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001149 // class, so just don't dump it. It could be
1150 // gDvm.unlinkedJavaLangClass or it could be an object just
1151 // allocated which hasn't been initialized yet.
1152 } else {
1153 if (obj->IsClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001154 DumpHeapClass(obj->AsClass());
Elliott Hughese84278b2012-03-22 10:06:53 -07001155 } else if (c->IsArrayClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001156 DumpHeapArray(obj->AsArray(), c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001157 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001158 DumpHeapInstanceObject(obj, c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001159 }
1160 }
1161
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001162 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001163}
1164
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001165void Hprof::DumpHeapClass(mirror::Class* klass) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001166 if (!klass->IsResolved()) {
Mathieu Chartier12393f32016-10-20 17:11:23 -07001167 // Class is allocated but not yet resolved: we cannot access its fields or super class.
Sebastien Hertzca068b22015-04-07 10:28:53 +02001168 return;
1169 }
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001170 const size_t num_static_fields = klass->NumStaticFields();
1171 // Total class size including embedded IMT, embedded vtable, and static fields.
1172 const size_t class_size = klass->GetClassSize();
1173 // Class size excluding static fields (relies on reference fields being the first static fields).
1174 const size_t class_size_without_overhead = sizeof(mirror::Class);
1175 CHECK_LE(class_size_without_overhead, class_size);
1176 const size_t overhead_size = class_size - class_size_without_overhead;
1177
1178 if (overhead_size != 0) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001179 // Create a byte array to reflect the allocation of the
1180 // StaticField array at the end of this class.
1181 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1182 __ AddClassStaticsId(klass);
Man Cao8c2ff642015-05-27 17:25:30 -07001183 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(klass));
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001184 __ AddU4(overhead_size);
Andreas Gampe3a913092015-01-10 00:26:17 -08001185 __ AddU1(hprof_basic_byte);
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001186 for (size_t i = 0; i < overhead_size; ++i) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001187 __ AddU1(0);
1188 }
1189 }
1190
1191 __ AddU1(HPROF_CLASS_DUMP);
1192 __ AddClassId(LookupClassId(klass));
Man Cao8c2ff642015-05-27 17:25:30 -07001193 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001194 __ AddClassId(LookupClassId(klass->GetSuperClass()));
1195 __ AddObjectId(klass->GetClassLoader());
1196 __ AddObjectId(nullptr); // no signer
1197 __ AddObjectId(nullptr); // no prot domain
1198 __ AddObjectId(nullptr); // reserved
1199 __ AddObjectId(nullptr); // reserved
1200 if (klass->IsClassClass()) {
1201 // ClassObjects have their static fields appended, so aren't all the same size.
1202 // But they're at least this size.
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001203 __ AddU4(class_size_without_overhead); // instance size
Jeff Hao0ce43532015-05-12 18:58:32 -07001204 } else if (klass->IsStringClass()) {
1205 // Strings are variable length with character data at the end like arrays.
1206 // This outputs the size of an empty string.
1207 __ AddU4(sizeof(mirror::String));
1208 } else if (klass->IsArrayClass() || klass->IsPrimitive()) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001209 __ AddU4(0);
1210 } else {
1211 __ AddU4(klass->GetObjectSize()); // instance size
1212 }
1213
1214 __ AddU2(0); // empty const pool
1215
1216 // Static fields
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001217 if (overhead_size == 0) {
1218 __ AddU2(static_cast<uint16_t>(0));
Andreas Gampe3a913092015-01-10 00:26:17 -08001219 } else {
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001220 __ AddU2(static_cast<uint16_t>(num_static_fields + 1));
1221 __ AddStringId(LookupStringId(kClassOverheadName));
Andreas Gampe3a913092015-01-10 00:26:17 -08001222 __ AddU1(hprof_basic_object);
1223 __ AddClassStaticsId(klass);
1224
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001225 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001226 ArtField* f = klass->GetStaticField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001227
1228 size_t size;
1229 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1230 __ AddStringId(LookupStringId(f->GetName()));
1231 __ AddU1(t);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001232 switch (t) {
1233 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001234 __ AddU1(f->GetByte(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001235 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001236 case hprof_basic_boolean:
1237 __ AddU1(f->GetBoolean(klass));
1238 break;
1239 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001240 __ AddU2(f->GetChar(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001241 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001242 case hprof_basic_short:
1243 __ AddU2(f->GetShort(klass));
1244 break;
1245 case hprof_basic_float:
1246 case hprof_basic_int:
1247 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001248 __ AddU4(f->Get32(klass));
1249 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001250 case hprof_basic_double:
1251 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001252 __ AddU8(f->Get64(klass));
1253 break;
1254 default:
1255 LOG(FATAL) << "Unexpected size " << size;
1256 UNREACHABLE();
1257 }
1258 }
1259 }
1260
1261 // Instance fields for this class (no superclass fields)
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001262 int iFieldCount = klass->NumInstanceFields();
Jeff Hao848f70a2014-01-15 13:49:50 -08001263 if (klass->IsStringClass()) {
1264 __ AddU2((uint16_t)iFieldCount + 1);
1265 } else {
1266 __ AddU2((uint16_t)iFieldCount);
1267 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001268 for (int i = 0; i < iFieldCount; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001269 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001270 __ AddStringId(LookupStringId(f->GetName()));
1271 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), nullptr);
1272 __ AddU1(t);
1273 }
Vladimir Marko595beb32017-02-06 14:11:54 +00001274 // Add native value character array for strings / byte array for compressed strings.
Jeff Hao848f70a2014-01-15 13:49:50 -08001275 if (klass->IsStringClass()) {
1276 __ AddStringId(LookupStringId("value"));
1277 __ AddU1(hprof_basic_object);
1278 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001279}
1280
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001281void Hprof::DumpHeapArray(mirror::Array* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001282 uint32_t length = obj->GetLength();
1283
1284 if (obj->IsObjectArray()) {
1285 // obj is an object array.
1286 __ AddU1(HPROF_OBJECT_ARRAY_DUMP);
1287
1288 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001289 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001290 __ AddU4(length);
1291 __ AddClassId(LookupClassId(klass));
1292
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001293 // Dump the elements, which are always objects or null.
Andreas Gampe3a913092015-01-10 00:26:17 -08001294 __ AddIdList(obj->AsObjectArray<mirror::Object>());
1295 } else {
1296 size_t size;
1297 HprofBasicType t = SignatureToBasicTypeAndSize(
1298 Primitive::Descriptor(klass->GetComponentType()->GetPrimitiveType()), &size);
1299
1300 // obj is a primitive array.
1301 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1302
1303 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001304 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001305 __ AddU4(length);
1306 __ AddU1(t);
1307
1308 // Dump the raw, packed element values.
1309 if (size == 1) {
1310 __ AddU1List(reinterpret_cast<const uint8_t*>(obj->GetRawData(sizeof(uint8_t), 0)), length);
1311 } else if (size == 2) {
1312 __ AddU2List(reinterpret_cast<const uint16_t*>(obj->GetRawData(sizeof(uint16_t), 0)), length);
1313 } else if (size == 4) {
1314 __ AddU4List(reinterpret_cast<const uint32_t*>(obj->GetRawData(sizeof(uint32_t), 0)), length);
1315 } else if (size == 8) {
1316 __ AddU8List(reinterpret_cast<const uint64_t*>(obj->GetRawData(sizeof(uint64_t), 0)), length);
1317 }
1318 }
1319}
1320
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001321void Hprof::DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001322 // obj is an instance object.
1323 __ AddU1(HPROF_INSTANCE_DUMP);
1324 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001325 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001326 __ AddClassId(LookupClassId(klass));
1327
1328 // Reserve some space for the length of the instance data, which we won't
1329 // know until we're done writing it.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001330 size_t size_patch_offset = output_->Length();
Andreas Gampe3a913092015-01-10 00:26:17 -08001331 __ AddU4(0x77777777);
1332
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001333 // What we will use for the string value if the object is a string.
1334 mirror::Object* string_value = nullptr;
1335
1336 // Write the instance data; fields for this class, followed by super class fields, and so on.
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001337 do {
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001338 const size_t instance_fields = klass->NumInstanceFields();
1339 for (size_t i = 0; i < instance_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001340 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001341 size_t size;
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001342 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001343 switch (t) {
1344 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001345 __ AddU1(f->GetByte(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001346 break;
1347 case hprof_basic_boolean:
1348 __ AddU1(f->GetBoolean(obj));
1349 break;
1350 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001351 __ AddU2(f->GetChar(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001352 break;
1353 case hprof_basic_short:
1354 __ AddU2(f->GetShort(obj));
1355 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001356 case hprof_basic_int:
Vladimir Marko595beb32017-02-06 14:11:54 +00001357 if (mirror::kUseStringCompression &&
1358 klass->IsStringClass() &&
1359 f->GetOffset().SizeValue() == mirror::String::CountOffset().SizeValue()) {
1360 // Store the string length instead of the raw count field with compression flag.
1361 __ AddU4(obj->AsString()->GetLength());
1362 break;
1363 }
1364 FALLTHROUGH_INTENDED;
1365 case hprof_basic_float:
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001366 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001367 __ AddU4(f->Get32(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001368 break;
1369 case hprof_basic_double:
1370 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001371 __ AddU8(f->Get64(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001372 break;
Andreas Gampe3a913092015-01-10 00:26:17 -08001373 }
1374 }
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001375 // Add value field for String if necessary.
1376 if (klass->IsStringClass()) {
1377 mirror::String* s = obj->AsString();
1378 if (s->GetLength() == 0) {
1379 // If string is empty, use an object-aligned address within the string for the value.
1380 string_value = reinterpret_cast<mirror::Object*>(
1381 reinterpret_cast<uintptr_t>(s) + kObjectAlignment);
1382 } else {
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001383 if (s->IsCompressed()) {
1384 string_value = reinterpret_cast<mirror::Object*>(s->GetValueCompressed());
1385 } else {
1386 string_value = reinterpret_cast<mirror::Object*>(s->GetValue());
1387 }
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001388 }
1389 __ AddObjectId(string_value);
1390 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001391
1392 klass = klass->GetSuperClass();
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001393 } while (klass != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -08001394
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001395 // Patch the instance field length.
1396 __ UpdateU4(size_patch_offset, output_->Length() - (size_patch_offset + 4));
1397
Jeff Hao848f70a2014-01-15 13:49:50 -08001398 // Output native value character array for strings.
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001399 CHECK_EQ(obj->IsString(), string_value != nullptr);
1400 if (string_value != nullptr) {
Jeff Hao848f70a2014-01-15 13:49:50 -08001401 mirror::String* s = obj->AsString();
Jeff Hao848f70a2014-01-15 13:49:50 -08001402 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001403 __ AddObjectId(string_value);
Man Cao8c2ff642015-05-27 17:25:30 -07001404 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Vladimir Marko595beb32017-02-06 14:11:54 +00001405 __ AddU4(s->GetLength());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001406 if (s->IsCompressed()) {
Vladimir Marko595beb32017-02-06 14:11:54 +00001407 __ AddU1(hprof_basic_byte);
1408 __ AddU1List(s->GetValueCompressed(), s->GetLength());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001409 } else {
Vladimir Marko595beb32017-02-06 14:11:54 +00001410 __ AddU1(hprof_basic_char);
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001411 __ AddU2List(s->GetValue(), s->GetLength());
1412 }
Jeff Hao848f70a2014-01-15 13:49:50 -08001413 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001414}
1415
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001416void Hprof::VisitRoot(mirror::Object* obj, const RootInfo& info) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001417 static const HprofHeapTag xlate[] = {
1418 HPROF_ROOT_UNKNOWN,
1419 HPROF_ROOT_JNI_GLOBAL,
1420 HPROF_ROOT_JNI_LOCAL,
1421 HPROF_ROOT_JAVA_FRAME,
1422 HPROF_ROOT_NATIVE_STACK,
1423 HPROF_ROOT_STICKY_CLASS,
1424 HPROF_ROOT_THREAD_BLOCK,
1425 HPROF_ROOT_MONITOR_USED,
1426 HPROF_ROOT_THREAD_OBJECT,
1427 HPROF_ROOT_INTERNED_STRING,
1428 HPROF_ROOT_FINALIZING,
1429 HPROF_ROOT_DEBUGGER,
1430 HPROF_ROOT_REFERENCE_CLEANUP,
1431 HPROF_ROOT_VM_INTERNAL,
1432 HPROF_ROOT_JNI_MONITOR,
1433 };
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001434 CHECK_LT(info.GetType(), sizeof(xlate) / sizeof(HprofHeapTag));
Andreas Gampe3a913092015-01-10 00:26:17 -08001435 if (obj == nullptr) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001436 return;
1437 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001438 MarkRootObject(obj, 0, xlate[info.GetType()], info.GetThreadId());
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001439}
1440
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001441// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1442// sent directly to DDMS.
1443// If "fd" is >= 0, the output will be written to that file descriptor.
1444// Otherwise, "filename" is used to create an output file.
1445void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001446 CHECK(filename != nullptr);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001447
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001448 Thread* self = Thread::Current();
1449 gc::Heap* heap = Runtime::Current()->GetHeap();
1450 if (heap->IsGcConcurrentAndMoving()) {
1451 // Need to take a heap dump while GC isn't running. See the
1452 // comment in Heap::VisitObjects().
1453 heap->IncrementDisableMovingGC(self);
1454 }
Mathieu Chartier4f55e222015-09-04 13:26:21 -07001455 {
1456 ScopedSuspendAll ssa(__FUNCTION__, true /* long suspend */);
1457 Hprof hprof(filename, fd, direct_to_ddms);
1458 hprof.Dump();
1459 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001460 if (heap->IsGcConcurrentAndMoving()) {
1461 heap->DecrementDisableMovingGC(self);
1462 }
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001463}
1464
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001465} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001466} // namespace art