blob: 4f390fd30a90014fd393252485ece128be9c1a43 [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"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080043#include "art_method-inl.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080044#include "base/logging.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010045#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080046#include "base/unix_file/fd_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080047#include "class_linker.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080048#include "common_throws.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040049#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070050#include "dex_file-inl.h"
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -080051#include "gc_root.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "gc/accounting/heap_bitmap.h"
Man Cao8c2ff642015-05-27 17:25:30 -070053#include "gc/allocation_record.h"
Mathieu Chartierecc82302017-02-16 10:20:12 -080054#include "gc/scoped_gc_critical_section.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070055#include "gc/heap.h"
56#include "gc/space/space.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070057#include "globals.h"
Mathieu Chartierad466ad2015-01-08 16:28:08 -080058#include "jdwp/jdwp.h"
59#include "jdwp/jdwp_priv.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/class.h"
61#include "mirror/class-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080062#include "mirror/object-refvisitor-inl.h"
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -070063#include "os.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070064#include "safe_map.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070065#include "scoped_thread_state_change-inl.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070066#include "thread_list.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040067
68namespace art {
69
70namespace hprof {
71
Mathieu Chartierad466ad2015-01-08 16:28:08 -080072static constexpr bool kDirectStream = true;
Jesse Wilson0c54ac12011-11-09 15:14:05 -050073
Andreas Gampe3a913092015-01-10 00:26:17 -080074static constexpr uint32_t kHprofTime = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -080075static constexpr uint32_t kHprofNullThread = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -070076
Andreas Gampe3a913092015-01-10 00:26:17 -080077static constexpr size_t kMaxObjectsPerSegment = 128;
78static constexpr size_t kMaxBytesPerSegment = 4096;
Elliott Hughes622a6982012-06-08 17:58:54 -070079
Andreas Gampe3a913092015-01-10 00:26:17 -080080// The static field-name for the synthetic object generated to account for class static overhead.
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -070081static constexpr const char* kClassOverheadName = "$classOverhead";
Elliott Hughes622a6982012-06-08 17:58:54 -070082
83enum HprofTag {
84 HPROF_TAG_STRING = 0x01,
85 HPROF_TAG_LOAD_CLASS = 0x02,
86 HPROF_TAG_UNLOAD_CLASS = 0x03,
87 HPROF_TAG_STACK_FRAME = 0x04,
88 HPROF_TAG_STACK_TRACE = 0x05,
89 HPROF_TAG_ALLOC_SITES = 0x06,
90 HPROF_TAG_HEAP_SUMMARY = 0x07,
91 HPROF_TAG_START_THREAD = 0x0A,
92 HPROF_TAG_END_THREAD = 0x0B,
93 HPROF_TAG_HEAP_DUMP = 0x0C,
94 HPROF_TAG_HEAP_DUMP_SEGMENT = 0x1C,
95 HPROF_TAG_HEAP_DUMP_END = 0x2C,
96 HPROF_TAG_CPU_SAMPLES = 0x0D,
97 HPROF_TAG_CONTROL_SETTINGS = 0x0E,
98};
99
100// Values for the first byte of HEAP_DUMP and HEAP_DUMP_SEGMENT records:
101enum HprofHeapTag {
102 // Traditional.
103 HPROF_ROOT_UNKNOWN = 0xFF,
104 HPROF_ROOT_JNI_GLOBAL = 0x01,
105 HPROF_ROOT_JNI_LOCAL = 0x02,
106 HPROF_ROOT_JAVA_FRAME = 0x03,
107 HPROF_ROOT_NATIVE_STACK = 0x04,
108 HPROF_ROOT_STICKY_CLASS = 0x05,
109 HPROF_ROOT_THREAD_BLOCK = 0x06,
110 HPROF_ROOT_MONITOR_USED = 0x07,
111 HPROF_ROOT_THREAD_OBJECT = 0x08,
112 HPROF_CLASS_DUMP = 0x20,
113 HPROF_INSTANCE_DUMP = 0x21,
114 HPROF_OBJECT_ARRAY_DUMP = 0x22,
115 HPROF_PRIMITIVE_ARRAY_DUMP = 0x23,
116
117 // Android.
118 HPROF_HEAP_DUMP_INFO = 0xfe,
119 HPROF_ROOT_INTERNED_STRING = 0x89,
120 HPROF_ROOT_FINALIZING = 0x8a, // Obsolete.
121 HPROF_ROOT_DEBUGGER = 0x8b,
122 HPROF_ROOT_REFERENCE_CLEANUP = 0x8c, // Obsolete.
123 HPROF_ROOT_VM_INTERNAL = 0x8d,
124 HPROF_ROOT_JNI_MONITOR = 0x8e,
125 HPROF_UNREACHABLE = 0x90, // Obsolete.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700126 HPROF_PRIMITIVE_ARRAY_NODATA_DUMP = 0xc3, // Obsolete.
Elliott Hughes622a6982012-06-08 17:58:54 -0700127};
128
129enum HprofHeapId {
130 HPROF_HEAP_DEFAULT = 0,
131 HPROF_HEAP_ZYGOTE = 'Z',
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700132 HPROF_HEAP_APP = 'A',
133 HPROF_HEAP_IMAGE = 'I',
Elliott Hughes622a6982012-06-08 17:58:54 -0700134};
135
136enum HprofBasicType {
137 hprof_basic_object = 2,
138 hprof_basic_boolean = 4,
139 hprof_basic_char = 5,
140 hprof_basic_float = 6,
141 hprof_basic_double = 7,
142 hprof_basic_byte = 8,
143 hprof_basic_short = 9,
144 hprof_basic_int = 10,
145 hprof_basic_long = 11,
146};
147
Ian Rogersef7d42f2014-01-06 12:55:46 -0800148typedef uint32_t HprofStringId;
149typedef uint32_t HprofClassObjectId;
Man Cao8c2ff642015-05-27 17:25:30 -0700150typedef uint32_t HprofClassSerialNumber;
151typedef uint32_t HprofStackTraceSerialNumber;
152typedef uint32_t HprofStackFrameId;
153static constexpr HprofStackTraceSerialNumber kHprofNullStackTrace = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -0700154
Andreas Gampe3a913092015-01-10 00:26:17 -0800155class EndianOutput {
Elliott Hughes622a6982012-06-08 17:58:54 -0700156 public:
Andreas Gampe3a913092015-01-10 00:26:17 -0800157 EndianOutput() : length_(0), sum_length_(0), max_length_(0), started_(false) {}
158 virtual ~EndianOutput() {}
159
160 void StartNewRecord(uint8_t tag, uint32_t time) {
161 if (length_ > 0) {
162 EndRecord();
163 }
164 DCHECK_EQ(length_, 0U);
165 AddU1(tag);
166 AddU4(time);
167 AddU4(0xdeaddead); // Length, replaced on flush.
168 started_ = true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700169 }
170
Andreas Gampe3a913092015-01-10 00:26:17 -0800171 void EndRecord() {
172 // Replace length in header.
173 if (started_) {
174 UpdateU4(sizeof(uint8_t) + sizeof(uint32_t),
175 length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
176 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700177
Andreas Gampe3a913092015-01-10 00:26:17 -0800178 HandleEndRecord();
179
180 sum_length_ += length_;
181 max_length_ = std::max(max_length_, length_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700182 length_ = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -0800183 started_ = false;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700184 }
185
Andreas Gampe3a913092015-01-10 00:26:17 -0800186 void AddU1(uint8_t value) {
187 AddU1List(&value, 1);
188 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800189 void AddU2(uint16_t value) {
190 AddU2List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700191 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800192 void AddU4(uint32_t value) {
193 AddU4List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700194 }
195
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800196 void AddU8(uint64_t value) {
197 AddU8List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700198 }
199
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800200 void AddObjectId(const mirror::Object* value) {
201 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800202 }
203
Man Cao8c2ff642015-05-27 17:25:30 -0700204 void AddStackTraceSerialNumber(HprofStackTraceSerialNumber value) {
205 AddU4(value);
206 }
207
Ian Rogersef7d42f2014-01-06 12:55:46 -0800208 // The ID for the synthetic object generated to account for class static overhead.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800209 void AddClassStaticsId(const mirror::Class* value) {
210 AddU4(1 | PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800211 }
212
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800213 void AddJniGlobalRefId(jobject value) {
214 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800215 }
216
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800217 void AddClassId(HprofClassObjectId value) {
218 AddU4(value);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800219 }
220
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800221 void AddStringId(HprofStringId value) {
222 AddU4(value);
Elliott Hughes622a6982012-06-08 17:58:54 -0700223 }
224
Andreas Gampe3a913092015-01-10 00:26:17 -0800225 void AddU1List(const uint8_t* values, size_t count) {
226 HandleU1List(values, count);
227 length_ += count;
228 }
229 void AddU2List(const uint16_t* values, size_t count) {
230 HandleU2List(values, count);
231 length_ += count * sizeof(uint16_t);
232 }
233 void AddU4List(const uint32_t* values, size_t count) {
234 HandleU4List(values, count);
235 length_ += count * sizeof(uint32_t);
236 }
Andreas Gampeca714582015-04-03 19:41:34 -0700237 virtual void UpdateU4(size_t offset, uint32_t new_value ATTRIBUTE_UNUSED) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800238 DCHECK_LE(offset, length_ - 4);
239 }
240 void AddU8List(const uint64_t* values, size_t count) {
241 HandleU8List(values, count);
242 length_ += count * sizeof(uint64_t);
243 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700244
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800245 void AddIdList(mirror::ObjectArray<mirror::Object>* values)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700246 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800247 const int32_t length = values->GetLength();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800248 for (int32_t i = 0; i < length; ++i) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800249 AddObjectId(values->GetWithoutChecks(i));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800250 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700251 }
252
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800253 void AddUtf8String(const char* str) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700254 // The terminating NUL character is NOT written.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800255 AddU1List((const uint8_t*)str, strlen(str));
Elliott Hughes622a6982012-06-08 17:58:54 -0700256 }
257
Andreas Gampe3a913092015-01-10 00:26:17 -0800258 size_t Length() const {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700259 return length_;
260 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700261
Andreas Gampe3a913092015-01-10 00:26:17 -0800262 size_t SumLength() const {
263 return sum_length_;
Elliott Hughes622a6982012-06-08 17:58:54 -0700264 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700265
Andreas Gampe3a913092015-01-10 00:26:17 -0800266 size_t MaxLength() const {
267 return max_length_;
268 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700269
Andreas Gampe3a913092015-01-10 00:26:17 -0800270 protected:
271 virtual void HandleU1List(const uint8_t* values ATTRIBUTE_UNUSED,
272 size_t count ATTRIBUTE_UNUSED) {
273 }
jessicahandojo3aaa37b2016-07-29 14:46:37 -0700274 virtual void HandleU1AsU2List(const uint8_t* values ATTRIBUTE_UNUSED,
275 size_t count ATTRIBUTE_UNUSED) {
276 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800277 virtual void HandleU2List(const uint16_t* values ATTRIBUTE_UNUSED,
278 size_t count ATTRIBUTE_UNUSED) {
279 }
280 virtual void HandleU4List(const uint32_t* values ATTRIBUTE_UNUSED,
281 size_t count ATTRIBUTE_UNUSED) {
282 }
283 virtual void HandleU8List(const uint64_t* values ATTRIBUTE_UNUSED,
284 size_t count ATTRIBUTE_UNUSED) {
285 }
286 virtual void HandleEndRecord() {
287 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700288
Andreas Gampe3a913092015-01-10 00:26:17 -0800289 size_t length_; // Current record size.
290 size_t sum_length_; // Size of all data.
291 size_t max_length_; // Maximum seen length.
292 bool started_; // Was StartRecord called?
Elliott Hughes622a6982012-06-08 17:58:54 -0700293};
294
Andreas Gampe3a913092015-01-10 00:26:17 -0800295// This keeps things buffered until flushed.
296class EndianOutputBuffered : public EndianOutput {
297 public:
298 explicit EndianOutputBuffered(size_t reserve_size) {
299 buffer_.reserve(reserve_size);
300 }
301 virtual ~EndianOutputBuffered() {}
302
303 void UpdateU4(size_t offset, uint32_t new_value) OVERRIDE {
304 DCHECK_LE(offset, length_ - 4);
305 buffer_[offset + 0] = static_cast<uint8_t>((new_value >> 24) & 0xFF);
306 buffer_[offset + 1] = static_cast<uint8_t>((new_value >> 16) & 0xFF);
307 buffer_[offset + 2] = static_cast<uint8_t>((new_value >> 8) & 0xFF);
308 buffer_[offset + 3] = static_cast<uint8_t>((new_value >> 0) & 0xFF);
309 }
310
311 protected:
312 void HandleU1List(const uint8_t* values, size_t count) OVERRIDE {
313 DCHECK_EQ(length_, buffer_.size());
314 buffer_.insert(buffer_.end(), values, values + count);
315 }
316
jessicahandojo3aaa37b2016-07-29 14:46:37 -0700317 void HandleU1AsU2List(const uint8_t* values, size_t count) OVERRIDE {
318 DCHECK_EQ(length_, buffer_.size());
319 // All 8-bits are grouped in 2 to make 16-bit block like Java Char
320 if (count & 1) {
321 buffer_.push_back(0);
322 }
323 for (size_t i = 0; i < count; ++i) {
324 uint8_t value = *values;
325 buffer_.push_back(value);
326 values++;
327 }
328 }
329
Andreas Gampe3a913092015-01-10 00:26:17 -0800330 void HandleU2List(const uint16_t* values, size_t count) OVERRIDE {
331 DCHECK_EQ(length_, buffer_.size());
332 for (size_t i = 0; i < count; ++i) {
333 uint16_t value = *values;
334 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
335 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
336 values++;
337 }
338 }
339
340 void HandleU4List(const uint32_t* values, size_t count) OVERRIDE {
341 DCHECK_EQ(length_, buffer_.size());
342 for (size_t i = 0; i < count; ++i) {
343 uint32_t value = *values;
344 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
345 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
346 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
347 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
348 values++;
349 }
350 }
351
352 void HandleU8List(const uint64_t* values, size_t count) OVERRIDE {
353 DCHECK_EQ(length_, buffer_.size());
354 for (size_t i = 0; i < count; ++i) {
355 uint64_t value = *values;
356 buffer_.push_back(static_cast<uint8_t>((value >> 56) & 0xFF));
357 buffer_.push_back(static_cast<uint8_t>((value >> 48) & 0xFF));
358 buffer_.push_back(static_cast<uint8_t>((value >> 40) & 0xFF));
359 buffer_.push_back(static_cast<uint8_t>((value >> 32) & 0xFF));
360 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
361 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
362 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
363 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
364 values++;
365 }
366 }
367
368 void HandleEndRecord() OVERRIDE {
369 DCHECK_EQ(buffer_.size(), length_);
370 if (kIsDebugBuild && started_) {
371 uint32_t stored_length =
372 static_cast<uint32_t>(buffer_[5]) << 24 |
373 static_cast<uint32_t>(buffer_[6]) << 16 |
374 static_cast<uint32_t>(buffer_[7]) << 8 |
375 static_cast<uint32_t>(buffer_[8]);
376 DCHECK_EQ(stored_length, length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
377 }
378 HandleFlush(buffer_.data(), length_);
379 buffer_.clear();
380 }
381
382 virtual void HandleFlush(const uint8_t* buffer ATTRIBUTE_UNUSED, size_t length ATTRIBUTE_UNUSED) {
383 }
384
385 std::vector<uint8_t> buffer_;
386};
387
388class FileEndianOutput FINAL : public EndianOutputBuffered {
389 public:
390 FileEndianOutput(File* fp, size_t reserved_size)
391 : EndianOutputBuffered(reserved_size), fp_(fp), errors_(false) {
392 DCHECK(fp != nullptr);
393 }
394 ~FileEndianOutput() {
395 }
396
397 bool Errors() {
398 return errors_;
399 }
400
401 protected:
402 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
403 if (!errors_) {
404 errors_ = !fp_->WriteFully(buffer, length);
405 }
406 }
407
408 private:
409 File* fp_;
410 bool errors_;
411};
412
413class NetStateEndianOutput FINAL : public EndianOutputBuffered {
414 public:
415 NetStateEndianOutput(JDWP::JdwpNetStateBase* net_state, size_t reserved_size)
416 : EndianOutputBuffered(reserved_size), net_state_(net_state) {
417 DCHECK(net_state != nullptr);
418 }
419 ~NetStateEndianOutput() {}
420
421 protected:
422 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
423 std::vector<iovec> iov;
424 iov.push_back(iovec());
425 iov[0].iov_base = const_cast<void*>(reinterpret_cast<const void*>(buffer));
426 iov[0].iov_len = length;
427 net_state_->WriteBufferedPacketLocked(iov);
428 }
429
430 private:
431 JDWP::JdwpNetStateBase* net_state_;
432};
433
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700434#define __ output_->
Andreas Gampe3a913092015-01-10 00:26:17 -0800435
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700436class Hprof : public SingleRootVisitor {
Elliott Hughes622a6982012-06-08 17:58:54 -0700437 public:
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700438 Hprof(const char* output_filename, int fd, bool direct_to_ddms)
439 : filename_(output_filename),
440 fd_(fd),
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800441 direct_to_ddms_(direct_to_ddms) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700442 LOG(INFO) << "hprof: heap dump \"" << filename_ << "\" starting...";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500443 }
444
Andreas Gampe3a913092015-01-10 00:26:17 -0800445 void Dump()
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800446 REQUIRES(Locks::mutator_lock_)
447 REQUIRES(!Locks::heap_bitmap_lock_, !Locks::alloc_tracker_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700448 {
449 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
450 if (Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
451 PopulateAllocationTrackingTraces();
452 }
453 }
454
Andreas Gampe3a913092015-01-10 00:26:17 -0800455 // First pass to measure the size of the dump.
456 size_t overall_size;
457 size_t max_length;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800458 {
Andreas Gampe3a913092015-01-10 00:26:17 -0800459 EndianOutput count_output;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700460 output_ = &count_output;
461 ProcessHeap(false);
Andreas Gampe3a913092015-01-10 00:26:17 -0800462 overall_size = count_output.SumLength();
463 max_length = count_output.MaxLength();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700464 output_ = nullptr;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800465 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700466
Andreas Gampe3a913092015-01-10 00:26:17 -0800467 bool okay;
Mathieu Chartierecc82302017-02-16 10:20:12 -0800468 visited_objects_.clear();
Andreas Gampe3a913092015-01-10 00:26:17 -0800469 if (direct_to_ddms_) {
470 if (kDirectStream) {
471 okay = DumpToDdmsDirect(overall_size, max_length, CHUNK_TYPE("HPDS"));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700472 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800473 okay = DumpToDdmsBuffered(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700474 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800475 } else {
476 okay = DumpToFile(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700477 }
478
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700479 if (okay) {
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800480 const uint64_t duration = NanoTime() - start_ns_;
481 LOG(INFO) << "hprof: heap dump completed (" << PrettySize(RoundUp(overall_size, KB))
482 << ") in " << PrettyDuration(duration)
483 << " objects " << total_objects_
484 << " objects with stack traces " << total_objects_with_stack_trace_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700485 }
486 }
487
488 private:
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800489 static void VisitObjectCallback(mirror::Object* obj, void* arg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700490 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800491 DCHECK(obj != nullptr);
492 DCHECK(arg != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700493 reinterpret_cast<Hprof*>(arg)->DumpHeapObject(obj);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700494 }
495
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700496 void DumpHeapObject(mirror::Object* obj)
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 DumpHeapClass(mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700500 REQUIRES_SHARED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700501
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700502 void DumpHeapArray(mirror::Array* 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 DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700506 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800507
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700508 void ProcessHeap(bool header_first)
Mathieu Chartier90443472015-07-16 20:32:27 -0700509 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800510 // Reset current heap and object count.
511 current_heap_ = HPROF_HEAP_DEFAULT;
512 objects_in_segment_ = 0;
513
514 if (header_first) {
Man Cao8c2ff642015-05-27 17:25:30 -0700515 ProcessHeader(true);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700516 ProcessBody();
Andreas Gampe3a913092015-01-10 00:26:17 -0800517 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700518 ProcessBody();
Man Cao8c2ff642015-05-27 17:25:30 -0700519 ProcessHeader(false);
Andreas Gampe3a913092015-01-10 00:26:17 -0800520 }
521 }
522
Mathieu Chartier90443472015-07-16 20:32:27 -0700523 void ProcessBody() REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700524 Runtime* const runtime = Runtime::Current();
Andreas Gampe3a913092015-01-10 00:26:17 -0800525 // Walk the roots and the heap.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700526 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Andreas Gampe3a913092015-01-10 00:26:17 -0800527
Richard Uhler4b767552016-04-26 13:28:59 -0700528 simple_roots_.clear();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700529 runtime->VisitRoots(this);
530 runtime->VisitImageRoots(this);
531 runtime->GetHeap()->VisitObjectsPaused(VisitObjectCallback, this);
Andreas Gampe3a913092015-01-10 00:26:17 -0800532
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700533 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_END, kHprofTime);
534 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800535 }
536
Mathieu Chartier90443472015-07-16 20:32:27 -0700537 void ProcessHeader(bool string_first) REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800538 // Write the header.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700539 WriteFixedHeader();
Andreas Gampe3a913092015-01-10 00:26:17 -0800540 // Write the string and class tables, and any stack traces, to the header.
541 // (jhat requires that these appear before any of the data in the body that refers to them.)
Man Cao8c2ff642015-05-27 17:25:30 -0700542 // jhat also requires the string table appear before class table and stack traces.
543 // However, WriteStackTraces() can modify the string table, so it's necessary to call
544 // WriteStringTable() last in the first pass, to compute the correct length of the output.
545 if (string_first) {
546 WriteStringTable();
547 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700548 WriteClassTable();
549 WriteStackTraces();
Man Cao8c2ff642015-05-27 17:25:30 -0700550 if (!string_first) {
551 WriteStringTable();
552 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700553 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800554 }
555
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700556 void WriteClassTable() REQUIRES_SHARED(Locks::mutator_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700557 for (const auto& p : classes_) {
558 mirror::Class* c = p.first;
559 HprofClassSerialNumber sn = p.second;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800560 CHECK(c != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700561 output_->StartNewRecord(HPROF_TAG_LOAD_CLASS, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700562 // LOAD CLASS format:
563 // U4: class serial number (always > 0)
564 // ID: class object ID. We use the address of the class object structure as its ID.
565 // U4: stack trace serial number
566 // ID: class name string ID
Man Cao8c2ff642015-05-27 17:25:30 -0700567 __ AddU4(sn);
Andreas Gampe3a913092015-01-10 00:26:17 -0800568 __ AddObjectId(c);
Man Cao8c2ff642015-05-27 17:25:30 -0700569 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(c));
Andreas Gampe3a913092015-01-10 00:26:17 -0800570 __ AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700571 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700572 }
573
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700574 void WriteStringTable() {
Andreas Gampe1eeb00c2016-11-03 08:19:01 -0700575 for (const auto& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800576 const std::string& string = p.first;
Andreas Gampe1eeb00c2016-11-03 08:19:01 -0700577 const HprofStringId id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700578
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700579 output_->StartNewRecord(HPROF_TAG_STRING, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700580
581 // STRING format:
582 // ID: ID for this string
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700583 // U1*: UTF8 characters for string (NOT null terminated)
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700584 // (the record format encodes the length)
Andreas Gampe3a913092015-01-10 00:26:17 -0800585 __ AddU4(id);
586 __ AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700587 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700588 }
589
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700590 void StartNewHeapDumpSegment() {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700591 // This flushes the old segment and starts a new one.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700592 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700593 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700594 // Starting a new HEAP_DUMP resets the heap to default.
595 current_heap_ = HPROF_HEAP_DEFAULT;
596 }
597
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700598 void CheckHeapSegmentConstraints() {
599 if (objects_in_segment_ >= kMaxObjectsPerSegment || output_->Length() >= kMaxBytesPerSegment) {
600 StartNewHeapDumpSegment();
Andreas Gampe3a913092015-01-10 00:26:17 -0800601 }
602 }
603
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700604 void VisitRoot(mirror::Object* obj, const RootInfo& root_info)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700605 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800606 void MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700607 uint32_t thread_serial);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700608
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700609 HprofClassObjectId LookupClassId(mirror::Class* c) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800610 if (c != nullptr) {
Man Cao8c2ff642015-05-27 17:25:30 -0700611 auto it = classes_.find(c);
612 if (it == classes_.end()) {
613 // first time to see this class
614 HprofClassSerialNumber sn = next_class_serial_number_++;
615 classes_.Put(c, sn);
616 // Make sure that we've assigned a string ID for this class' name
617 LookupClassNameId(c);
618 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800619 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800620 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700621 }
622
Man Cao8c2ff642015-05-27 17:25:30 -0700623 HprofStackTraceSerialNumber LookupStackTraceSerialNumber(const mirror::Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700624 REQUIRES_SHARED(Locks::mutator_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700625 auto r = allocation_records_.find(obj);
626 if (r == allocation_records_.end()) {
627 return kHprofNullStackTrace;
628 } else {
629 const gc::AllocRecordStackTrace* trace = r->second;
630 auto result = traces_.find(trace);
631 CHECK(result != traces_.end());
632 return result->second;
633 }
634 }
635
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700636 HprofStringId LookupStringId(mirror::String* string) REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700637 return LookupStringId(string->ToModifiedUtf8());
638 }
639
640 HprofStringId LookupStringId(const char* string) {
641 return LookupStringId(std::string(string));
642 }
643
644 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800645 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700646 if (it != strings_.end()) {
647 return it->second;
648 }
649 HprofStringId id = next_string_id_++;
650 strings_.Put(string, id);
651 return id;
652 }
653
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700654 HprofStringId LookupClassNameId(mirror::Class* c) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700655 return LookupStringId(c->PrettyDescriptor());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700656 }
657
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700658 void WriteFixedHeader() {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500659 // Write the file header.
660 // U1: NUL-terminated magic string.
Andreas Gampe3a913092015-01-10 00:26:17 -0800661 const char magic[] = "JAVA PROFILE 1.0.3";
662 __ AddU1List(reinterpret_cast<const uint8_t*>(magic), sizeof(magic));
663
Calin Juravle32805172014-07-04 16:24:03 +0100664 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
665 // as uint32_t.
666 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800667 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
668 "Unexpected HeapReference size");
Andreas Gampe3a913092015-01-10 00:26:17 -0800669 __ AddU4(sizeof(uint32_t));
670
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500671 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700672 timeval now;
Andreas Gampe3a913092015-01-10 00:26:17 -0800673 const uint64_t nowMs = (gettimeofday(&now, nullptr) < 0) ? 0 :
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800674 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Andreas Gampe3a913092015-01-10 00:26:17 -0800675 // TODO: It seems it would be correct to use U8.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500676 // U4: high word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800677 __ AddU4(static_cast<uint32_t>(nowMs >> 32));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500678 // U4: low word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800679 __ AddU4(static_cast<uint32_t>(nowMs & 0xFFFFFFFF));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500680 }
681
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700682 void WriteStackTraces() REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700683 // Write a dummy stack trace record so the analysis tools don't freak out.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700684 output_->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
Man Cao8c2ff642015-05-27 17:25:30 -0700685 __ AddStackTraceSerialNumber(kHprofNullStackTrace);
Andreas Gampe3a913092015-01-10 00:26:17 -0800686 __ AddU4(kHprofNullThread);
687 __ AddU4(0); // no frames
Man Cao8c2ff642015-05-27 17:25:30 -0700688
689 // TODO: jhat complains "WARNING: Stack trace not found for serial # -1", but no trace should
690 // have -1 as its serial number (as long as HprofStackTraceSerialNumber doesn't overflow).
691 for (const auto& it : traces_) {
692 const gc::AllocRecordStackTrace* trace = it.first;
693 HprofStackTraceSerialNumber trace_sn = it.second;
694 size_t depth = trace->GetDepth();
695
696 // First write stack frames of the trace
697 for (size_t i = 0; i < depth; ++i) {
698 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
699 ArtMethod* method = frame->GetMethod();
700 CHECK(method != nullptr);
701 output_->StartNewRecord(HPROF_TAG_STACK_FRAME, kHprofTime);
702 // STACK FRAME format:
703 // ID: stack frame ID. We use the address of the AllocRecordStackTraceElement object as its ID.
704 // ID: method name string ID
705 // ID: method signature string ID
706 // ID: source file name string ID
707 // U4: class serial number
708 // U4: >0, line number; 0, no line information available; -1, unknown location
709 auto frame_result = frames_.find(frame);
710 CHECK(frame_result != frames_.end());
711 __ AddU4(frame_result->second);
712 __ AddStringId(LookupStringId(method->GetName()));
713 __ AddStringId(LookupStringId(method->GetSignature().ToString()));
714 const char* source_file = method->GetDeclaringClassSourceFile();
715 if (source_file == nullptr) {
716 source_file = "";
717 }
718 __ AddStringId(LookupStringId(source_file));
719 auto class_result = classes_.find(method->GetDeclaringClass());
720 CHECK(class_result != classes_.end());
721 __ AddU4(class_result->second);
722 __ AddU4(frame->ComputeLineNumber());
723 }
724
725 // Then write the trace itself
726 output_->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
727 // STACK TRACE format:
728 // U4: stack trace serial number. We use the address of the AllocRecordStackTrace object as its serial number.
729 // U4: thread serial number. We use Thread::GetTid().
730 // U4: number of frames
731 // [ID]*: series of stack frame ID's
732 __ AddStackTraceSerialNumber(trace_sn);
733 __ AddU4(trace->GetTid());
734 __ AddU4(depth);
735 for (size_t i = 0; i < depth; ++i) {
736 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
737 auto frame_result = frames_.find(frame);
738 CHECK(frame_result != frames_.end());
739 __ AddU4(frame_result->second);
740 }
741 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800742 }
743
744 bool DumpToDdmsBuffered(size_t overall_size ATTRIBUTE_UNUSED, size_t max_length ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700745 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800746 LOG(FATAL) << "Unimplemented";
747 UNREACHABLE();
748 // // Send the data off to DDMS.
749 // iovec iov[2];
750 // iov[0].iov_base = header_data_ptr_;
751 // iov[0].iov_len = header_data_size_;
752 // iov[1].iov_base = body_data_ptr_;
753 // iov[1].iov_len = body_data_size_;
754 // Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
755 }
756
757 bool DumpToFile(size_t overall_size, size_t max_length)
Mathieu Chartier90443472015-07-16 20:32:27 -0700758 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800759 // Where exactly are we writing to?
760 int out_fd;
761 if (fd_ >= 0) {
762 out_fd = dup(fd_);
763 if (out_fd < 0) {
764 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
765 return false;
766 }
767 } else {
768 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
769 if (out_fd < 0) {
770 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
771 strerror(errno));
772 return false;
773 }
774 }
775
776 std::unique_ptr<File> file(new File(out_fd, filename_, true));
777 bool okay;
778 {
779 FileEndianOutput file_output(file.get(), max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700780 output_ = &file_output;
781 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800782 okay = !file_output.Errors();
783
784 if (okay) {
Andreas Gampec515f212015-08-28 18:15:27 -0700785 // Check for expected size. Output is expected to be less-or-equal than first phase, see
786 // b/23521263.
787 DCHECK_LE(file_output.SumLength(), overall_size);
Andreas Gampe3a913092015-01-10 00:26:17 -0800788 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700789 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800790 }
791
792 if (okay) {
793 okay = file->FlushCloseOrErase() == 0;
794 } else {
795 file->Erase();
796 }
797 if (!okay) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800798 std::string msg(android::base::StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
799 filename_.c_str(),
800 strerror(errno)));
Andreas Gampe3a913092015-01-10 00:26:17 -0800801 ThrowRuntimeException("%s", msg.c_str());
802 LOG(ERROR) << msg;
803 }
804
805 return okay;
806 }
807
808 bool DumpToDdmsDirect(size_t overall_size, size_t max_length, uint32_t chunk_type)
Mathieu Chartier90443472015-07-16 20:32:27 -0700809 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800810 CHECK(direct_to_ddms_);
811 JDWP::JdwpState* state = Dbg::GetJdwpState();
812 CHECK(state != nullptr);
813 JDWP::JdwpNetStateBase* net_state = state->netState;
814 CHECK(net_state != nullptr);
815
816 // Hold the socket lock for the whole time since we want this to be atomic.
817 MutexLock mu(Thread::Current(), *net_state->GetSocketLock());
818
819 // Prepare the Ddms chunk.
820 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
821 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
822 state->SetupChunkHeader(chunk_type, overall_size, kChunkHeaderSize, chunk_header);
823
824 // Prepare the output and send the chunk header.
825 NetStateEndianOutput net_output(net_state, max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700826 output_ = &net_output;
Andreas Gampe3a913092015-01-10 00:26:17 -0800827 net_output.AddU1List(chunk_header, kChunkHeaderSize);
828
829 // Write the dump.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700830 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800831
Andreas Gampec515f212015-08-28 18:15:27 -0700832 // Check for expected size. See DumpToFile for comment.
833 DCHECK_LE(net_output.SumLength(), overall_size + kChunkHeaderSize);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700834 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800835
836 return true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700837 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500838
Man Cao8c2ff642015-05-27 17:25:30 -0700839 void PopulateAllocationTrackingTraces()
Mathieu Chartier90443472015-07-16 20:32:27 -0700840 REQUIRES(Locks::mutator_lock_, Locks::alloc_tracker_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700841 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
842 CHECK(records != nullptr);
843 HprofStackTraceSerialNumber next_trace_sn = kHprofNullStackTrace + 1;
844 HprofStackFrameId next_frame_id = 0;
Man Cao42c3c332015-06-23 16:38:25 -0700845 size_t count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -0700846
847 for (auto it = records->Begin(), end = records->End(); it != end; ++it) {
848 const mirror::Object* obj = it->first.Read();
Man Cao42c3c332015-06-23 16:38:25 -0700849 if (obj == nullptr) {
850 continue;
851 }
852 ++count;
Mathieu Chartier458b1052016-03-29 14:02:55 -0700853 const gc::AllocRecordStackTrace* trace = it->second.GetStackTrace();
Man Cao8c2ff642015-05-27 17:25:30 -0700854
855 // Copy the pair into a real hash map to speed up look up.
856 auto records_result = allocation_records_.emplace(obj, trace);
857 // The insertion should always succeed, i.e. no duplicate object pointers in "records"
858 CHECK(records_result.second);
859
860 // Generate serial numbers for traces, and IDs for frames.
861 auto traces_result = traces_.find(trace);
862 if (traces_result == traces_.end()) {
863 traces_.emplace(trace, next_trace_sn++);
864 // only check frames if the trace is newly discovered
865 for (size_t i = 0, depth = trace->GetDepth(); i < depth; ++i) {
866 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
867 auto frames_result = frames_.find(frame);
868 if (frames_result == frames_.end()) {
869 frames_.emplace(frame, next_frame_id++);
870 }
871 }
872 }
873 }
874 CHECK_EQ(traces_.size(), next_trace_sn - kHprofNullStackTrace - 1);
875 CHECK_EQ(frames_.size(), next_frame_id);
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800876 total_objects_with_stack_trace_ = count;
Man Cao8c2ff642015-05-27 17:25:30 -0700877 }
878
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700879 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
880 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
881 // only be used for debug messages.
882 std::string filename_;
883 int fd_;
884 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500885
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800886 uint64_t start_ns_ = NanoTime();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700887
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800888 EndianOutput* output_ = nullptr;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700889
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800890 HprofHeapId current_heap_ = HPROF_HEAP_DEFAULT; // Which heap we're currently dumping.
891 size_t objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700892
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800893 size_t total_objects_ = 0u;
894 size_t total_objects_with_stack_trace_ = 0u;
895
896 HprofStringId next_string_id_ = 0x400000;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800897 SafeMap<std::string, HprofStringId> strings_;
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -0800898 HprofClassSerialNumber next_class_serial_number_ = 1;
Man Cao8c2ff642015-05-27 17:25:30 -0700899 SafeMap<mirror::Class*, HprofClassSerialNumber> classes_;
900
901 std::unordered_map<const gc::AllocRecordStackTrace*, HprofStackTraceSerialNumber,
902 gc::HashAllocRecordTypesPtr<gc::AllocRecordStackTrace>,
903 gc::EqAllocRecordTypesPtr<gc::AllocRecordStackTrace>> traces_;
904 std::unordered_map<const gc::AllocRecordStackTraceElement*, HprofStackFrameId,
905 gc::HashAllocRecordTypesPtr<gc::AllocRecordStackTraceElement>,
906 gc::EqAllocRecordTypesPtr<gc::AllocRecordStackTraceElement>> frames_;
907 std::unordered_map<const mirror::Object*, const gc::AllocRecordStackTrace*> allocation_records_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700908
Richard Uhler4b767552016-04-26 13:28:59 -0700909 // Set used to keep track of what simple root records we have already
910 // emitted, to avoid emitting duplicate entries. The simple root records are
911 // those that contain no other information than the root type and the object
912 // id. A pair of root type and object id is packed into a uint64_t, with
913 // the root type in the upper 32 bits and the object id in the lower 32
914 // bits.
915 std::unordered_set<uint64_t> simple_roots_;
916
Mathieu Chartierecc82302017-02-16 10:20:12 -0800917 // To make sure we don't dump the same object multiple times. b/34967844
918 std::unordered_set<mirror::Object*> visited_objects_;
919
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700920 friend class GcRootVisitor;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700921 DISALLOW_COPY_AND_ASSIGN(Hprof);
922};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500923
Andreas Gampe3a913092015-01-10 00:26:17 -0800924static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* size_out) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500925 char c = sig[0];
926 HprofBasicType ret;
927 size_t size;
928
929 switch (c) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800930 case '[':
931 case 'L':
932 ret = hprof_basic_object;
933 size = 4;
934 break;
935 case 'Z':
936 ret = hprof_basic_boolean;
937 size = 1;
938 break;
939 case 'C':
940 ret = hprof_basic_char;
941 size = 2;
942 break;
943 case 'F':
944 ret = hprof_basic_float;
945 size = 4;
946 break;
947 case 'D':
948 ret = hprof_basic_double;
949 size = 8;
950 break;
951 case 'B':
952 ret = hprof_basic_byte;
953 size = 1;
954 break;
955 case 'S':
956 ret = hprof_basic_short;
957 size = 2;
958 break;
959 case 'I':
960 ret = hprof_basic_int;
961 size = 4;
962 break;
963 case 'J':
964 ret = hprof_basic_long;
965 size = 8;
966 break;
967 default:
968 LOG(FATAL) << "UNREACHABLE";
969 UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500970 }
971
Andreas Gampe3a913092015-01-10 00:26:17 -0800972 if (size_out != nullptr) {
973 *size_out = size;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500974 }
975
976 return ret;
977}
978
979// Always called when marking objects, but only does
980// something when ctx->gc_scan_state_ is non-zero, which is usually
981// only true when marking the root set or unreachable
982// objects. Used to add rootset references to obj.
Andreas Gampe3a913092015-01-10 00:26:17 -0800983void Hprof::MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700984 uint32_t thread_serial) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800985 if (heap_tag == 0) {
986 return;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500987 }
988
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700989 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500990
Andreas Gampe3a913092015-01-10 00:26:17 -0800991 switch (heap_tag) {
992 // ID: object ID
993 case HPROF_ROOT_UNKNOWN:
994 case HPROF_ROOT_STICKY_CLASS:
995 case HPROF_ROOT_MONITOR_USED:
996 case HPROF_ROOT_INTERNED_STRING:
997 case HPROF_ROOT_DEBUGGER:
Richard Uhler4b767552016-04-26 13:28:59 -0700998 case HPROF_ROOT_VM_INTERNAL: {
999 uint64_t key = (static_cast<uint64_t>(heap_tag) << 32) | PointerToLowMemUInt32(obj);
1000 if (simple_roots_.insert(key).second) {
1001 __ AddU1(heap_tag);
1002 __ AddObjectId(obj);
1003 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001004 break;
Richard Uhler4b767552016-04-26 13:28:59 -07001005 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001006
Andreas Gampe3a913092015-01-10 00:26:17 -08001007 // ID: object ID
1008 // ID: JNI global ref ID
1009 case HPROF_ROOT_JNI_GLOBAL:
1010 __ AddU1(heap_tag);
1011 __ AddObjectId(obj);
1012 __ AddJniGlobalRefId(jni_obj);
1013 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001014
Andreas Gampe3a913092015-01-10 00:26:17 -08001015 // ID: object ID
1016 // U4: thread serial number
1017 // U4: frame number in stack trace (-1 for empty)
1018 case HPROF_ROOT_JNI_LOCAL:
1019 case HPROF_ROOT_JNI_MONITOR:
1020 case HPROF_ROOT_JAVA_FRAME:
1021 __ AddU1(heap_tag);
1022 __ AddObjectId(obj);
1023 __ AddU4(thread_serial);
1024 __ AddU4((uint32_t)-1);
1025 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001026
Andreas Gampe3a913092015-01-10 00:26:17 -08001027 // ID: object ID
1028 // U4: thread serial number
1029 case HPROF_ROOT_NATIVE_STACK:
1030 case HPROF_ROOT_THREAD_BLOCK:
1031 __ AddU1(heap_tag);
1032 __ AddObjectId(obj);
1033 __ AddU4(thread_serial);
1034 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001035
Andreas Gampe3a913092015-01-10 00:26:17 -08001036 // ID: thread object ID
1037 // U4: thread serial number
1038 // U4: stack trace serial number
1039 case HPROF_ROOT_THREAD_OBJECT:
1040 __ AddU1(heap_tag);
1041 __ AddObjectId(obj);
1042 __ AddU4(thread_serial);
1043 __ AddU4((uint32_t)-1); // xxx
1044 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001045
Andreas Gampe3a913092015-01-10 00:26:17 -08001046 case HPROF_CLASS_DUMP:
1047 case HPROF_INSTANCE_DUMP:
1048 case HPROF_OBJECT_ARRAY_DUMP:
1049 case HPROF_PRIMITIVE_ARRAY_DUMP:
1050 case HPROF_HEAP_DUMP_INFO:
1051 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
1052 // Ignored.
1053 break;
Elliott Hughes73e66f72012-05-09 09:34:45 -07001054
Andreas Gampe3a913092015-01-10 00:26:17 -08001055 case HPROF_ROOT_FINALIZING:
1056 case HPROF_ROOT_REFERENCE_CLEANUP:
1057 case HPROF_UNREACHABLE:
1058 LOG(FATAL) << "obsolete tag " << static_cast<int>(heap_tag);
1059 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001060 }
1061
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001062 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001063}
1064
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001065// Use for visiting the GcRoots held live by ArtFields, ArtMethods, and ClassLoaders.
1066class GcRootVisitor {
1067 public:
1068 explicit GcRootVisitor(Hprof* hprof) : hprof_(hprof) {}
1069
1070 void operator()(mirror::Object* obj ATTRIBUTE_UNUSED,
1071 MemberOffset offset ATTRIBUTE_UNUSED,
1072 bool is_static ATTRIBUTE_UNUSED) const {}
1073
1074 // Note that these don't have read barriers. Its OK however since the GC is guaranteed to not be
1075 // running during the hprof dumping process.
1076 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001077 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001078 if (!root->IsNull()) {
1079 VisitRoot(root);
1080 }
1081 }
1082
1083 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001084 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001085 mirror::Object* obj = root->AsMirrorPtr();
1086 // The two cases are either classes or dex cache arrays. If it is a dex cache array, then use
1087 // VM internal. Otherwise the object is a declaring class of an ArtField or ArtMethod or a
1088 // class from a ClassLoader.
1089 hprof_->VisitRoot(obj, RootInfo(obj->IsClass() ? kRootStickyClass : kRootVMInternal));
1090 }
1091
1092
1093 private:
1094 Hprof* const hprof_;
1095};
1096
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001097void Hprof::DumpHeapObject(mirror::Object* obj) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001098 // Ignore classes that are retired.
1099 if (obj->IsClass() && obj->AsClass()->IsRetired()) {
1100 return;
1101 }
Mathieu Chartierecc82302017-02-16 10:20:12 -08001102 DCHECK(visited_objects_.insert(obj).second) << "Already visited " << obj;
Andreas Gampe3a913092015-01-10 00:26:17 -08001103
Mathieu Chartierc9cd7ac2016-01-20 14:48:36 -08001104 ++total_objects_;
1105
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001106 GcRootVisitor visitor(this);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001107 obj->VisitReferences(visitor, VoidFunctor());
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001108
Mathieu Chartiere7158112015-06-03 13:32:15 -07001109 gc::Heap* const heap = Runtime::Current()->GetHeap();
1110 const gc::space::ContinuousSpace* const space = heap->FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001111 HprofHeapId heap_type = HPROF_HEAP_APP;
1112 if (space != nullptr) {
1113 if (space->IsZygoteSpace()) {
1114 heap_type = HPROF_HEAP_ZYGOTE;
Mathieu Chartier0b874522017-02-24 14:47:08 -08001115 } else if (space->IsImageSpace() && heap->ObjectIsInBootImageSpace(obj)) {
1116 // Only count objects in the boot image as HPROF_HEAP_IMAGE, this leaves app image objects as
1117 // HPROF_HEAP_APP. b/35762934
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001118 heap_type = HPROF_HEAP_IMAGE;
1119 }
Mathieu Chartiere7158112015-06-03 13:32:15 -07001120 } else {
1121 const auto* los = heap->GetLargeObjectsSpace();
1122 if (los->Contains(obj) && los->IsZygoteLargeObject(Thread::Current(), obj)) {
1123 heap_type = HPROF_HEAP_ZYGOTE;
1124 }
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001125 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001126 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001127
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001128 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001129 HprofStringId nameId;
1130
1131 // This object is in a different heap than the current one.
1132 // Emit a HEAP_DUMP_INFO tag to change heaps.
Andreas Gampe3a913092015-01-10 00:26:17 -08001133 __ AddU1(HPROF_HEAP_DUMP_INFO);
1134 __ AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001135 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001136 case HPROF_HEAP_APP:
1137 nameId = LookupStringId("app");
1138 break;
1139 case HPROF_HEAP_ZYGOTE:
1140 nameId = LookupStringId("zygote");
1141 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001142 case HPROF_HEAP_IMAGE:
1143 nameId = LookupStringId("image");
1144 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001145 default:
1146 // Internal error
1147 LOG(ERROR) << "Unexpected desiredHeap";
1148 nameId = LookupStringId("<ILLEGAL>");
1149 break;
1150 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001151 __ AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001152 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001153 }
1154
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001155 mirror::Class* c = obj->GetClass();
Andreas Gampe3a913092015-01-10 00:26:17 -08001156 if (c == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001157 // This object will bother HprofReader, because it has a null
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001158 // class, so just don't dump it. It could be
1159 // gDvm.unlinkedJavaLangClass or it could be an object just
1160 // allocated which hasn't been initialized yet.
1161 } else {
1162 if (obj->IsClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001163 DumpHeapClass(obj->AsClass());
Elliott Hughese84278b2012-03-22 10:06:53 -07001164 } else if (c->IsArrayClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001165 DumpHeapArray(obj->AsArray(), c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001166 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001167 DumpHeapInstanceObject(obj, c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001168 }
1169 }
1170
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001171 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001172}
1173
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001174void Hprof::DumpHeapClass(mirror::Class* klass) {
Vladimir Marko72ab6842017-01-20 19:32:50 +00001175 if (!klass->IsResolved()) {
Mathieu Chartier12393f32016-10-20 17:11:23 -07001176 // Class is allocated but not yet resolved: we cannot access its fields or super class.
Sebastien Hertzca068b22015-04-07 10:28:53 +02001177 return;
1178 }
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001179 const size_t num_static_fields = klass->NumStaticFields();
1180 // Total class size including embedded IMT, embedded vtable, and static fields.
1181 const size_t class_size = klass->GetClassSize();
1182 // Class size excluding static fields (relies on reference fields being the first static fields).
1183 const size_t class_size_without_overhead = sizeof(mirror::Class);
1184 CHECK_LE(class_size_without_overhead, class_size);
1185 const size_t overhead_size = class_size - class_size_without_overhead;
1186
1187 if (overhead_size != 0) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001188 // Create a byte array to reflect the allocation of the
1189 // StaticField array at the end of this class.
1190 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1191 __ AddClassStaticsId(klass);
Man Cao8c2ff642015-05-27 17:25:30 -07001192 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(klass));
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001193 __ AddU4(overhead_size);
Andreas Gampe3a913092015-01-10 00:26:17 -08001194 __ AddU1(hprof_basic_byte);
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001195 for (size_t i = 0; i < overhead_size; ++i) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001196 __ AddU1(0);
1197 }
1198 }
1199
1200 __ AddU1(HPROF_CLASS_DUMP);
1201 __ AddClassId(LookupClassId(klass));
Man Cao8c2ff642015-05-27 17:25:30 -07001202 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001203 __ AddClassId(LookupClassId(klass->GetSuperClass()));
1204 __ AddObjectId(klass->GetClassLoader());
1205 __ AddObjectId(nullptr); // no signer
1206 __ AddObjectId(nullptr); // no prot domain
1207 __ AddObjectId(nullptr); // reserved
1208 __ AddObjectId(nullptr); // reserved
1209 if (klass->IsClassClass()) {
1210 // ClassObjects have their static fields appended, so aren't all the same size.
1211 // But they're at least this size.
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001212 __ AddU4(class_size_without_overhead); // instance size
Jeff Hao0ce43532015-05-12 18:58:32 -07001213 } else if (klass->IsStringClass()) {
1214 // Strings are variable length with character data at the end like arrays.
1215 // This outputs the size of an empty string.
1216 __ AddU4(sizeof(mirror::String));
1217 } else if (klass->IsArrayClass() || klass->IsPrimitive()) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001218 __ AddU4(0);
1219 } else {
1220 __ AddU4(klass->GetObjectSize()); // instance size
1221 }
1222
1223 __ AddU2(0); // empty const pool
1224
1225 // Static fields
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001226 if (overhead_size == 0) {
1227 __ AddU2(static_cast<uint16_t>(0));
Andreas Gampe3a913092015-01-10 00:26:17 -08001228 } else {
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001229 __ AddU2(static_cast<uint16_t>(num_static_fields + 1));
1230 __ AddStringId(LookupStringId(kClassOverheadName));
Andreas Gampe3a913092015-01-10 00:26:17 -08001231 __ AddU1(hprof_basic_object);
1232 __ AddClassStaticsId(klass);
1233
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001234 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001235 ArtField* f = klass->GetStaticField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001236
1237 size_t size;
1238 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1239 __ AddStringId(LookupStringId(f->GetName()));
1240 __ AddU1(t);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001241 switch (t) {
1242 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001243 __ AddU1(f->GetByte(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001244 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001245 case hprof_basic_boolean:
1246 __ AddU1(f->GetBoolean(klass));
1247 break;
1248 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001249 __ AddU2(f->GetChar(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001250 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001251 case hprof_basic_short:
1252 __ AddU2(f->GetShort(klass));
1253 break;
1254 case hprof_basic_float:
1255 case hprof_basic_int:
1256 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001257 __ AddU4(f->Get32(klass));
1258 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001259 case hprof_basic_double:
1260 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001261 __ AddU8(f->Get64(klass));
1262 break;
1263 default:
1264 LOG(FATAL) << "Unexpected size " << size;
1265 UNREACHABLE();
1266 }
1267 }
1268 }
1269
1270 // Instance fields for this class (no superclass fields)
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001271 int iFieldCount = klass->NumInstanceFields();
Jeff Hao848f70a2014-01-15 13:49:50 -08001272 if (klass->IsStringClass()) {
1273 __ AddU2((uint16_t)iFieldCount + 1);
1274 } else {
1275 __ AddU2((uint16_t)iFieldCount);
1276 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001277 for (int i = 0; i < iFieldCount; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001278 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001279 __ AddStringId(LookupStringId(f->GetName()));
1280 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), nullptr);
1281 __ AddU1(t);
1282 }
Vladimir Marko595beb32017-02-06 14:11:54 +00001283 // Add native value character array for strings / byte array for compressed strings.
Jeff Hao848f70a2014-01-15 13:49:50 -08001284 if (klass->IsStringClass()) {
1285 __ AddStringId(LookupStringId("value"));
1286 __ AddU1(hprof_basic_object);
1287 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001288}
1289
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001290void Hprof::DumpHeapArray(mirror::Array* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001291 uint32_t length = obj->GetLength();
1292
1293 if (obj->IsObjectArray()) {
1294 // obj is an object array.
1295 __ AddU1(HPROF_OBJECT_ARRAY_DUMP);
1296
1297 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001298 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001299 __ AddU4(length);
1300 __ AddClassId(LookupClassId(klass));
1301
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001302 // Dump the elements, which are always objects or null.
Andreas Gampe3a913092015-01-10 00:26:17 -08001303 __ AddIdList(obj->AsObjectArray<mirror::Object>());
1304 } else {
1305 size_t size;
1306 HprofBasicType t = SignatureToBasicTypeAndSize(
1307 Primitive::Descriptor(klass->GetComponentType()->GetPrimitiveType()), &size);
1308
1309 // obj is a primitive array.
1310 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1311
1312 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001313 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001314 __ AddU4(length);
1315 __ AddU1(t);
1316
1317 // Dump the raw, packed element values.
1318 if (size == 1) {
1319 __ AddU1List(reinterpret_cast<const uint8_t*>(obj->GetRawData(sizeof(uint8_t), 0)), length);
1320 } else if (size == 2) {
1321 __ AddU2List(reinterpret_cast<const uint16_t*>(obj->GetRawData(sizeof(uint16_t), 0)), length);
1322 } else if (size == 4) {
1323 __ AddU4List(reinterpret_cast<const uint32_t*>(obj->GetRawData(sizeof(uint32_t), 0)), length);
1324 } else if (size == 8) {
1325 __ AddU8List(reinterpret_cast<const uint64_t*>(obj->GetRawData(sizeof(uint64_t), 0)), length);
1326 }
1327 }
1328}
1329
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001330void Hprof::DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001331 // obj is an instance object.
1332 __ AddU1(HPROF_INSTANCE_DUMP);
1333 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001334 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001335 __ AddClassId(LookupClassId(klass));
1336
1337 // Reserve some space for the length of the instance data, which we won't
1338 // know until we're done writing it.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001339 size_t size_patch_offset = output_->Length();
Andreas Gampe3a913092015-01-10 00:26:17 -08001340 __ AddU4(0x77777777);
1341
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001342 // What we will use for the string value if the object is a string.
1343 mirror::Object* string_value = nullptr;
1344
1345 // Write the instance data; fields for this class, followed by super class fields, and so on.
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001346 do {
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001347 const size_t instance_fields = klass->NumInstanceFields();
1348 for (size_t i = 0; i < instance_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001349 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001350 size_t size;
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001351 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001352 switch (t) {
1353 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001354 __ AddU1(f->GetByte(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001355 break;
1356 case hprof_basic_boolean:
1357 __ AddU1(f->GetBoolean(obj));
1358 break;
1359 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001360 __ AddU2(f->GetChar(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001361 break;
1362 case hprof_basic_short:
1363 __ AddU2(f->GetShort(obj));
1364 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001365 case hprof_basic_int:
Vladimir Marko595beb32017-02-06 14:11:54 +00001366 if (mirror::kUseStringCompression &&
1367 klass->IsStringClass() &&
1368 f->GetOffset().SizeValue() == mirror::String::CountOffset().SizeValue()) {
1369 // Store the string length instead of the raw count field with compression flag.
1370 __ AddU4(obj->AsString()->GetLength());
1371 break;
1372 }
1373 FALLTHROUGH_INTENDED;
1374 case hprof_basic_float:
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001375 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001376 __ AddU4(f->Get32(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001377 break;
1378 case hprof_basic_double:
1379 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001380 __ AddU8(f->Get64(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001381 break;
Andreas Gampe3a913092015-01-10 00:26:17 -08001382 }
1383 }
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001384 // Add value field for String if necessary.
1385 if (klass->IsStringClass()) {
1386 mirror::String* s = obj->AsString();
1387 if (s->GetLength() == 0) {
1388 // If string is empty, use an object-aligned address within the string for the value.
1389 string_value = reinterpret_cast<mirror::Object*>(
1390 reinterpret_cast<uintptr_t>(s) + kObjectAlignment);
1391 } else {
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001392 if (s->IsCompressed()) {
1393 string_value = reinterpret_cast<mirror::Object*>(s->GetValueCompressed());
1394 } else {
1395 string_value = reinterpret_cast<mirror::Object*>(s->GetValue());
1396 }
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001397 }
1398 __ AddObjectId(string_value);
1399 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001400
1401 klass = klass->GetSuperClass();
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001402 } while (klass != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -08001403
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001404 // Patch the instance field length.
1405 __ UpdateU4(size_patch_offset, output_->Length() - (size_patch_offset + 4));
1406
Jeff Hao848f70a2014-01-15 13:49:50 -08001407 // Output native value character array for strings.
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001408 CHECK_EQ(obj->IsString(), string_value != nullptr);
1409 if (string_value != nullptr) {
Jeff Hao848f70a2014-01-15 13:49:50 -08001410 mirror::String* s = obj->AsString();
Jeff Hao848f70a2014-01-15 13:49:50 -08001411 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001412 __ AddObjectId(string_value);
Man Cao8c2ff642015-05-27 17:25:30 -07001413 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Vladimir Marko595beb32017-02-06 14:11:54 +00001414 __ AddU4(s->GetLength());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001415 if (s->IsCompressed()) {
Vladimir Marko595beb32017-02-06 14:11:54 +00001416 __ AddU1(hprof_basic_byte);
1417 __ AddU1List(s->GetValueCompressed(), s->GetLength());
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001418 } else {
Vladimir Marko595beb32017-02-06 14:11:54 +00001419 __ AddU1(hprof_basic_char);
jessicahandojo3aaa37b2016-07-29 14:46:37 -07001420 __ AddU2List(s->GetValue(), s->GetLength());
1421 }
Jeff Hao848f70a2014-01-15 13:49:50 -08001422 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001423}
1424
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001425void Hprof::VisitRoot(mirror::Object* obj, const RootInfo& info) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001426 static const HprofHeapTag xlate[] = {
1427 HPROF_ROOT_UNKNOWN,
1428 HPROF_ROOT_JNI_GLOBAL,
1429 HPROF_ROOT_JNI_LOCAL,
1430 HPROF_ROOT_JAVA_FRAME,
1431 HPROF_ROOT_NATIVE_STACK,
1432 HPROF_ROOT_STICKY_CLASS,
1433 HPROF_ROOT_THREAD_BLOCK,
1434 HPROF_ROOT_MONITOR_USED,
1435 HPROF_ROOT_THREAD_OBJECT,
1436 HPROF_ROOT_INTERNED_STRING,
1437 HPROF_ROOT_FINALIZING,
1438 HPROF_ROOT_DEBUGGER,
1439 HPROF_ROOT_REFERENCE_CLEANUP,
1440 HPROF_ROOT_VM_INTERNAL,
1441 HPROF_ROOT_JNI_MONITOR,
1442 };
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001443 CHECK_LT(info.GetType(), sizeof(xlate) / sizeof(HprofHeapTag));
Andreas Gampe3a913092015-01-10 00:26:17 -08001444 if (obj == nullptr) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001445 return;
1446 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001447 MarkRootObject(obj, 0, xlate[info.GetType()], info.GetThreadId());
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001448}
1449
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001450// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1451// sent directly to DDMS.
1452// If "fd" is >= 0, the output will be written to that file descriptor.
1453// Otherwise, "filename" is used to create an output file.
1454void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001455 CHECK(filename != nullptr);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001456 Thread* self = Thread::Current();
Mathieu Chartierecc82302017-02-16 10:20:12 -08001457 // Need to take a heap dump while GC isn't running. See the comment in Heap::VisitObjects().
1458 // Also we need the critical section to avoid visiting the same object twice. See b/34967844
1459 gc::ScopedGCCriticalSection gcs(self,
1460 gc::kGcCauseHprof,
1461 gc::kCollectorTypeHprof);
1462 ScopedSuspendAll ssa(__FUNCTION__, true /* long suspend */);
1463 Hprof hprof(filename, fd, direct_to_ddms);
1464 hprof.Dump();
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001465}
1466
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001467} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001468} // namespace art