blob: 495fec7a487810b966493546fd0db5a8041acdc6 [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"
Mathieu Chartierecc82302017-02-16 10:20:12 -080053#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070054#include "gc/heap.h"
55#include "gc/space/space.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070056#include "globals.h"
Mathieu Chartierad466ad2015-01-08 16:28:08 -080057#include "jdwp/jdwp.h"
58#include "jdwp/jdwp_priv.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/class.h"
60#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/object-inl.h"
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -070062#include "os.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070063#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070064#include "scoped_thread_state_change-inl.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070065#include "thread_list.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040066
67namespace art {
68
69namespace hprof {
70
Mathieu Chartierad466ad2015-01-08 16:28:08 -080071static constexpr bool kDirectStream = true;
Jesse Wilson0c54ac12011-11-09 15:14:05 -050072
Andreas Gampe3a913092015-01-10 00:26:17 -080073static constexpr uint32_t kHprofTime = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -080074static constexpr uint32_t kHprofNullThread = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -070075
Andreas Gampe3a913092015-01-10 00:26:17 -080076static constexpr size_t kMaxObjectsPerSegment = 128;
77static constexpr size_t kMaxBytesPerSegment = 4096;
Elliott Hughes622a6982012-06-08 17:58:54 -070078
Andreas Gampe3a913092015-01-10 00:26:17 -080079// The static field-name for the synthetic object generated to account for class static overhead.
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -070080static constexpr const char* kClassOverheadName = "$classOverhead";
Elliott Hughes622a6982012-06-08 17:58:54 -070081
82enum HprofTag {
83 HPROF_TAG_STRING = 0x01,
84 HPROF_TAG_LOAD_CLASS = 0x02,
85 HPROF_TAG_UNLOAD_CLASS = 0x03,
86 HPROF_TAG_STACK_FRAME = 0x04,
87 HPROF_TAG_STACK_TRACE = 0x05,
88 HPROF_TAG_ALLOC_SITES = 0x06,
89 HPROF_TAG_HEAP_SUMMARY = 0x07,
90 HPROF_TAG_START_THREAD = 0x0A,
91 HPROF_TAG_END_THREAD = 0x0B,
92 HPROF_TAG_HEAP_DUMP = 0x0C,
93 HPROF_TAG_HEAP_DUMP_SEGMENT = 0x1C,
94 HPROF_TAG_HEAP_DUMP_END = 0x2C,
95 HPROF_TAG_CPU_SAMPLES = 0x0D,
96 HPROF_TAG_CONTROL_SETTINGS = 0x0E,
97};
98
99// Values for the first byte of HEAP_DUMP and HEAP_DUMP_SEGMENT records:
100enum HprofHeapTag {
101 // Traditional.
102 HPROF_ROOT_UNKNOWN = 0xFF,
103 HPROF_ROOT_JNI_GLOBAL = 0x01,
104 HPROF_ROOT_JNI_LOCAL = 0x02,
105 HPROF_ROOT_JAVA_FRAME = 0x03,
106 HPROF_ROOT_NATIVE_STACK = 0x04,
107 HPROF_ROOT_STICKY_CLASS = 0x05,
108 HPROF_ROOT_THREAD_BLOCK = 0x06,
109 HPROF_ROOT_MONITOR_USED = 0x07,
110 HPROF_ROOT_THREAD_OBJECT = 0x08,
111 HPROF_CLASS_DUMP = 0x20,
112 HPROF_INSTANCE_DUMP = 0x21,
113 HPROF_OBJECT_ARRAY_DUMP = 0x22,
114 HPROF_PRIMITIVE_ARRAY_DUMP = 0x23,
115
116 // Android.
117 HPROF_HEAP_DUMP_INFO = 0xfe,
118 HPROF_ROOT_INTERNED_STRING = 0x89,
119 HPROF_ROOT_FINALIZING = 0x8a, // Obsolete.
120 HPROF_ROOT_DEBUGGER = 0x8b,
121 HPROF_ROOT_REFERENCE_CLEANUP = 0x8c, // Obsolete.
122 HPROF_ROOT_VM_INTERNAL = 0x8d,
123 HPROF_ROOT_JNI_MONITOR = 0x8e,
124 HPROF_UNREACHABLE = 0x90, // Obsolete.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700125 HPROF_PRIMITIVE_ARRAY_NODATA_DUMP = 0xc3, // Obsolete.
Elliott Hughes622a6982012-06-08 17:58:54 -0700126};
127
128enum HprofHeapId {
129 HPROF_HEAP_DEFAULT = 0,
130 HPROF_HEAP_ZYGOTE = 'Z',
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700131 HPROF_HEAP_APP = 'A',
132 HPROF_HEAP_IMAGE = 'I',
Elliott Hughes622a6982012-06-08 17:58:54 -0700133};
134
135enum HprofBasicType {
136 hprof_basic_object = 2,
137 hprof_basic_boolean = 4,
138 hprof_basic_char = 5,
139 hprof_basic_float = 6,
140 hprof_basic_double = 7,
141 hprof_basic_byte = 8,
142 hprof_basic_short = 9,
143 hprof_basic_int = 10,
144 hprof_basic_long = 11,
145};
146
Ian Rogersef7d42f2014-01-06 12:55:46 -0800147typedef uint32_t HprofStringId;
148typedef uint32_t HprofClassObjectId;
Man Cao8c2ff642015-05-27 17:25:30 -0700149typedef uint32_t HprofClassSerialNumber;
150typedef uint32_t HprofStackTraceSerialNumber;
151typedef uint32_t HprofStackFrameId;
152static constexpr HprofStackTraceSerialNumber kHprofNullStackTrace = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -0700153
Andreas Gampe3a913092015-01-10 00:26:17 -0800154class EndianOutput {
Elliott Hughes622a6982012-06-08 17:58:54 -0700155 public:
Andreas Gampe3a913092015-01-10 00:26:17 -0800156 EndianOutput() : length_(0), sum_length_(0), max_length_(0), started_(false) {}
157 virtual ~EndianOutput() {}
158
159 void StartNewRecord(uint8_t tag, uint32_t time) {
160 if (length_ > 0) {
161 EndRecord();
162 }
163 DCHECK_EQ(length_, 0U);
164 AddU1(tag);
165 AddU4(time);
166 AddU4(0xdeaddead); // Length, replaced on flush.
167 started_ = true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700168 }
169
Andreas Gampe3a913092015-01-10 00:26:17 -0800170 void EndRecord() {
171 // Replace length in header.
172 if (started_) {
173 UpdateU4(sizeof(uint8_t) + sizeof(uint32_t),
174 length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
175 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700176
Andreas Gampe3a913092015-01-10 00:26:17 -0800177 HandleEndRecord();
178
179 sum_length_ += length_;
180 max_length_ = std::max(max_length_, length_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700181 length_ = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -0800182 started_ = false;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700183 }
184
Andreas Gampe3a913092015-01-10 00:26:17 -0800185 void AddU1(uint8_t value) {
186 AddU1List(&value, 1);
187 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800188 void AddU2(uint16_t value) {
189 AddU2List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700190 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800191 void AddU4(uint32_t value) {
192 AddU4List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700193 }
194
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800195 void AddU8(uint64_t value) {
196 AddU8List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700197 }
198
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800199 void AddObjectId(const mirror::Object* value) {
200 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800201 }
202
Man Cao8c2ff642015-05-27 17:25:30 -0700203 void AddStackTraceSerialNumber(HprofStackTraceSerialNumber value) {
204 AddU4(value);
205 }
206
Ian Rogersef7d42f2014-01-06 12:55:46 -0800207 // The ID for the synthetic object generated to account for class static overhead.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800208 void AddClassStaticsId(const mirror::Class* value) {
209 AddU4(1 | PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800210 }
211
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800212 void AddJniGlobalRefId(jobject value) {
213 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800214 }
215
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800216 void AddClassId(HprofClassObjectId value) {
217 AddU4(value);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800218 }
219
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800220 void AddStringId(HprofStringId value) {
221 AddU4(value);
Elliott Hughes622a6982012-06-08 17:58:54 -0700222 }
223
Andreas Gampe3a913092015-01-10 00:26:17 -0800224 void AddU1List(const uint8_t* values, size_t count) {
225 HandleU1List(values, count);
226 length_ += count;
227 }
228 void AddU2List(const uint16_t* values, size_t count) {
229 HandleU2List(values, count);
230 length_ += count * sizeof(uint16_t);
231 }
232 void AddU4List(const uint32_t* values, size_t count) {
233 HandleU4List(values, count);
234 length_ += count * sizeof(uint32_t);
235 }
Andreas Gampeca714582015-04-03 19:41:34 -0700236 virtual void UpdateU4(size_t offset, uint32_t new_value ATTRIBUTE_UNUSED) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800237 DCHECK_LE(offset, length_ - 4);
238 }
239 void AddU8List(const uint64_t* values, size_t count) {
240 HandleU8List(values, count);
241 length_ += count * sizeof(uint64_t);
242 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700243
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800244 void AddIdList(mirror::ObjectArray<mirror::Object>* values)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700245 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800246 const int32_t length = values->GetLength();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800247 for (int32_t i = 0; i < length; ++i) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800248 AddObjectId(values->GetWithoutChecks(i));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800249 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700250 }
251
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800252 void AddUtf8String(const char* str) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700253 // The terminating NUL character is NOT written.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800254 AddU1List((const uint8_t*)str, strlen(str));
Elliott Hughes622a6982012-06-08 17:58:54 -0700255 }
256
Andreas Gampe3a913092015-01-10 00:26:17 -0800257 size_t Length() const {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700258 return length_;
259 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700260
Andreas Gampe3a913092015-01-10 00:26:17 -0800261 size_t SumLength() const {
262 return sum_length_;
Elliott Hughes622a6982012-06-08 17:58:54 -0700263 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700264
Andreas Gampe3a913092015-01-10 00:26:17 -0800265 size_t MaxLength() const {
266 return max_length_;
267 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700268
Andreas Gampe3a913092015-01-10 00:26:17 -0800269 protected:
270 virtual void HandleU1List(const uint8_t* values ATTRIBUTE_UNUSED,
271 size_t count ATTRIBUTE_UNUSED) {
272 }
jessicahandojo3aaa37b2016-07-29 14:46:37 -0700273 virtual void HandleU1AsU2List(const uint8_t* values ATTRIBUTE_UNUSED,
274 size_t count ATTRIBUTE_UNUSED) {
275 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800276 virtual void HandleU2List(const uint16_t* values ATTRIBUTE_UNUSED,
277 size_t count ATTRIBUTE_UNUSED) {
278 }
279 virtual void HandleU4List(const uint32_t* values ATTRIBUTE_UNUSED,
280 size_t count ATTRIBUTE_UNUSED) {
281 }
282 virtual void HandleU8List(const uint64_t* values ATTRIBUTE_UNUSED,
283 size_t count ATTRIBUTE_UNUSED) {
284 }
285 virtual void HandleEndRecord() {
286 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700287
Andreas Gampe3a913092015-01-10 00:26:17 -0800288 size_t length_; // Current record size.
289 size_t sum_length_; // Size of all data.
290 size_t max_length_; // Maximum seen length.
291 bool started_; // Was StartRecord called?
Elliott Hughes622a6982012-06-08 17:58:54 -0700292};
293
Andreas Gampe3a913092015-01-10 00:26:17 -0800294// This keeps things buffered until flushed.
295class EndianOutputBuffered : public EndianOutput {
296 public:
297 explicit EndianOutputBuffered(size_t reserve_size) {
298 buffer_.reserve(reserve_size);
299 }
300 virtual ~EndianOutputBuffered() {}
301
302 void UpdateU4(size_t offset, uint32_t new_value) OVERRIDE {
303 DCHECK_LE(offset, length_ - 4);
304 buffer_[offset + 0] = static_cast<uint8_t>((new_value >> 24) & 0xFF);
305 buffer_[offset + 1] = static_cast<uint8_t>((new_value >> 16) & 0xFF);
306 buffer_[offset + 2] = static_cast<uint8_t>((new_value >> 8) & 0xFF);
307 buffer_[offset + 3] = static_cast<uint8_t>((new_value >> 0) & 0xFF);
308 }
309
310 protected:
311 void HandleU1List(const uint8_t* values, size_t count) OVERRIDE {
312 DCHECK_EQ(length_, buffer_.size());
313 buffer_.insert(buffer_.end(), values, values + count);
314 }
315
jessicahandojo3aaa37b2016-07-29 14:46:37 -0700316 void HandleU1AsU2List(const uint8_t* values, size_t count) OVERRIDE {
317 DCHECK_EQ(length_, buffer_.size());
318 // All 8-bits are grouped in 2 to make 16-bit block like Java Char
319 if (count & 1) {
320 buffer_.push_back(0);
321 }
322 for (size_t i = 0; i < count; ++i) {
323 uint8_t value = *values;
324 buffer_.push_back(value);
325 values++;
326 }
327 }
328
Andreas Gampe3a913092015-01-10 00:26:17 -0800329 void HandleU2List(const uint16_t* values, size_t count) OVERRIDE {
330 DCHECK_EQ(length_, buffer_.size());
331 for (size_t i = 0; i < count; ++i) {
332 uint16_t value = *values;
333 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
334 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
335 values++;
336 }
337 }
338
339 void HandleU4List(const uint32_t* values, size_t count) OVERRIDE {
340 DCHECK_EQ(length_, buffer_.size());
341 for (size_t i = 0; i < count; ++i) {
342 uint32_t value = *values;
343 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
344 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
345 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
346 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
347 values++;
348 }
349 }
350
351 void HandleU8List(const uint64_t* values, size_t count) OVERRIDE {
352 DCHECK_EQ(length_, buffer_.size());
353 for (size_t i = 0; i < count; ++i) {
354 uint64_t value = *values;
355 buffer_.push_back(static_cast<uint8_t>((value >> 56) & 0xFF));
356 buffer_.push_back(static_cast<uint8_t>((value >> 48) & 0xFF));
357 buffer_.push_back(static_cast<uint8_t>((value >> 40) & 0xFF));
358 buffer_.push_back(static_cast<uint8_t>((value >> 32) & 0xFF));
359 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
360 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
361 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
362 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
363 values++;
364 }
365 }
366
367 void HandleEndRecord() OVERRIDE {
368 DCHECK_EQ(buffer_.size(), length_);
369 if (kIsDebugBuild && started_) {
370 uint32_t stored_length =
371 static_cast<uint32_t>(buffer_[5]) << 24 |
372 static_cast<uint32_t>(buffer_[6]) << 16 |
373 static_cast<uint32_t>(buffer_[7]) << 8 |
374 static_cast<uint32_t>(buffer_[8]);
375 DCHECK_EQ(stored_length, length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
376 }
377 HandleFlush(buffer_.data(), length_);
378 buffer_.clear();
379 }
380
381 virtual void HandleFlush(const uint8_t* buffer ATTRIBUTE_UNUSED, size_t length ATTRIBUTE_UNUSED) {
382 }
383
384 std::vector<uint8_t> buffer_;
385};
386
387class FileEndianOutput FINAL : public EndianOutputBuffered {
388 public:
389 FileEndianOutput(File* fp, size_t reserved_size)
390 : EndianOutputBuffered(reserved_size), fp_(fp), errors_(false) {
391 DCHECK(fp != nullptr);
392 }
393 ~FileEndianOutput() {
394 }
395
396 bool Errors() {
397 return errors_;
398 }
399
400 protected:
401 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
402 if (!errors_) {
403 errors_ = !fp_->WriteFully(buffer, length);
404 }
405 }
406
407 private:
408 File* fp_;
409 bool errors_;
410};
411
412class NetStateEndianOutput FINAL : public EndianOutputBuffered {
413 public:
414 NetStateEndianOutput(JDWP::JdwpNetStateBase* net_state, size_t reserved_size)
415 : EndianOutputBuffered(reserved_size), net_state_(net_state) {
416 DCHECK(net_state != nullptr);
417 }
418 ~NetStateEndianOutput() {}
419
420 protected:
421 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
422 std::vector<iovec> iov;
423 iov.push_back(iovec());
424 iov[0].iov_base = const_cast<void*>(reinterpret_cast<const void*>(buffer));
425 iov[0].iov_len = length;
426 net_state_->WriteBufferedPacketLocked(iov);
427 }
428
429 private:
430 JDWP::JdwpNetStateBase* net_state_;
431};
432
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700433#define __ output_->
Andreas Gampe3a913092015-01-10 00:26:17 -0800434
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700435class Hprof : public SingleRootVisitor {
Elliott Hughes622a6982012-06-08 17:58:54 -0700436 public:
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700437 Hprof(const char* output_filename, int fd, bool direct_to_ddms)
438 : filename_(output_filename),
439 fd_(fd),
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800440 direct_to_ddms_(direct_to_ddms) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700441 LOG(INFO) << "hprof: heap dump \"" << filename_ << "\" starting...";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500442 }
443
Andreas Gampe3a913092015-01-10 00:26:17 -0800444 void Dump()
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800445 REQUIRES(Locks::mutator_lock_)
446 REQUIRES(!Locks::heap_bitmap_lock_, !Locks::alloc_tracker_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700447 {
448 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
449 if (Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
450 PopulateAllocationTrackingTraces();
451 }
452 }
453
Andreas Gampe3a913092015-01-10 00:26:17 -0800454 // First pass to measure the size of the dump.
455 size_t overall_size;
456 size_t max_length;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800457 {
Andreas Gampe3a913092015-01-10 00:26:17 -0800458 EndianOutput count_output;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700459 output_ = &count_output;
460 ProcessHeap(false);
Andreas Gampe3a913092015-01-10 00:26:17 -0800461 overall_size = count_output.SumLength();
462 max_length = count_output.MaxLength();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700463 output_ = nullptr;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800464 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700465
Andreas Gampe3a913092015-01-10 00:26:17 -0800466 bool okay;
Mathieu Chartierecc82302017-02-16 10:20:12 -0800467 visited_objects_.clear();
Andreas Gampe3a913092015-01-10 00:26:17 -0800468 if (direct_to_ddms_) {
469 if (kDirectStream) {
470 okay = DumpToDdmsDirect(overall_size, max_length, CHUNK_TYPE("HPDS"));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700471 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800472 okay = DumpToDdmsBuffered(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700473 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800474 } else {
475 okay = DumpToFile(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700476 }
477
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700478 if (okay) {
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800479 const uint64_t duration = NanoTime() - start_ns_;
480 LOG(INFO) << "hprof: heap dump completed (" << PrettySize(RoundUp(overall_size, KB))
481 << ") in " << PrettyDuration(duration)
482 << " objects " << total_objects_
483 << " objects with stack traces " << total_objects_with_stack_trace_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700484 }
485 }
486
487 private:
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800488 static void VisitObjectCallback(mirror::Object* obj, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700489 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800490 DCHECK(obj != nullptr);
491 DCHECK(arg != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700492 reinterpret_cast<Hprof*>(arg)->DumpHeapObject(obj);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700493 }
494
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700495 void DumpHeapObject(mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700496 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700497
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700498 void DumpHeapClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700499 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700500
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700501 void DumpHeapArray(mirror::Array* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700502 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800503
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700504 void DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700505 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800506
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700507 void ProcessHeap(bool header_first)
Mathieu Chartier90443472015-07-16 20:32:27 -0700508 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800509 // Reset current heap and object count.
510 current_heap_ = HPROF_HEAP_DEFAULT;
511 objects_in_segment_ = 0;
512
513 if (header_first) {
Man Cao8c2ff642015-05-27 17:25:30 -0700514 ProcessHeader(true);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700515 ProcessBody();
Andreas Gampe3a913092015-01-10 00:26:17 -0800516 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700517 ProcessBody();
Man Cao8c2ff642015-05-27 17:25:30 -0700518 ProcessHeader(false);
Andreas Gampe3a913092015-01-10 00:26:17 -0800519 }
520 }
521
Mathieu Chartier90443472015-07-16 20:32:27 -0700522 void ProcessBody() REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700523 Runtime* const runtime = Runtime::Current();
Andreas Gampe3a913092015-01-10 00:26:17 -0800524 // Walk the roots and the heap.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700525 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Andreas Gampe3a913092015-01-10 00:26:17 -0800526
Richard Uhler4b767552016-04-26 13:28:59 -0700527 simple_roots_.clear();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700528 runtime->VisitRoots(this);
529 runtime->VisitImageRoots(this);
530 runtime->GetHeap()->VisitObjectsPaused(VisitObjectCallback, this);
Andreas Gampe3a913092015-01-10 00:26:17 -0800531
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700532 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_END, kHprofTime);
533 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800534 }
535
Mathieu Chartier90443472015-07-16 20:32:27 -0700536 void ProcessHeader(bool string_first) REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800537 // Write the header.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700538 WriteFixedHeader();
Andreas Gampe3a913092015-01-10 00:26:17 -0800539 // Write the string and class tables, and any stack traces, to the header.
540 // (jhat requires that these appear before any of the data in the body that refers to them.)
Man Cao8c2ff642015-05-27 17:25:30 -0700541 // jhat also requires the string table appear before class table and stack traces.
542 // However, WriteStackTraces() can modify the string table, so it's necessary to call
543 // WriteStringTable() last in the first pass, to compute the correct length of the output.
544 if (string_first) {
545 WriteStringTable();
546 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700547 WriteClassTable();
548 WriteStackTraces();
Man Cao8c2ff642015-05-27 17:25:30 -0700549 if (!string_first) {
550 WriteStringTable();
551 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700552 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800553 }
554
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700555 void WriteClassTable() REQUIRES_SHARED(Locks::mutator_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700556 for (const auto& p : classes_) {
557 mirror::Class* c = p.first;
558 HprofClassSerialNumber sn = p.second;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800559 CHECK(c != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700560 output_->StartNewRecord(HPROF_TAG_LOAD_CLASS, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700561 // LOAD CLASS format:
562 // U4: class serial number (always > 0)
563 // ID: class object ID. We use the address of the class object structure as its ID.
564 // U4: stack trace serial number
565 // ID: class name string ID
Man Cao8c2ff642015-05-27 17:25:30 -0700566 __ AddU4(sn);
Andreas Gampe3a913092015-01-10 00:26:17 -0800567 __ AddObjectId(c);
Man Cao8c2ff642015-05-27 17:25:30 -0700568 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(c));
Andreas Gampe3a913092015-01-10 00:26:17 -0800569 __ AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700570 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700571 }
572
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700573 void WriteStringTable() {
Andreas Gampe1eeb00c2016-11-03 08:19:01 -0700574 for (const auto& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800575 const std::string& string = p.first;
Andreas Gampe1eeb00c2016-11-03 08:19:01 -0700576 const HprofStringId id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700577
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700578 output_->StartNewRecord(HPROF_TAG_STRING, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700579
580 // STRING format:
581 // ID: ID for this string
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700582 // U1*: UTF8 characters for string (NOT null terminated)
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700583 // (the record format encodes the length)
Andreas Gampe3a913092015-01-10 00:26:17 -0800584 __ AddU4(id);
585 __ AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700586 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700587 }
588
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700589 void StartNewHeapDumpSegment() {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700590 // This flushes the old segment and starts a new one.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700591 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700592 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700593 // Starting a new HEAP_DUMP resets the heap to default.
594 current_heap_ = HPROF_HEAP_DEFAULT;
595 }
596
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700597 void CheckHeapSegmentConstraints() {
598 if (objects_in_segment_ >= kMaxObjectsPerSegment || output_->Length() >= kMaxBytesPerSegment) {
599 StartNewHeapDumpSegment();
Andreas Gampe3a913092015-01-10 00:26:17 -0800600 }
601 }
602
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700603 void VisitRoot(mirror::Object* obj, const RootInfo& root_info)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700604 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800605 void MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700606 uint32_t thread_serial);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700607
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700608 HprofClassObjectId LookupClassId(mirror::Class* c) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800609 if (c != nullptr) {
Man Cao8c2ff642015-05-27 17:25:30 -0700610 auto it = classes_.find(c);
611 if (it == classes_.end()) {
612 // first time to see this class
613 HprofClassSerialNumber sn = next_class_serial_number_++;
614 classes_.Put(c, sn);
615 // Make sure that we've assigned a string ID for this class' name
616 LookupClassNameId(c);
617 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800618 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800619 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700620 }
621
Man Cao8c2ff642015-05-27 17:25:30 -0700622 HprofStackTraceSerialNumber LookupStackTraceSerialNumber(const mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700623 REQUIRES_SHARED(Locks::mutator_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700624 auto r = allocation_records_.find(obj);
625 if (r == allocation_records_.end()) {
626 return kHprofNullStackTrace;
627 } else {
628 const gc::AllocRecordStackTrace* trace = r->second;
629 auto result = traces_.find(trace);
630 CHECK(result != traces_.end());
631 return result->second;
632 }
633 }
634
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700635 HprofStringId LookupStringId(mirror::String* string) REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700636 return LookupStringId(string->ToModifiedUtf8());
637 }
638
639 HprofStringId LookupStringId(const char* string) {
640 return LookupStringId(std::string(string));
641 }
642
643 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800644 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700645 if (it != strings_.end()) {
646 return it->second;
647 }
648 HprofStringId id = next_string_id_++;
649 strings_.Put(string, id);
650 return id;
651 }
652
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700653 HprofStringId LookupClassNameId(mirror::Class* c) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700654 return LookupStringId(c->PrettyDescriptor());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700655 }
656
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700657 void WriteFixedHeader() {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500658 // Write the file header.
659 // U1: NUL-terminated magic string.
Andreas Gampe3a913092015-01-10 00:26:17 -0800660 const char magic[] = "JAVA PROFILE 1.0.3";
661 __ AddU1List(reinterpret_cast<const uint8_t*>(magic), sizeof(magic));
662
Calin Juravle32805172014-07-04 16:24:03 +0100663 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
664 // as uint32_t.
665 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800666 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
667 "Unexpected HeapReference size");
Andreas Gampe3a913092015-01-10 00:26:17 -0800668 __ AddU4(sizeof(uint32_t));
669
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500670 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700671 timeval now;
Andreas Gampe3a913092015-01-10 00:26:17 -0800672 const uint64_t nowMs = (gettimeofday(&now, nullptr) < 0) ? 0 :
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800673 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Andreas Gampe3a913092015-01-10 00:26:17 -0800674 // TODO: It seems it would be correct to use U8.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500675 // U4: high word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800676 __ AddU4(static_cast<uint32_t>(nowMs >> 32));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500677 // U4: low word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800678 __ AddU4(static_cast<uint32_t>(nowMs & 0xFFFFFFFF));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500679 }
680
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700681 void WriteStackTraces() REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700682 // Write a dummy stack trace record so the analysis tools don't freak out.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700683 output_->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
Man Cao8c2ff642015-05-27 17:25:30 -0700684 __ AddStackTraceSerialNumber(kHprofNullStackTrace);
Andreas Gampe3a913092015-01-10 00:26:17 -0800685 __ AddU4(kHprofNullThread);
686 __ AddU4(0); // no frames
Man Cao8c2ff642015-05-27 17:25:30 -0700687
688 // TODO: jhat complains "WARNING: Stack trace not found for serial # -1", but no trace should
689 // have -1 as its serial number (as long as HprofStackTraceSerialNumber doesn't overflow).
690 for (const auto& it : traces_) {
691 const gc::AllocRecordStackTrace* trace = it.first;
692 HprofStackTraceSerialNumber trace_sn = it.second;
693 size_t depth = trace->GetDepth();
694
695 // First write stack frames of the trace
696 for (size_t i = 0; i < depth; ++i) {
697 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
698 ArtMethod* method = frame->GetMethod();
699 CHECK(method != nullptr);
700 output_->StartNewRecord(HPROF_TAG_STACK_FRAME, kHprofTime);
701 // STACK FRAME format:
702 // ID: stack frame ID. We use the address of the AllocRecordStackTraceElement object as its ID.
703 // ID: method name string ID
704 // ID: method signature string ID
705 // ID: source file name string ID
706 // U4: class serial number
707 // U4: >0, line number; 0, no line information available; -1, unknown location
708 auto frame_result = frames_.find(frame);
709 CHECK(frame_result != frames_.end());
710 __ AddU4(frame_result->second);
711 __ AddStringId(LookupStringId(method->GetName()));
712 __ AddStringId(LookupStringId(method->GetSignature().ToString()));
713 const char* source_file = method->GetDeclaringClassSourceFile();
714 if (source_file == nullptr) {
715 source_file = "";
716 }
717 __ AddStringId(LookupStringId(source_file));
718 auto class_result = classes_.find(method->GetDeclaringClass());
719 CHECK(class_result != classes_.end());
720 __ AddU4(class_result->second);
721 __ AddU4(frame->ComputeLineNumber());
722 }
723
724 // Then write the trace itself
725 output_->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
726 // STACK TRACE format:
727 // U4: stack trace serial number. We use the address of the AllocRecordStackTrace object as its serial number.
728 // U4: thread serial number. We use Thread::GetTid().
729 // U4: number of frames
730 // [ID]*: series of stack frame ID's
731 __ AddStackTraceSerialNumber(trace_sn);
732 __ AddU4(trace->GetTid());
733 __ AddU4(depth);
734 for (size_t i = 0; i < depth; ++i) {
735 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
736 auto frame_result = frames_.find(frame);
737 CHECK(frame_result != frames_.end());
738 __ AddU4(frame_result->second);
739 }
740 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800741 }
742
743 bool DumpToDdmsBuffered(size_t overall_size ATTRIBUTE_UNUSED, size_t max_length ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700744 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800745 LOG(FATAL) << "Unimplemented";
746 UNREACHABLE();
747 // // Send the data off to DDMS.
748 // iovec iov[2];
749 // iov[0].iov_base = header_data_ptr_;
750 // iov[0].iov_len = header_data_size_;
751 // iov[1].iov_base = body_data_ptr_;
752 // iov[1].iov_len = body_data_size_;
753 // Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
754 }
755
756 bool DumpToFile(size_t overall_size, size_t max_length)
Mathieu Chartier90443472015-07-16 20:32:27 -0700757 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800758 // Where exactly are we writing to?
759 int out_fd;
760 if (fd_ >= 0) {
761 out_fd = dup(fd_);
762 if (out_fd < 0) {
763 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
764 return false;
765 }
766 } else {
767 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
768 if (out_fd < 0) {
769 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
770 strerror(errno));
771 return false;
772 }
773 }
774
775 std::unique_ptr<File> file(new File(out_fd, filename_, true));
776 bool okay;
777 {
778 FileEndianOutput file_output(file.get(), max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700779 output_ = &file_output;
780 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800781 okay = !file_output.Errors();
782
783 if (okay) {
Andreas Gampec515f212015-08-28 18:15:27 -0700784 // Check for expected size. Output is expected to be less-or-equal than first phase, see
785 // b/23521263.
786 DCHECK_LE(file_output.SumLength(), overall_size);
Andreas Gampe3a913092015-01-10 00:26:17 -0800787 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700788 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800789 }
790
791 if (okay) {
792 okay = file->FlushCloseOrErase() == 0;
793 } else {
794 file->Erase();
795 }
796 if (!okay) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800797 std::string msg(android::base::StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
798 filename_.c_str(),
799 strerror(errno)));
Andreas Gampe3a913092015-01-10 00:26:17 -0800800 ThrowRuntimeException("%s", msg.c_str());
801 LOG(ERROR) << msg;
802 }
803
804 return okay;
805 }
806
807 bool DumpToDdmsDirect(size_t overall_size, size_t max_length, uint32_t chunk_type)
Mathieu Chartier90443472015-07-16 20:32:27 -0700808 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800809 CHECK(direct_to_ddms_);
810 JDWP::JdwpState* state = Dbg::GetJdwpState();
811 CHECK(state != nullptr);
812 JDWP::JdwpNetStateBase* net_state = state->netState;
813 CHECK(net_state != nullptr);
814
815 // Hold the socket lock for the whole time since we want this to be atomic.
816 MutexLock mu(Thread::Current(), *net_state->GetSocketLock());
817
818 // Prepare the Ddms chunk.
819 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
820 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
821 state->SetupChunkHeader(chunk_type, overall_size, kChunkHeaderSize, chunk_header);
822
823 // Prepare the output and send the chunk header.
824 NetStateEndianOutput net_output(net_state, max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700825 output_ = &net_output;
Andreas Gampe3a913092015-01-10 00:26:17 -0800826 net_output.AddU1List(chunk_header, kChunkHeaderSize);
827
828 // Write the dump.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700829 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800830
Andreas Gampec515f212015-08-28 18:15:27 -0700831 // Check for expected size. See DumpToFile for comment.
832 DCHECK_LE(net_output.SumLength(), overall_size + kChunkHeaderSize);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700833 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800834
835 return true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700836 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500837
Man Cao8c2ff642015-05-27 17:25:30 -0700838 void PopulateAllocationTrackingTraces()
Mathieu Chartier90443472015-07-16 20:32:27 -0700839 REQUIRES(Locks::mutator_lock_, Locks::alloc_tracker_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700840 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
841 CHECK(records != nullptr);
842 HprofStackTraceSerialNumber next_trace_sn = kHprofNullStackTrace + 1;
843 HprofStackFrameId next_frame_id = 0;
Man Cao42c3c332015-06-23 16:38:25 -0700844 size_t count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -0700845
846 for (auto it = records->Begin(), end = records->End(); it != end; ++it) {
847 const mirror::Object* obj = it->first.Read();
Man Cao42c3c332015-06-23 16:38:25 -0700848 if (obj == nullptr) {
849 continue;
850 }
851 ++count;
Mathieu Chartier458b1052016-03-29 14:02:55 -0700852 const gc::AllocRecordStackTrace* trace = it->second.GetStackTrace();
Man Cao8c2ff642015-05-27 17:25:30 -0700853
854 // Copy the pair into a real hash map to speed up look up.
855 auto records_result = allocation_records_.emplace(obj, trace);
856 // The insertion should always succeed, i.e. no duplicate object pointers in "records"
857 CHECK(records_result.second);
858
859 // Generate serial numbers for traces, and IDs for frames.
860 auto traces_result = traces_.find(trace);
861 if (traces_result == traces_.end()) {
862 traces_.emplace(trace, next_trace_sn++);
863 // only check frames if the trace is newly discovered
864 for (size_t i = 0, depth = trace->GetDepth(); i < depth; ++i) {
865 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
866 auto frames_result = frames_.find(frame);
867 if (frames_result == frames_.end()) {
868 frames_.emplace(frame, next_frame_id++);
869 }
870 }
871 }
872 }
873 CHECK_EQ(traces_.size(), next_trace_sn - kHprofNullStackTrace - 1);
874 CHECK_EQ(frames_.size(), next_frame_id);
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800875 total_objects_with_stack_trace_ = count;
Man Cao8c2ff642015-05-27 17:25:30 -0700876 }
877
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700878 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
879 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
880 // only be used for debug messages.
881 std::string filename_;
882 int fd_;
883 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500884
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800885 uint64_t start_ns_ = NanoTime();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700886
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800887 EndianOutput* output_ = nullptr;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700888
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800889 HprofHeapId current_heap_ = HPROF_HEAP_DEFAULT; // Which heap we're currently dumping.
890 size_t objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700891
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800892 size_t total_objects_ = 0u;
893 size_t total_objects_with_stack_trace_ = 0u;
894
895 HprofStringId next_string_id_ = 0x400000;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800896 SafeMap<std::string, HprofStringId> strings_;
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800897 HprofClassSerialNumber next_class_serial_number_ = 1;
Man Cao8c2ff642015-05-27 17:25:30 -0700898 SafeMap<mirror::Class*, HprofClassSerialNumber> classes_;
899
900 std::unordered_map<const gc::AllocRecordStackTrace*, HprofStackTraceSerialNumber,
901 gc::HashAllocRecordTypesPtr<gc::AllocRecordStackTrace>,
902 gc::EqAllocRecordTypesPtr<gc::AllocRecordStackTrace>> traces_;
903 std::unordered_map<const gc::AllocRecordStackTraceElement*, HprofStackFrameId,
904 gc::HashAllocRecordTypesPtr<gc::AllocRecordStackTraceElement>,
905 gc::EqAllocRecordTypesPtr<gc::AllocRecordStackTraceElement>> frames_;
906 std::unordered_map<const mirror::Object*, const gc::AllocRecordStackTrace*> allocation_records_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700907
Richard Uhler4b767552016-04-26 13:28:59 -0700908 // Set used to keep track of what simple root records we have already
909 // emitted, to avoid emitting duplicate entries. The simple root records are
910 // those that contain no other information than the root type and the object
911 // id. A pair of root type and object id is packed into a uint64_t, with
912 // the root type in the upper 32 bits and the object id in the lower 32
913 // bits.
914 std::unordered_set<uint64_t> simple_roots_;
915
Mathieu Chartierecc82302017-02-16 10:20:12 -0800916 // To make sure we don't dump the same object multiple times. b/34967844
917 std::unordered_set<mirror::Object*> visited_objects_;
918
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700919 friend class GcRootVisitor;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700920 DISALLOW_COPY_AND_ASSIGN(Hprof);
921};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500922
Andreas Gampe3a913092015-01-10 00:26:17 -0800923static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* size_out) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500924 char c = sig[0];
925 HprofBasicType ret;
926 size_t size;
927
928 switch (c) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800929 case '[':
930 case 'L':
931 ret = hprof_basic_object;
932 size = 4;
933 break;
934 case 'Z':
935 ret = hprof_basic_boolean;
936 size = 1;
937 break;
938 case 'C':
939 ret = hprof_basic_char;
940 size = 2;
941 break;
942 case 'F':
943 ret = hprof_basic_float;
944 size = 4;
945 break;
946 case 'D':
947 ret = hprof_basic_double;
948 size = 8;
949 break;
950 case 'B':
951 ret = hprof_basic_byte;
952 size = 1;
953 break;
954 case 'S':
955 ret = hprof_basic_short;
956 size = 2;
957 break;
958 case 'I':
959 ret = hprof_basic_int;
960 size = 4;
961 break;
962 case 'J':
963 ret = hprof_basic_long;
964 size = 8;
965 break;
966 default:
967 LOG(FATAL) << "UNREACHABLE";
968 UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500969 }
970
Andreas Gampe3a913092015-01-10 00:26:17 -0800971 if (size_out != nullptr) {
972 *size_out = size;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500973 }
974
975 return ret;
976}
977
978// Always called when marking objects, but only does
979// something when ctx->gc_scan_state_ is non-zero, which is usually
980// only true when marking the root set or unreachable
981// objects. Used to add rootset references to obj.
Andreas Gampe3a913092015-01-10 00:26:17 -0800982void Hprof::MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700983 uint32_t thread_serial) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800984 if (heap_tag == 0) {
985 return;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500986 }
987
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700988 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500989
Andreas Gampe3a913092015-01-10 00:26:17 -0800990 switch (heap_tag) {
991 // ID: object ID
992 case HPROF_ROOT_UNKNOWN:
993 case HPROF_ROOT_STICKY_CLASS:
994 case HPROF_ROOT_MONITOR_USED:
995 case HPROF_ROOT_INTERNED_STRING:
996 case HPROF_ROOT_DEBUGGER:
Richard Uhler4b767552016-04-26 13:28:59 -0700997 case HPROF_ROOT_VM_INTERNAL: {
998 uint64_t key = (static_cast<uint64_t>(heap_tag) << 32) | PointerToLowMemUInt32(obj);
999 if (simple_roots_.insert(key).second) {
1000 __ AddU1(heap_tag);
1001 __ AddObjectId(obj);
1002 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001003 break;
Richard Uhler4b767552016-04-26 13:28:59 -07001004 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001005
Andreas Gampe3a913092015-01-10 00:26:17 -08001006 // ID: object ID
1007 // ID: JNI global ref ID
1008 case HPROF_ROOT_JNI_GLOBAL:
1009 __ AddU1(heap_tag);
1010 __ AddObjectId(obj);
1011 __ AddJniGlobalRefId(jni_obj);
1012 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001013
Andreas Gampe3a913092015-01-10 00:26:17 -08001014 // ID: object ID
1015 // U4: thread serial number
1016 // U4: frame number in stack trace (-1 for empty)
1017 case HPROF_ROOT_JNI_LOCAL:
1018 case HPROF_ROOT_JNI_MONITOR:
1019 case HPROF_ROOT_JAVA_FRAME:
1020 __ AddU1(heap_tag);
1021 __ AddObjectId(obj);
1022 __ AddU4(thread_serial);
1023 __ AddU4((uint32_t)-1);
1024 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001025
Andreas Gampe3a913092015-01-10 00:26:17 -08001026 // ID: object ID
1027 // U4: thread serial number
1028 case HPROF_ROOT_NATIVE_STACK:
1029 case HPROF_ROOT_THREAD_BLOCK:
1030 __ AddU1(heap_tag);
1031 __ AddObjectId(obj);
1032 __ AddU4(thread_serial);
1033 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001034
Andreas Gampe3a913092015-01-10 00:26:17 -08001035 // ID: thread object ID
1036 // U4: thread serial number
1037 // U4: stack trace serial number
1038 case HPROF_ROOT_THREAD_OBJECT:
1039 __ AddU1(heap_tag);
1040 __ AddObjectId(obj);
1041 __ AddU4(thread_serial);
1042 __ AddU4((uint32_t)-1); // xxx
1043 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001044
Andreas Gampe3a913092015-01-10 00:26:17 -08001045 case HPROF_CLASS_DUMP:
1046 case HPROF_INSTANCE_DUMP:
1047 case HPROF_OBJECT_ARRAY_DUMP:
1048 case HPROF_PRIMITIVE_ARRAY_DUMP:
1049 case HPROF_HEAP_DUMP_INFO:
1050 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
1051 // Ignored.
1052 break;
Elliott Hughes73e66f72012-05-09 09:34:45 -07001053
Andreas Gampe3a913092015-01-10 00:26:17 -08001054 case HPROF_ROOT_FINALIZING:
1055 case HPROF_ROOT_REFERENCE_CLEANUP:
1056 case HPROF_UNREACHABLE:
1057 LOG(FATAL) << "obsolete tag " << static_cast<int>(heap_tag);
1058 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001059 }
1060
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001061 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001062}
1063
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001064// Use for visiting the GcRoots held live by ArtFields, ArtMethods, and ClassLoaders.
1065class GcRootVisitor {
1066 public:
1067 explicit GcRootVisitor(Hprof* hprof) : hprof_(hprof) {}
1068
1069 void operator()(mirror::Object* obj ATTRIBUTE_UNUSED,
1070 MemberOffset offset ATTRIBUTE_UNUSED,
1071 bool is_static ATTRIBUTE_UNUSED) const {}
1072
1073 // Note that these don't have read barriers. Its OK however since the GC is guaranteed to not be
1074 // running during the hprof dumping process.
1075 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001076 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001077 if (!root->IsNull()) {
1078 VisitRoot(root);
1079 }
1080 }
1081
1082 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001083 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001084 mirror::Object* obj = root->AsMirrorPtr();
1085 // The two cases are either classes or dex cache arrays. If it is a dex cache array, then use
1086 // VM internal. Otherwise the object is a declaring class of an ArtField or ArtMethod or a
1087 // class from a ClassLoader.
1088 hprof_->VisitRoot(obj, RootInfo(obj->IsClass() ? kRootStickyClass : kRootVMInternal));
1089 }
1090
1091
1092 private:
1093 Hprof* const hprof_;
1094};
1095
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001096void Hprof::DumpHeapObject(mirror::Object* obj) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001097 // Ignore classes that are retired.
1098 if (obj->IsClass() && obj->AsClass()->IsRetired()) {
1099 return;
1100 }
Mathieu Chartierecc82302017-02-16 10:20:12 -08001101 DCHECK(visited_objects_.insert(obj).second) << "Already visited " << obj;
Andreas Gampe3a913092015-01-10 00:26:17 -08001102
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -08001103 ++total_objects_;
1104
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001105 GcRootVisitor visitor(this);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001106 obj->VisitReferences(visitor, VoidFunctor());
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001107
Mathieu Chartiere7158112015-06-03 13:32:15 -07001108 gc::Heap* const heap = Runtime::Current()->GetHeap();
1109 const gc::space::ContinuousSpace* const space = heap->FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001110 HprofHeapId heap_type = HPROF_HEAP_APP;
1111 if (space != nullptr) {
1112 if (space->IsZygoteSpace()) {
1113 heap_type = HPROF_HEAP_ZYGOTE;
Mathieu Chartier0b874522017-02-24 14:47:08 -08001114 } else if (space->IsImageSpace() && heap->ObjectIsInBootImageSpace(obj)) {
1115 // Only count objects in the boot image as HPROF_HEAP_IMAGE, this leaves app image objects as
1116 // HPROF_HEAP_APP. b/35762934
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001117 heap_type = HPROF_HEAP_IMAGE;
1118 }
Mathieu Chartiere7158112015-06-03 13:32:15 -07001119 } else {
1120 const auto* los = heap->GetLargeObjectsSpace();
1121 if (los->Contains(obj) && los->IsZygoteLargeObject(Thread::Current(), obj)) {
1122 heap_type = HPROF_HEAP_ZYGOTE;
1123 }
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001124 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001125 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001126
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001127 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001128 HprofStringId nameId;
1129
1130 // This object is in a different heap than the current one.
1131 // Emit a HEAP_DUMP_INFO tag to change heaps.
Andreas Gampe3a913092015-01-10 00:26:17 -08001132 __ AddU1(HPROF_HEAP_DUMP_INFO);
1133 __ AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001134 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001135 case HPROF_HEAP_APP:
1136 nameId = LookupStringId("app");
1137 break;
1138 case HPROF_HEAP_ZYGOTE:
1139 nameId = LookupStringId("zygote");
1140 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001141 case HPROF_HEAP_IMAGE:
1142 nameId = LookupStringId("image");
1143 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001144 default:
1145 // Internal error
1146 LOG(ERROR) << "Unexpected desiredHeap";
1147 nameId = LookupStringId("<ILLEGAL>");
1148 break;
1149 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001150 __ AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001151 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001152 }
1153
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001154 mirror::Class* c = obj->GetClass();
Andreas Gampe3a913092015-01-10 00:26:17 -08001155 if (c == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001156 // This object will bother HprofReader, because it has a null
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001157 // class, so just don't dump it. It could be
1158 // gDvm.unlinkedJavaLangClass or it could be an object just
1159 // allocated which hasn't been initialized yet.
1160 } else {
1161 if (obj->IsClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001162 DumpHeapClass(obj->AsClass());
Elliott Hughese84278b2012-03-22 10:06:53 -07001163 } else if (c->IsArrayClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001164 DumpHeapArray(obj->AsArray(), c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001165 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001166 DumpHeapInstanceObject(obj, c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001167 }
1168 }
1169
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001170 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001171}
1172
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001173void Hprof::DumpHeapClass(mirror::Class* klass) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001174 if (!klass->IsResolved()) {
Mathieu Chartier12393f32016-10-20 17:11:23 -07001175 // Class is allocated but not yet resolved: we cannot access its fields or super class.
Sebastien Hertzca068b22015-04-07 10:28:53 +02001176 return;
1177 }
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001178 const size_t num_static_fields = klass->NumStaticFields();
1179 // Total class size including embedded IMT, embedded vtable, and static fields.
1180 const size_t class_size = klass->GetClassSize();
1181 // Class size excluding static fields (relies on reference fields being the first static fields).
1182 const size_t class_size_without_overhead = sizeof(mirror::Class);
1183 CHECK_LE(class_size_without_overhead, class_size);
1184 const size_t overhead_size = class_size - class_size_without_overhead;
1185
1186 if (overhead_size != 0) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001187 // Create a byte array to reflect the allocation of the
1188 // StaticField array at the end of this class.
1189 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1190 __ AddClassStaticsId(klass);
Man Cao8c2ff642015-05-27 17:25:30 -07001191 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(klass));
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001192 __ AddU4(overhead_size);
Andreas Gampe3a913092015-01-10 00:26:17 -08001193 __ AddU1(hprof_basic_byte);
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001194 for (size_t i = 0; i < overhead_size; ++i) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001195 __ AddU1(0);
1196 }
1197 }
1198
1199 __ AddU1(HPROF_CLASS_DUMP);
1200 __ AddClassId(LookupClassId(klass));
Man Cao8c2ff642015-05-27 17:25:30 -07001201 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001202 __ AddClassId(LookupClassId(klass->GetSuperClass()));
1203 __ AddObjectId(klass->GetClassLoader());
1204 __ AddObjectId(nullptr); // no signer
1205 __ AddObjectId(nullptr); // no prot domain
1206 __ AddObjectId(nullptr); // reserved
1207 __ AddObjectId(nullptr); // reserved
1208 if (klass->IsClassClass()) {
1209 // ClassObjects have their static fields appended, so aren't all the same size.
1210 // But they're at least this size.
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001211 __ AddU4(class_size_without_overhead); // instance size
Jeff Hao0ce43532015-05-12 18:58:32 -07001212 } else if (klass->IsStringClass()) {
1213 // Strings are variable length with character data at the end like arrays.
1214 // This outputs the size of an empty string.
1215 __ AddU4(sizeof(mirror::String));
1216 } else if (klass->IsArrayClass() || klass->IsPrimitive()) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001217 __ AddU4(0);
1218 } else {
1219 __ AddU4(klass->GetObjectSize()); // instance size
1220 }
1221
1222 __ AddU2(0); // empty const pool
1223
1224 // Static fields
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001225 if (overhead_size == 0) {
1226 __ AddU2(static_cast<uint16_t>(0));
Andreas Gampe3a913092015-01-10 00:26:17 -08001227 } else {
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001228 __ AddU2(static_cast<uint16_t>(num_static_fields + 1));
1229 __ AddStringId(LookupStringId(kClassOverheadName));
Andreas Gampe3a913092015-01-10 00:26:17 -08001230 __ AddU1(hprof_basic_object);
1231 __ AddClassStaticsId(klass);
1232
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001233 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001234 ArtField* f = klass->GetStaticField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001235
1236 size_t size;
1237 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1238 __ AddStringId(LookupStringId(f->GetName()));
1239 __ AddU1(t);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001240 switch (t) {
1241 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001242 __ AddU1(f->GetByte(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001243 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001244 case hprof_basic_boolean:
1245 __ AddU1(f->GetBoolean(klass));
1246 break;
1247 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001248 __ AddU2(f->GetChar(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001249 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001250 case hprof_basic_short:
1251 __ AddU2(f->GetShort(klass));
1252 break;
1253 case hprof_basic_float:
1254 case hprof_basic_int:
1255 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001256 __ AddU4(f->Get32(klass));
1257 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001258 case hprof_basic_double:
1259 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001260 __ AddU8(f->Get64(klass));
1261 break;
1262 default:
1263 LOG(FATAL) << "Unexpected size " << size;
1264 UNREACHABLE();
1265 }
1266 }
1267 }
1268
1269 // Instance fields for this class (no superclass fields)
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001270 int iFieldCount = klass->NumInstanceFields();
Jeff Hao848f70a2014-01-15 13:49:50 -08001271 if (klass->IsStringClass()) {
1272 __ AddU2((uint16_t)iFieldCount + 1);
1273 } else {
1274 __ AddU2((uint16_t)iFieldCount);
1275 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001276 for (int i = 0; i < iFieldCount; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001277 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001278 __ AddStringId(LookupStringId(f->GetName()));
1279 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), nullptr);
1280 __ AddU1(t);
1281 }
Vladimir Marko595beb32017-02-06 14:11:54 +00001282 // Add native value character array for strings / byte array for compressed strings.
Jeff Hao848f70a2014-01-15 13:49:50 -08001283 if (klass->IsStringClass()) {
1284 __ AddStringId(LookupStringId("value"));
1285 __ AddU1(hprof_basic_object);
1286 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001287}
1288
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001289void Hprof::DumpHeapArray(mirror::Array* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001290 uint32_t length = obj->GetLength();
1291
1292 if (obj->IsObjectArray()) {
1293 // obj is an object array.
1294 __ AddU1(HPROF_OBJECT_ARRAY_DUMP);
1295
1296 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001297 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001298 __ AddU4(length);
1299 __ AddClassId(LookupClassId(klass));
1300
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001301 // Dump the elements, which are always objects or null.
Andreas Gampe3a913092015-01-10 00:26:17 -08001302 __ AddIdList(obj->AsObjectArray<mirror::Object>());
1303 } else {
1304 size_t size;
1305 HprofBasicType t = SignatureToBasicTypeAndSize(
1306 Primitive::Descriptor(klass->GetComponentType()->GetPrimitiveType()), &size);
1307
1308 // obj is a primitive array.
1309 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1310
1311 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001312 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001313 __ AddU4(length);
1314 __ AddU1(t);
1315
1316 // Dump the raw, packed element values.
1317 if (size == 1) {
1318 __ AddU1List(reinterpret_cast<const uint8_t*>(obj->GetRawData(sizeof(uint8_t), 0)), length);
1319 } else if (size == 2) {
1320 __ AddU2List(reinterpret_cast<const uint16_t*>(obj->GetRawData(sizeof(uint16_t), 0)), length);
1321 } else if (size == 4) {
1322 __ AddU4List(reinterpret_cast<const uint32_t*>(obj->GetRawData(sizeof(uint32_t), 0)), length);
1323 } else if (size == 8) {
1324 __ AddU8List(reinterpret_cast<const uint64_t*>(obj->GetRawData(sizeof(uint64_t), 0)), length);
1325 }
1326 }
1327}
1328
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001329void Hprof::DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001330 // obj is an instance object.
1331 __ AddU1(HPROF_INSTANCE_DUMP);
1332 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001333 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001334 __ AddClassId(LookupClassId(klass));
1335
1336 // Reserve some space for the length of the instance data, which we won't
1337 // know until we're done writing it.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001338 size_t size_patch_offset = output_->Length();
Andreas Gampe3a913092015-01-10 00:26:17 -08001339 __ AddU4(0x77777777);
1340
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001341 // What we will use for the string value if the object is a string.
1342 mirror::Object* string_value = nullptr;
1343
1344 // Write the instance data; fields for this class, followed by super class fields, and so on.
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001345 do {
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001346 const size_t instance_fields = klass->NumInstanceFields();
1347 for (size_t i = 0; i < instance_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001348 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001349 size_t size;
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001350 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001351 switch (t) {
1352 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001353 __ AddU1(f->GetByte(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001354 break;
1355 case hprof_basic_boolean:
1356 __ AddU1(f->GetBoolean(obj));
1357 break;
1358 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001359 __ AddU2(f->GetChar(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001360 break;
1361 case hprof_basic_short:
1362 __ AddU2(f->GetShort(obj));
1363 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001364 case hprof_basic_int:
Vladimir Marko595beb32017-02-06 14:11:54 +00001365 if (mirror::kUseStringCompression &&
1366 klass->IsStringClass() &&
1367 f->GetOffset().SizeValue() == mirror::String::CountOffset().SizeValue()) {
1368 // Store the string length instead of the raw count field with compression flag.
1369 __ AddU4(obj->AsString()->GetLength());
1370 break;
1371 }
1372 FALLTHROUGH_INTENDED;
1373 case hprof_basic_float:
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001374 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001375 __ AddU4(f->Get32(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001376 break;
1377 case hprof_basic_double:
1378 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001379 __ AddU8(f->Get64(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001380 break;
Andreas Gampe3a913092015-01-10 00:26:17 -08001381 }
1382 }
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001383 // Add value field for String if necessary.
1384 if (klass->IsStringClass()) {
1385 mirror::String* s = obj->AsString();
1386 if (s->GetLength() == 0) {
1387 // If string is empty, use an object-aligned address within the string for the value.
1388 string_value = reinterpret_cast<mirror::Object*>(
1389 reinterpret_cast<uintptr_t>(s) + kObjectAlignment);
1390 } else {
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001391 if (s->IsCompressed()) {
1392 string_value = reinterpret_cast<mirror::Object*>(s->GetValueCompressed());
1393 } else {
1394 string_value = reinterpret_cast<mirror::Object*>(s->GetValue());
1395 }
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001396 }
1397 __ AddObjectId(string_value);
1398 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001399
1400 klass = klass->GetSuperClass();
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001401 } while (klass != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -08001402
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001403 // Patch the instance field length.
1404 __ UpdateU4(size_patch_offset, output_->Length() - (size_patch_offset + 4));
1405
Jeff Hao848f70a2014-01-15 13:49:50 -08001406 // Output native value character array for strings.
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001407 CHECK_EQ(obj->IsString(), string_value != nullptr);
1408 if (string_value != nullptr) {
Jeff Hao848f70a2014-01-15 13:49:50 -08001409 mirror::String* s = obj->AsString();
Jeff Hao848f70a2014-01-15 13:49:50 -08001410 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001411 __ AddObjectId(string_value);
Man Cao8c2ff642015-05-27 17:25:30 -07001412 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Vladimir Marko595beb32017-02-06 14:11:54 +00001413 __ AddU4(s->GetLength());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001414 if (s->IsCompressed()) {
Vladimir Marko595beb32017-02-06 14:11:54 +00001415 __ AddU1(hprof_basic_byte);
1416 __ AddU1List(s->GetValueCompressed(), s->GetLength());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001417 } else {
Vladimir Marko595beb32017-02-06 14:11:54 +00001418 __ AddU1(hprof_basic_char);
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001419 __ AddU2List(s->GetValue(), s->GetLength());
1420 }
Jeff Hao848f70a2014-01-15 13:49:50 -08001421 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001422}
1423
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001424void Hprof::VisitRoot(mirror::Object* obj, const RootInfo& info) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001425 static const HprofHeapTag xlate[] = {
1426 HPROF_ROOT_UNKNOWN,
1427 HPROF_ROOT_JNI_GLOBAL,
1428 HPROF_ROOT_JNI_LOCAL,
1429 HPROF_ROOT_JAVA_FRAME,
1430 HPROF_ROOT_NATIVE_STACK,
1431 HPROF_ROOT_STICKY_CLASS,
1432 HPROF_ROOT_THREAD_BLOCK,
1433 HPROF_ROOT_MONITOR_USED,
1434 HPROF_ROOT_THREAD_OBJECT,
1435 HPROF_ROOT_INTERNED_STRING,
1436 HPROF_ROOT_FINALIZING,
1437 HPROF_ROOT_DEBUGGER,
1438 HPROF_ROOT_REFERENCE_CLEANUP,
1439 HPROF_ROOT_VM_INTERNAL,
1440 HPROF_ROOT_JNI_MONITOR,
1441 };
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001442 CHECK_LT(info.GetType(), sizeof(xlate) / sizeof(HprofHeapTag));
Andreas Gampe3a913092015-01-10 00:26:17 -08001443 if (obj == nullptr) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001444 return;
1445 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001446 MarkRootObject(obj, 0, xlate[info.GetType()], info.GetThreadId());
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001447}
1448
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001449// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1450// sent directly to DDMS.
1451// If "fd" is >= 0, the output will be written to that file descriptor.
1452// Otherwise, "filename" is used to create an output file.
1453void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001454 CHECK(filename != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001455 Thread* self = Thread::Current();
Mathieu Chartierecc82302017-02-16 10:20:12 -08001456 // Need to take a heap dump while GC isn't running. See the comment in Heap::VisitObjects().
1457 // Also we need the critical section to avoid visiting the same object twice. See b/34967844
1458 gc::ScopedGCCriticalSection gcs(self,
1459 gc::kGcCauseHprof,
1460 gc::kCollectorTypeHprof);
1461 ScopedSuspendAll ssa(__FUNCTION__, true /* long suspend */);
1462 Hprof hprof(filename, fd, direct_to_ddms);
1463 hprof.Dump();
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001464}
1465
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001466} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001467} // namespace art