blob: 713797fc3db9ce681732fde097ddaf95e25a0675 [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
Mathieu Chartierc7853442015-03-27 14:35:38 -070040#include "art_field-inl.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080041#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080042#include "base/stringprintf.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010043#include "base/time_utils.h"
Elliott Hughes76160052012-12-12 16:31:20 -080044#include "base/unix_file/fd_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080045#include "class_linker.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080046#include "common_throws.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040047#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070048#include "dex_file-inl.h"
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -080049#include "gc_root.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070050#include "gc/accounting/heap_bitmap.h"
Man Cao8c2ff642015-05-27 17:25:30 -070051#include "gc/allocation_record.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "gc/heap.h"
53#include "gc/space/space.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070054#include "globals.h"
Mathieu Chartierad466ad2015-01-08 16:28:08 -080055#include "jdwp/jdwp.h"
56#include "jdwp/jdwp_priv.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/class.h"
58#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/object-inl.h"
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -070060#include "os.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070061#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070062#include "scoped_thread_state_change.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070063#include "thread_list.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040064
65namespace art {
66
67namespace hprof {
68
Mathieu Chartierad466ad2015-01-08 16:28:08 -080069static constexpr bool kDirectStream = true;
Jesse Wilson0c54ac12011-11-09 15:14:05 -050070
Andreas Gampe3a913092015-01-10 00:26:17 -080071static constexpr uint32_t kHprofTime = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -080072static constexpr uint32_t kHprofNullThread = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -070073
Andreas Gampe3a913092015-01-10 00:26:17 -080074static constexpr size_t kMaxObjectsPerSegment = 128;
75static constexpr size_t kMaxBytesPerSegment = 4096;
Elliott Hughes622a6982012-06-08 17:58:54 -070076
Andreas Gampe3a913092015-01-10 00:26:17 -080077// The static field-name for the synthetic object generated to account for class static overhead.
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -070078static constexpr const char* kClassOverheadName = "$classOverhead";
Elliott Hughes622a6982012-06-08 17:58:54 -070079
80enum HprofTag {
81 HPROF_TAG_STRING = 0x01,
82 HPROF_TAG_LOAD_CLASS = 0x02,
83 HPROF_TAG_UNLOAD_CLASS = 0x03,
84 HPROF_TAG_STACK_FRAME = 0x04,
85 HPROF_TAG_STACK_TRACE = 0x05,
86 HPROF_TAG_ALLOC_SITES = 0x06,
87 HPROF_TAG_HEAP_SUMMARY = 0x07,
88 HPROF_TAG_START_THREAD = 0x0A,
89 HPROF_TAG_END_THREAD = 0x0B,
90 HPROF_TAG_HEAP_DUMP = 0x0C,
91 HPROF_TAG_HEAP_DUMP_SEGMENT = 0x1C,
92 HPROF_TAG_HEAP_DUMP_END = 0x2C,
93 HPROF_TAG_CPU_SAMPLES = 0x0D,
94 HPROF_TAG_CONTROL_SETTINGS = 0x0E,
95};
96
97// Values for the first byte of HEAP_DUMP and HEAP_DUMP_SEGMENT records:
98enum HprofHeapTag {
99 // Traditional.
100 HPROF_ROOT_UNKNOWN = 0xFF,
101 HPROF_ROOT_JNI_GLOBAL = 0x01,
102 HPROF_ROOT_JNI_LOCAL = 0x02,
103 HPROF_ROOT_JAVA_FRAME = 0x03,
104 HPROF_ROOT_NATIVE_STACK = 0x04,
105 HPROF_ROOT_STICKY_CLASS = 0x05,
106 HPROF_ROOT_THREAD_BLOCK = 0x06,
107 HPROF_ROOT_MONITOR_USED = 0x07,
108 HPROF_ROOT_THREAD_OBJECT = 0x08,
109 HPROF_CLASS_DUMP = 0x20,
110 HPROF_INSTANCE_DUMP = 0x21,
111 HPROF_OBJECT_ARRAY_DUMP = 0x22,
112 HPROF_PRIMITIVE_ARRAY_DUMP = 0x23,
113
114 // Android.
115 HPROF_HEAP_DUMP_INFO = 0xfe,
116 HPROF_ROOT_INTERNED_STRING = 0x89,
117 HPROF_ROOT_FINALIZING = 0x8a, // Obsolete.
118 HPROF_ROOT_DEBUGGER = 0x8b,
119 HPROF_ROOT_REFERENCE_CLEANUP = 0x8c, // Obsolete.
120 HPROF_ROOT_VM_INTERNAL = 0x8d,
121 HPROF_ROOT_JNI_MONITOR = 0x8e,
122 HPROF_UNREACHABLE = 0x90, // Obsolete.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700123 HPROF_PRIMITIVE_ARRAY_NODATA_DUMP = 0xc3, // Obsolete.
Elliott Hughes622a6982012-06-08 17:58:54 -0700124};
125
126enum HprofHeapId {
127 HPROF_HEAP_DEFAULT = 0,
128 HPROF_HEAP_ZYGOTE = 'Z',
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700129 HPROF_HEAP_APP = 'A',
130 HPROF_HEAP_IMAGE = 'I',
Elliott Hughes622a6982012-06-08 17:58:54 -0700131};
132
133enum HprofBasicType {
134 hprof_basic_object = 2,
135 hprof_basic_boolean = 4,
136 hprof_basic_char = 5,
137 hprof_basic_float = 6,
138 hprof_basic_double = 7,
139 hprof_basic_byte = 8,
140 hprof_basic_short = 9,
141 hprof_basic_int = 10,
142 hprof_basic_long = 11,
143};
144
Ian Rogersef7d42f2014-01-06 12:55:46 -0800145typedef uint32_t HprofStringId;
146typedef uint32_t HprofClassObjectId;
Man Cao8c2ff642015-05-27 17:25:30 -0700147typedef uint32_t HprofClassSerialNumber;
148typedef uint32_t HprofStackTraceSerialNumber;
149typedef uint32_t HprofStackFrameId;
150static constexpr HprofStackTraceSerialNumber kHprofNullStackTrace = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -0700151
Andreas Gampe3a913092015-01-10 00:26:17 -0800152class EndianOutput {
Elliott Hughes622a6982012-06-08 17:58:54 -0700153 public:
Andreas Gampe3a913092015-01-10 00:26:17 -0800154 EndianOutput() : length_(0), sum_length_(0), max_length_(0), started_(false) {}
155 virtual ~EndianOutput() {}
156
157 void StartNewRecord(uint8_t tag, uint32_t time) {
158 if (length_ > 0) {
159 EndRecord();
160 }
161 DCHECK_EQ(length_, 0U);
162 AddU1(tag);
163 AddU4(time);
164 AddU4(0xdeaddead); // Length, replaced on flush.
165 started_ = true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700166 }
167
Andreas Gampe3a913092015-01-10 00:26:17 -0800168 void EndRecord() {
169 // Replace length in header.
170 if (started_) {
171 UpdateU4(sizeof(uint8_t) + sizeof(uint32_t),
172 length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
173 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700174
Andreas Gampe3a913092015-01-10 00:26:17 -0800175 HandleEndRecord();
176
177 sum_length_ += length_;
178 max_length_ = std::max(max_length_, length_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700179 length_ = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -0800180 started_ = false;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700181 }
182
Andreas Gampe3a913092015-01-10 00:26:17 -0800183 void AddU1(uint8_t value) {
184 AddU1List(&value, 1);
185 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800186 void AddU2(uint16_t value) {
187 AddU2List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700188 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800189 void AddU4(uint32_t value) {
190 AddU4List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700191 }
192
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800193 void AddU8(uint64_t value) {
194 AddU8List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700195 }
196
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800197 void AddObjectId(const mirror::Object* value) {
198 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800199 }
200
Man Cao8c2ff642015-05-27 17:25:30 -0700201 void AddStackTraceSerialNumber(HprofStackTraceSerialNumber value) {
202 AddU4(value);
203 }
204
Ian Rogersef7d42f2014-01-06 12:55:46 -0800205 // The ID for the synthetic object generated to account for class static overhead.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800206 void AddClassStaticsId(const mirror::Class* value) {
207 AddU4(1 | PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800208 }
209
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800210 void AddJniGlobalRefId(jobject value) {
211 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800212 }
213
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800214 void AddClassId(HprofClassObjectId value) {
215 AddU4(value);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800216 }
217
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800218 void AddStringId(HprofStringId value) {
219 AddU4(value);
Elliott Hughes622a6982012-06-08 17:58:54 -0700220 }
221
Andreas Gampe3a913092015-01-10 00:26:17 -0800222 void AddU1List(const uint8_t* values, size_t count) {
223 HandleU1List(values, count);
224 length_ += count;
225 }
226 void AddU2List(const uint16_t* values, size_t count) {
227 HandleU2List(values, count);
228 length_ += count * sizeof(uint16_t);
229 }
230 void AddU4List(const uint32_t* values, size_t count) {
231 HandleU4List(values, count);
232 length_ += count * sizeof(uint32_t);
233 }
Andreas Gampeca714582015-04-03 19:41:34 -0700234 virtual void UpdateU4(size_t offset, uint32_t new_value ATTRIBUTE_UNUSED) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800235 DCHECK_LE(offset, length_ - 4);
236 }
237 void AddU8List(const uint64_t* values, size_t count) {
238 HandleU8List(values, count);
239 length_ += count * sizeof(uint64_t);
240 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700241
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800242 void AddIdList(mirror::ObjectArray<mirror::Object>* values)
Mathieu Chartier90443472015-07-16 20:32:27 -0700243 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800244 const int32_t length = values->GetLength();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800245 for (int32_t i = 0; i < length; ++i) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800246 AddObjectId(values->GetWithoutChecks(i));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800247 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700248 }
249
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800250 void AddUtf8String(const char* str) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700251 // The terminating NUL character is NOT written.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800252 AddU1List((const uint8_t*)str, strlen(str));
Elliott Hughes622a6982012-06-08 17:58:54 -0700253 }
254
Andreas Gampe3a913092015-01-10 00:26:17 -0800255 size_t Length() const {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700256 return length_;
257 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700258
Andreas Gampe3a913092015-01-10 00:26:17 -0800259 size_t SumLength() const {
260 return sum_length_;
Elliott Hughes622a6982012-06-08 17:58:54 -0700261 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700262
Andreas Gampe3a913092015-01-10 00:26:17 -0800263 size_t MaxLength() const {
264 return max_length_;
265 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700266
Andreas Gampe3a913092015-01-10 00:26:17 -0800267 protected:
268 virtual void HandleU1List(const uint8_t* values ATTRIBUTE_UNUSED,
269 size_t count ATTRIBUTE_UNUSED) {
270 }
271 virtual void HandleU2List(const uint16_t* values ATTRIBUTE_UNUSED,
272 size_t count ATTRIBUTE_UNUSED) {
273 }
274 virtual void HandleU4List(const uint32_t* values ATTRIBUTE_UNUSED,
275 size_t count ATTRIBUTE_UNUSED) {
276 }
277 virtual void HandleU8List(const uint64_t* values ATTRIBUTE_UNUSED,
278 size_t count ATTRIBUTE_UNUSED) {
279 }
280 virtual void HandleEndRecord() {
281 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700282
Andreas Gampe3a913092015-01-10 00:26:17 -0800283 size_t length_; // Current record size.
284 size_t sum_length_; // Size of all data.
285 size_t max_length_; // Maximum seen length.
286 bool started_; // Was StartRecord called?
Elliott Hughes622a6982012-06-08 17:58:54 -0700287};
288
Andreas Gampe3a913092015-01-10 00:26:17 -0800289// This keeps things buffered until flushed.
290class EndianOutputBuffered : public EndianOutput {
291 public:
292 explicit EndianOutputBuffered(size_t reserve_size) {
293 buffer_.reserve(reserve_size);
294 }
295 virtual ~EndianOutputBuffered() {}
296
297 void UpdateU4(size_t offset, uint32_t new_value) OVERRIDE {
298 DCHECK_LE(offset, length_ - 4);
299 buffer_[offset + 0] = static_cast<uint8_t>((new_value >> 24) & 0xFF);
300 buffer_[offset + 1] = static_cast<uint8_t>((new_value >> 16) & 0xFF);
301 buffer_[offset + 2] = static_cast<uint8_t>((new_value >> 8) & 0xFF);
302 buffer_[offset + 3] = static_cast<uint8_t>((new_value >> 0) & 0xFF);
303 }
304
305 protected:
306 void HandleU1List(const uint8_t* values, size_t count) OVERRIDE {
307 DCHECK_EQ(length_, buffer_.size());
308 buffer_.insert(buffer_.end(), values, values + count);
309 }
310
311 void HandleU2List(const uint16_t* values, size_t count) OVERRIDE {
312 DCHECK_EQ(length_, buffer_.size());
313 for (size_t i = 0; i < count; ++i) {
314 uint16_t value = *values;
315 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
316 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
317 values++;
318 }
319 }
320
321 void HandleU4List(const uint32_t* values, size_t count) OVERRIDE {
322 DCHECK_EQ(length_, buffer_.size());
323 for (size_t i = 0; i < count; ++i) {
324 uint32_t value = *values;
325 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
326 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
327 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
328 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
329 values++;
330 }
331 }
332
333 void HandleU8List(const uint64_t* values, size_t count) OVERRIDE {
334 DCHECK_EQ(length_, buffer_.size());
335 for (size_t i = 0; i < count; ++i) {
336 uint64_t value = *values;
337 buffer_.push_back(static_cast<uint8_t>((value >> 56) & 0xFF));
338 buffer_.push_back(static_cast<uint8_t>((value >> 48) & 0xFF));
339 buffer_.push_back(static_cast<uint8_t>((value >> 40) & 0xFF));
340 buffer_.push_back(static_cast<uint8_t>((value >> 32) & 0xFF));
341 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
342 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
343 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
344 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
345 values++;
346 }
347 }
348
349 void HandleEndRecord() OVERRIDE {
350 DCHECK_EQ(buffer_.size(), length_);
351 if (kIsDebugBuild && started_) {
352 uint32_t stored_length =
353 static_cast<uint32_t>(buffer_[5]) << 24 |
354 static_cast<uint32_t>(buffer_[6]) << 16 |
355 static_cast<uint32_t>(buffer_[7]) << 8 |
356 static_cast<uint32_t>(buffer_[8]);
357 DCHECK_EQ(stored_length, length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
358 }
359 HandleFlush(buffer_.data(), length_);
360 buffer_.clear();
361 }
362
363 virtual void HandleFlush(const uint8_t* buffer ATTRIBUTE_UNUSED, size_t length ATTRIBUTE_UNUSED) {
364 }
365
366 std::vector<uint8_t> buffer_;
367};
368
369class FileEndianOutput FINAL : public EndianOutputBuffered {
370 public:
371 FileEndianOutput(File* fp, size_t reserved_size)
372 : EndianOutputBuffered(reserved_size), fp_(fp), errors_(false) {
373 DCHECK(fp != nullptr);
374 }
375 ~FileEndianOutput() {
376 }
377
378 bool Errors() {
379 return errors_;
380 }
381
382 protected:
383 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
384 if (!errors_) {
385 errors_ = !fp_->WriteFully(buffer, length);
386 }
387 }
388
389 private:
390 File* fp_;
391 bool errors_;
392};
393
394class NetStateEndianOutput FINAL : public EndianOutputBuffered {
395 public:
396 NetStateEndianOutput(JDWP::JdwpNetStateBase* net_state, size_t reserved_size)
397 : EndianOutputBuffered(reserved_size), net_state_(net_state) {
398 DCHECK(net_state != nullptr);
399 }
400 ~NetStateEndianOutput() {}
401
402 protected:
403 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
404 std::vector<iovec> iov;
405 iov.push_back(iovec());
406 iov[0].iov_base = const_cast<void*>(reinterpret_cast<const void*>(buffer));
407 iov[0].iov_len = length;
408 net_state_->WriteBufferedPacketLocked(iov);
409 }
410
411 private:
412 JDWP::JdwpNetStateBase* net_state_;
413};
414
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700415#define __ output_->
Andreas Gampe3a913092015-01-10 00:26:17 -0800416
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700417class Hprof : public SingleRootVisitor {
Elliott Hughes622a6982012-06-08 17:58:54 -0700418 public:
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700419 Hprof(const char* output_filename, int fd, bool direct_to_ddms)
420 : filename_(output_filename),
421 fd_(fd),
422 direct_to_ddms_(direct_to_ddms),
423 start_ns_(NanoTime()),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700424 current_heap_(HPROF_HEAP_DEFAULT),
425 objects_in_segment_(0),
Man Cao8c2ff642015-05-27 17:25:30 -0700426 next_string_id_(0x400000),
427 next_class_serial_number_(1) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700428 LOG(INFO) << "hprof: heap dump \"" << filename_ << "\" starting...";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500429 }
430
Andreas Gampe3a913092015-01-10 00:26:17 -0800431 void Dump()
Mathieu Chartier90443472015-07-16 20:32:27 -0700432 REQUIRES(Locks::mutator_lock_, !Locks::heap_bitmap_lock_, !Locks::alloc_tracker_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700433 {
434 MutexLock mu(Thread::Current(), *Locks::alloc_tracker_lock_);
435 if (Runtime::Current()->GetHeap()->IsAllocTrackingEnabled()) {
436 PopulateAllocationTrackingTraces();
437 }
438 }
439
Andreas Gampe3a913092015-01-10 00:26:17 -0800440 // First pass to measure the size of the dump.
441 size_t overall_size;
442 size_t max_length;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800443 {
Andreas Gampe3a913092015-01-10 00:26:17 -0800444 EndianOutput count_output;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700445 output_ = &count_output;
446 ProcessHeap(false);
Andreas Gampe3a913092015-01-10 00:26:17 -0800447 overall_size = count_output.SumLength();
448 max_length = count_output.MaxLength();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700449 output_ = nullptr;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800450 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700451
Andreas Gampe3a913092015-01-10 00:26:17 -0800452 bool okay;
453 if (direct_to_ddms_) {
454 if (kDirectStream) {
455 okay = DumpToDdmsDirect(overall_size, max_length, CHUNK_TYPE("HPDS"));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700456 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800457 okay = DumpToDdmsBuffered(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700458 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800459 } else {
460 okay = DumpToFile(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700461 }
462
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700463 if (okay) {
464 uint64_t duration = NanoTime() - start_ns_;
Ian Rogers50b35e22012-10-04 10:09:15 -0700465 LOG(INFO) << "hprof: heap dump completed ("
Andreas Gampe3a913092015-01-10 00:26:17 -0800466 << PrettySize(RoundUp(overall_size, 1024))
Ian Rogers50b35e22012-10-04 10:09:15 -0700467 << ") in " << PrettyDuration(duration);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700468 }
469 }
470
471 private:
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800472 static void VisitObjectCallback(mirror::Object* obj, void* arg)
Mathieu Chartier90443472015-07-16 20:32:27 -0700473 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800474 DCHECK(obj != nullptr);
475 DCHECK(arg != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700476 reinterpret_cast<Hprof*>(arg)->DumpHeapObject(obj);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700477 }
478
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700479 void DumpHeapObject(mirror::Object* obj)
Mathieu Chartier90443472015-07-16 20:32:27 -0700480 SHARED_REQUIRES(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700481
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700482 void DumpHeapClass(mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700483 SHARED_REQUIRES(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700484
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700485 void DumpHeapArray(mirror::Array* obj, mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700486 SHARED_REQUIRES(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800487
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700488 void DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass)
Mathieu Chartier90443472015-07-16 20:32:27 -0700489 SHARED_REQUIRES(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800490
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700491 void ProcessHeap(bool header_first)
Mathieu Chartier90443472015-07-16 20:32:27 -0700492 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800493 // Reset current heap and object count.
494 current_heap_ = HPROF_HEAP_DEFAULT;
495 objects_in_segment_ = 0;
496
497 if (header_first) {
Man Cao8c2ff642015-05-27 17:25:30 -0700498 ProcessHeader(true);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700499 ProcessBody();
Andreas Gampe3a913092015-01-10 00:26:17 -0800500 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700501 ProcessBody();
Man Cao8c2ff642015-05-27 17:25:30 -0700502 ProcessHeader(false);
Andreas Gampe3a913092015-01-10 00:26:17 -0800503 }
504 }
505
Mathieu Chartier90443472015-07-16 20:32:27 -0700506 void ProcessBody() REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700507 Runtime* const runtime = Runtime::Current();
Andreas Gampe3a913092015-01-10 00:26:17 -0800508 // Walk the roots and the heap.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700509 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Andreas Gampe3a913092015-01-10 00:26:17 -0800510
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700511 runtime->VisitRoots(this);
512 runtime->VisitImageRoots(this);
513 runtime->GetHeap()->VisitObjectsPaused(VisitObjectCallback, this);
Andreas Gampe3a913092015-01-10 00:26:17 -0800514
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700515 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_END, kHprofTime);
516 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800517 }
518
Mathieu Chartier90443472015-07-16 20:32:27 -0700519 void ProcessHeader(bool string_first) REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800520 // Write the header.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700521 WriteFixedHeader();
Andreas Gampe3a913092015-01-10 00:26:17 -0800522 // Write the string and class tables, and any stack traces, to the header.
523 // (jhat requires that these appear before any of the data in the body that refers to them.)
Man Cao8c2ff642015-05-27 17:25:30 -0700524 // jhat also requires the string table appear before class table and stack traces.
525 // However, WriteStackTraces() can modify the string table, so it's necessary to call
526 // WriteStringTable() last in the first pass, to compute the correct length of the output.
527 if (string_first) {
528 WriteStringTable();
529 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700530 WriteClassTable();
531 WriteStackTraces();
Man Cao8c2ff642015-05-27 17:25:30 -0700532 if (!string_first) {
533 WriteStringTable();
534 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700535 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800536 }
537
Mathieu Chartier90443472015-07-16 20:32:27 -0700538 void WriteClassTable() SHARED_REQUIRES(Locks::mutator_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700539 for (const auto& p : classes_) {
540 mirror::Class* c = p.first;
541 HprofClassSerialNumber sn = p.second;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800542 CHECK(c != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700543 output_->StartNewRecord(HPROF_TAG_LOAD_CLASS, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700544 // LOAD CLASS format:
545 // U4: class serial number (always > 0)
546 // ID: class object ID. We use the address of the class object structure as its ID.
547 // U4: stack trace serial number
548 // ID: class name string ID
Man Cao8c2ff642015-05-27 17:25:30 -0700549 __ AddU4(sn);
Andreas Gampe3a913092015-01-10 00:26:17 -0800550 __ AddObjectId(c);
Man Cao8c2ff642015-05-27 17:25:30 -0700551 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(c));
Andreas Gampe3a913092015-01-10 00:26:17 -0800552 __ AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700553 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700554 }
555
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700556 void WriteStringTable() {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800557 for (const std::pair<std::string, HprofStringId>& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800558 const std::string& string = p.first;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800559 const size_t id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700560
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700561 output_->StartNewRecord(HPROF_TAG_STRING, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700562
563 // STRING format:
564 // ID: ID for this string
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700565 // U1*: UTF8 characters for string (NOT null terminated)
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700566 // (the record format encodes the length)
Andreas Gampe3a913092015-01-10 00:26:17 -0800567 __ AddU4(id);
568 __ AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700569 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700570 }
571
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700572 void StartNewHeapDumpSegment() {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700573 // This flushes the old segment and starts a new one.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700574 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700575 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700576 // Starting a new HEAP_DUMP resets the heap to default.
577 current_heap_ = HPROF_HEAP_DEFAULT;
578 }
579
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700580 void CheckHeapSegmentConstraints() {
581 if (objects_in_segment_ >= kMaxObjectsPerSegment || output_->Length() >= kMaxBytesPerSegment) {
582 StartNewHeapDumpSegment();
Andreas Gampe3a913092015-01-10 00:26:17 -0800583 }
584 }
585
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700586 void VisitRoot(mirror::Object* obj, const RootInfo& root_info)
Mathieu Chartier90443472015-07-16 20:32:27 -0700587 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800588 void MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700589 uint32_t thread_serial);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700590
Mathieu Chartier90443472015-07-16 20:32:27 -0700591 HprofClassObjectId LookupClassId(mirror::Class* c) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800592 if (c != nullptr) {
Man Cao8c2ff642015-05-27 17:25:30 -0700593 auto it = classes_.find(c);
594 if (it == classes_.end()) {
595 // first time to see this class
596 HprofClassSerialNumber sn = next_class_serial_number_++;
597 classes_.Put(c, sn);
598 // Make sure that we've assigned a string ID for this class' name
599 LookupClassNameId(c);
600 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800601 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800602 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700603 }
604
Man Cao8c2ff642015-05-27 17:25:30 -0700605 HprofStackTraceSerialNumber LookupStackTraceSerialNumber(const mirror::Object* obj)
Mathieu Chartier90443472015-07-16 20:32:27 -0700606 SHARED_REQUIRES(Locks::mutator_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700607 auto r = allocation_records_.find(obj);
608 if (r == allocation_records_.end()) {
609 return kHprofNullStackTrace;
610 } else {
611 const gc::AllocRecordStackTrace* trace = r->second;
612 auto result = traces_.find(trace);
613 CHECK(result != traces_.end());
614 return result->second;
615 }
616 }
617
Mathieu Chartier90443472015-07-16 20:32:27 -0700618 HprofStringId LookupStringId(mirror::String* string) SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700619 return LookupStringId(string->ToModifiedUtf8());
620 }
621
622 HprofStringId LookupStringId(const char* string) {
623 return LookupStringId(std::string(string));
624 }
625
626 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800627 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700628 if (it != strings_.end()) {
629 return it->second;
630 }
631 HprofStringId id = next_string_id_++;
632 strings_.Put(string, id);
633 return id;
634 }
635
Mathieu Chartier90443472015-07-16 20:32:27 -0700636 HprofStringId LookupClassNameId(mirror::Class* c) SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700637 return LookupStringId(PrettyDescriptor(c));
638 }
639
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700640 void WriteFixedHeader() {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500641 // Write the file header.
642 // U1: NUL-terminated magic string.
Andreas Gampe3a913092015-01-10 00:26:17 -0800643 const char magic[] = "JAVA PROFILE 1.0.3";
644 __ AddU1List(reinterpret_cast<const uint8_t*>(magic), sizeof(magic));
645
Calin Juravle32805172014-07-04 16:24:03 +0100646 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
647 // as uint32_t.
648 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800649 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
650 "Unexpected HeapReference size");
Andreas Gampe3a913092015-01-10 00:26:17 -0800651 __ AddU4(sizeof(uint32_t));
652
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500653 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700654 timeval now;
Andreas Gampe3a913092015-01-10 00:26:17 -0800655 const uint64_t nowMs = (gettimeofday(&now, nullptr) < 0) ? 0 :
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800656 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Andreas Gampe3a913092015-01-10 00:26:17 -0800657 // TODO: It seems it would be correct to use U8.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500658 // U4: high word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800659 __ AddU4(static_cast<uint32_t>(nowMs >> 32));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500660 // U4: low word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800661 __ AddU4(static_cast<uint32_t>(nowMs & 0xFFFFFFFF));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500662 }
663
Mathieu Chartier90443472015-07-16 20:32:27 -0700664 void WriteStackTraces() SHARED_REQUIRES(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700665 // Write a dummy stack trace record so the analysis tools don't freak out.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700666 output_->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
Man Cao8c2ff642015-05-27 17:25:30 -0700667 __ AddStackTraceSerialNumber(kHprofNullStackTrace);
Andreas Gampe3a913092015-01-10 00:26:17 -0800668 __ AddU4(kHprofNullThread);
669 __ AddU4(0); // no frames
Man Cao8c2ff642015-05-27 17:25:30 -0700670
671 // TODO: jhat complains "WARNING: Stack trace not found for serial # -1", but no trace should
672 // have -1 as its serial number (as long as HprofStackTraceSerialNumber doesn't overflow).
673 for (const auto& it : traces_) {
674 const gc::AllocRecordStackTrace* trace = it.first;
675 HprofStackTraceSerialNumber trace_sn = it.second;
676 size_t depth = trace->GetDepth();
677
678 // First write stack frames of the trace
679 for (size_t i = 0; i < depth; ++i) {
680 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
681 ArtMethod* method = frame->GetMethod();
682 CHECK(method != nullptr);
683 output_->StartNewRecord(HPROF_TAG_STACK_FRAME, kHprofTime);
684 // STACK FRAME format:
685 // ID: stack frame ID. We use the address of the AllocRecordStackTraceElement object as its ID.
686 // ID: method name string ID
687 // ID: method signature string ID
688 // ID: source file name string ID
689 // U4: class serial number
690 // U4: >0, line number; 0, no line information available; -1, unknown location
691 auto frame_result = frames_.find(frame);
692 CHECK(frame_result != frames_.end());
693 __ AddU4(frame_result->second);
694 __ AddStringId(LookupStringId(method->GetName()));
695 __ AddStringId(LookupStringId(method->GetSignature().ToString()));
696 const char* source_file = method->GetDeclaringClassSourceFile();
697 if (source_file == nullptr) {
698 source_file = "";
699 }
700 __ AddStringId(LookupStringId(source_file));
701 auto class_result = classes_.find(method->GetDeclaringClass());
702 CHECK(class_result != classes_.end());
703 __ AddU4(class_result->second);
704 __ AddU4(frame->ComputeLineNumber());
705 }
706
707 // Then write the trace itself
708 output_->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
709 // STACK TRACE format:
710 // U4: stack trace serial number. We use the address of the AllocRecordStackTrace object as its serial number.
711 // U4: thread serial number. We use Thread::GetTid().
712 // U4: number of frames
713 // [ID]*: series of stack frame ID's
714 __ AddStackTraceSerialNumber(trace_sn);
715 __ AddU4(trace->GetTid());
716 __ AddU4(depth);
717 for (size_t i = 0; i < depth; ++i) {
718 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
719 auto frame_result = frames_.find(frame);
720 CHECK(frame_result != frames_.end());
721 __ AddU4(frame_result->second);
722 }
723 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800724 }
725
726 bool DumpToDdmsBuffered(size_t overall_size ATTRIBUTE_UNUSED, size_t max_length ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700727 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800728 LOG(FATAL) << "Unimplemented";
729 UNREACHABLE();
730 // // Send the data off to DDMS.
731 // iovec iov[2];
732 // iov[0].iov_base = header_data_ptr_;
733 // iov[0].iov_len = header_data_size_;
734 // iov[1].iov_base = body_data_ptr_;
735 // iov[1].iov_len = body_data_size_;
736 // Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
737 }
738
739 bool DumpToFile(size_t overall_size, size_t max_length)
Mathieu Chartier90443472015-07-16 20:32:27 -0700740 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800741 // Where exactly are we writing to?
742 int out_fd;
743 if (fd_ >= 0) {
744 out_fd = dup(fd_);
745 if (out_fd < 0) {
746 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
747 return false;
748 }
749 } else {
750 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
751 if (out_fd < 0) {
752 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
753 strerror(errno));
754 return false;
755 }
756 }
757
758 std::unique_ptr<File> file(new File(out_fd, filename_, true));
759 bool okay;
760 {
761 FileEndianOutput file_output(file.get(), max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700762 output_ = &file_output;
763 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800764 okay = !file_output.Errors();
765
766 if (okay) {
767 // Check for expected size.
768 CHECK_EQ(file_output.SumLength(), overall_size);
769 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700770 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800771 }
772
773 if (okay) {
774 okay = file->FlushCloseOrErase() == 0;
775 } else {
776 file->Erase();
777 }
778 if (!okay) {
779 std::string msg(StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
780 filename_.c_str(), strerror(errno)));
781 ThrowRuntimeException("%s", msg.c_str());
782 LOG(ERROR) << msg;
783 }
784
785 return okay;
786 }
787
788 bool DumpToDdmsDirect(size_t overall_size, size_t max_length, uint32_t chunk_type)
Mathieu Chartier90443472015-07-16 20:32:27 -0700789 REQUIRES(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800790 CHECK(direct_to_ddms_);
791 JDWP::JdwpState* state = Dbg::GetJdwpState();
792 CHECK(state != nullptr);
793 JDWP::JdwpNetStateBase* net_state = state->netState;
794 CHECK(net_state != nullptr);
795
796 // Hold the socket lock for the whole time since we want this to be atomic.
797 MutexLock mu(Thread::Current(), *net_state->GetSocketLock());
798
799 // Prepare the Ddms chunk.
800 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
801 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
802 state->SetupChunkHeader(chunk_type, overall_size, kChunkHeaderSize, chunk_header);
803
804 // Prepare the output and send the chunk header.
805 NetStateEndianOutput net_output(net_state, max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700806 output_ = &net_output;
Andreas Gampe3a913092015-01-10 00:26:17 -0800807 net_output.AddU1List(chunk_header, kChunkHeaderSize);
808
809 // Write the dump.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700810 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800811
812 // Check for expected size.
813 CHECK_EQ(net_output.SumLength(), overall_size + kChunkHeaderSize);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700814 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800815
816 return true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700817 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500818
Man Cao8c2ff642015-05-27 17:25:30 -0700819 void PopulateAllocationTrackingTraces()
Mathieu Chartier90443472015-07-16 20:32:27 -0700820 REQUIRES(Locks::mutator_lock_, Locks::alloc_tracker_lock_) {
Man Cao8c2ff642015-05-27 17:25:30 -0700821 gc::AllocRecordObjectMap* records = Runtime::Current()->GetHeap()->GetAllocationRecords();
822 CHECK(records != nullptr);
823 HprofStackTraceSerialNumber next_trace_sn = kHprofNullStackTrace + 1;
824 HprofStackFrameId next_frame_id = 0;
Man Cao42c3c332015-06-23 16:38:25 -0700825 size_t count = 0;
Man Cao8c2ff642015-05-27 17:25:30 -0700826
827 for (auto it = records->Begin(), end = records->End(); it != end; ++it) {
828 const mirror::Object* obj = it->first.Read();
Man Cao42c3c332015-06-23 16:38:25 -0700829 if (obj == nullptr) {
830 continue;
831 }
832 ++count;
Man Cao8c2ff642015-05-27 17:25:30 -0700833 const gc::AllocRecordStackTrace* trace = it->second->GetStackTrace();
834
835 // Copy the pair into a real hash map to speed up look up.
836 auto records_result = allocation_records_.emplace(obj, trace);
837 // The insertion should always succeed, i.e. no duplicate object pointers in "records"
838 CHECK(records_result.second);
839
840 // Generate serial numbers for traces, and IDs for frames.
841 auto traces_result = traces_.find(trace);
842 if (traces_result == traces_.end()) {
843 traces_.emplace(trace, next_trace_sn++);
844 // only check frames if the trace is newly discovered
845 for (size_t i = 0, depth = trace->GetDepth(); i < depth; ++i) {
846 const gc::AllocRecordStackTraceElement* frame = &trace->GetStackElement(i);
847 auto frames_result = frames_.find(frame);
848 if (frames_result == frames_.end()) {
849 frames_.emplace(frame, next_frame_id++);
850 }
851 }
852 }
853 }
854 CHECK_EQ(traces_.size(), next_trace_sn - kHprofNullStackTrace - 1);
855 CHECK_EQ(frames_.size(), next_frame_id);
Man Cao42c3c332015-06-23 16:38:25 -0700856 VLOG(heap) << "hprof: found " << count << " objects with allocation stack traces";
Man Cao8c2ff642015-05-27 17:25:30 -0700857 }
858
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700859 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
860 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
861 // only be used for debug messages.
862 std::string filename_;
863 int fd_;
864 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500865
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700866 uint64_t start_ns_;
867
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700868 EndianOutput* output_;
869
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700870 HprofHeapId current_heap_; // Which heap we're currently dumping.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700871 size_t objects_in_segment_;
872
Ian Rogersef7d42f2014-01-06 12:55:46 -0800873 HprofStringId next_string_id_;
874 SafeMap<std::string, HprofStringId> strings_;
Man Cao8c2ff642015-05-27 17:25:30 -0700875 HprofClassSerialNumber next_class_serial_number_;
876 SafeMap<mirror::Class*, HprofClassSerialNumber> classes_;
877
878 std::unordered_map<const gc::AllocRecordStackTrace*, HprofStackTraceSerialNumber,
879 gc::HashAllocRecordTypesPtr<gc::AllocRecordStackTrace>,
880 gc::EqAllocRecordTypesPtr<gc::AllocRecordStackTrace>> traces_;
881 std::unordered_map<const gc::AllocRecordStackTraceElement*, HprofStackFrameId,
882 gc::HashAllocRecordTypesPtr<gc::AllocRecordStackTraceElement>,
883 gc::EqAllocRecordTypesPtr<gc::AllocRecordStackTraceElement>> frames_;
884 std::unordered_map<const mirror::Object*, const gc::AllocRecordStackTrace*> allocation_records_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700885
Mathieu Chartiere4275c02015-08-06 15:34:15 -0700886 friend class GcRootVisitor;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700887 DISALLOW_COPY_AND_ASSIGN(Hprof);
888};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500889
Andreas Gampe3a913092015-01-10 00:26:17 -0800890static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* size_out) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500891 char c = sig[0];
892 HprofBasicType ret;
893 size_t size;
894
895 switch (c) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800896 case '[':
897 case 'L':
898 ret = hprof_basic_object;
899 size = 4;
900 break;
901 case 'Z':
902 ret = hprof_basic_boolean;
903 size = 1;
904 break;
905 case 'C':
906 ret = hprof_basic_char;
907 size = 2;
908 break;
909 case 'F':
910 ret = hprof_basic_float;
911 size = 4;
912 break;
913 case 'D':
914 ret = hprof_basic_double;
915 size = 8;
916 break;
917 case 'B':
918 ret = hprof_basic_byte;
919 size = 1;
920 break;
921 case 'S':
922 ret = hprof_basic_short;
923 size = 2;
924 break;
925 case 'I':
926 ret = hprof_basic_int;
927 size = 4;
928 break;
929 case 'J':
930 ret = hprof_basic_long;
931 size = 8;
932 break;
933 default:
934 LOG(FATAL) << "UNREACHABLE";
935 UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500936 }
937
Andreas Gampe3a913092015-01-10 00:26:17 -0800938 if (size_out != nullptr) {
939 *size_out = size;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500940 }
941
942 return ret;
943}
944
945// Always called when marking objects, but only does
946// something when ctx->gc_scan_state_ is non-zero, which is usually
947// only true when marking the root set or unreachable
948// objects. Used to add rootset references to obj.
Andreas Gampe3a913092015-01-10 00:26:17 -0800949void Hprof::MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700950 uint32_t thread_serial) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800951 if (heap_tag == 0) {
952 return;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500953 }
954
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700955 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500956
Andreas Gampe3a913092015-01-10 00:26:17 -0800957 switch (heap_tag) {
958 // ID: object ID
959 case HPROF_ROOT_UNKNOWN:
960 case HPROF_ROOT_STICKY_CLASS:
961 case HPROF_ROOT_MONITOR_USED:
962 case HPROF_ROOT_INTERNED_STRING:
963 case HPROF_ROOT_DEBUGGER:
964 case HPROF_ROOT_VM_INTERNAL:
965 __ AddU1(heap_tag);
966 __ AddObjectId(obj);
967 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500968
Andreas Gampe3a913092015-01-10 00:26:17 -0800969 // ID: object ID
970 // ID: JNI global ref ID
971 case HPROF_ROOT_JNI_GLOBAL:
972 __ AddU1(heap_tag);
973 __ AddObjectId(obj);
974 __ AddJniGlobalRefId(jni_obj);
975 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500976
Andreas Gampe3a913092015-01-10 00:26:17 -0800977 // ID: object ID
978 // U4: thread serial number
979 // U4: frame number in stack trace (-1 for empty)
980 case HPROF_ROOT_JNI_LOCAL:
981 case HPROF_ROOT_JNI_MONITOR:
982 case HPROF_ROOT_JAVA_FRAME:
983 __ AddU1(heap_tag);
984 __ AddObjectId(obj);
985 __ AddU4(thread_serial);
986 __ AddU4((uint32_t)-1);
987 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500988
Andreas Gampe3a913092015-01-10 00:26:17 -0800989 // ID: object ID
990 // U4: thread serial number
991 case HPROF_ROOT_NATIVE_STACK:
992 case HPROF_ROOT_THREAD_BLOCK:
993 __ AddU1(heap_tag);
994 __ AddObjectId(obj);
995 __ AddU4(thread_serial);
996 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500997
Andreas Gampe3a913092015-01-10 00:26:17 -0800998 // ID: thread object ID
999 // U4: thread serial number
1000 // U4: stack trace serial number
1001 case HPROF_ROOT_THREAD_OBJECT:
1002 __ AddU1(heap_tag);
1003 __ AddObjectId(obj);
1004 __ AddU4(thread_serial);
1005 __ AddU4((uint32_t)-1); // xxx
1006 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001007
Andreas Gampe3a913092015-01-10 00:26:17 -08001008 case HPROF_CLASS_DUMP:
1009 case HPROF_INSTANCE_DUMP:
1010 case HPROF_OBJECT_ARRAY_DUMP:
1011 case HPROF_PRIMITIVE_ARRAY_DUMP:
1012 case HPROF_HEAP_DUMP_INFO:
1013 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
1014 // Ignored.
1015 break;
Elliott Hughes73e66f72012-05-09 09:34:45 -07001016
Andreas Gampe3a913092015-01-10 00:26:17 -08001017 case HPROF_ROOT_FINALIZING:
1018 case HPROF_ROOT_REFERENCE_CLEANUP:
1019 case HPROF_UNREACHABLE:
1020 LOG(FATAL) << "obsolete tag " << static_cast<int>(heap_tag);
1021 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001022 }
1023
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001024 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001025}
1026
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001027// Use for visiting the GcRoots held live by ArtFields, ArtMethods, and ClassLoaders.
1028class GcRootVisitor {
1029 public:
1030 explicit GcRootVisitor(Hprof* hprof) : hprof_(hprof) {}
1031
1032 void operator()(mirror::Object* obj ATTRIBUTE_UNUSED,
1033 MemberOffset offset ATTRIBUTE_UNUSED,
1034 bool is_static ATTRIBUTE_UNUSED) const {}
1035
1036 // Note that these don't have read barriers. Its OK however since the GC is guaranteed to not be
1037 // running during the hprof dumping process.
1038 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1039 SHARED_REQUIRES(Locks::mutator_lock_) {
1040 if (!root->IsNull()) {
1041 VisitRoot(root);
1042 }
1043 }
1044
1045 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1046 SHARED_REQUIRES(Locks::mutator_lock_) {
1047 mirror::Object* obj = root->AsMirrorPtr();
1048 // The two cases are either classes or dex cache arrays. If it is a dex cache array, then use
1049 // VM internal. Otherwise the object is a declaring class of an ArtField or ArtMethod or a
1050 // class from a ClassLoader.
1051 hprof_->VisitRoot(obj, RootInfo(obj->IsClass() ? kRootStickyClass : kRootVMInternal));
1052 }
1053
1054
1055 private:
1056 Hprof* const hprof_;
1057};
1058
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001059void Hprof::DumpHeapObject(mirror::Object* obj) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001060 // Ignore classes that are retired.
1061 if (obj->IsClass() && obj->AsClass()->IsRetired()) {
1062 return;
1063 }
1064
Mathieu Chartiere4275c02015-08-06 15:34:15 -07001065 GcRootVisitor visitor(this);
1066 obj->VisitReferences<true>(visitor, VoidFunctor());
1067
Mathieu Chartiere7158112015-06-03 13:32:15 -07001068 gc::Heap* const heap = Runtime::Current()->GetHeap();
1069 const gc::space::ContinuousSpace* const space = heap->FindContinuousSpaceFromObject(obj, true);
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001070 HprofHeapId heap_type = HPROF_HEAP_APP;
1071 if (space != nullptr) {
1072 if (space->IsZygoteSpace()) {
1073 heap_type = HPROF_HEAP_ZYGOTE;
1074 } else if (space->IsImageSpace()) {
1075 heap_type = HPROF_HEAP_IMAGE;
1076 }
Mathieu Chartiere7158112015-06-03 13:32:15 -07001077 } else {
1078 const auto* los = heap->GetLargeObjectsSpace();
1079 if (los->Contains(obj) && los->IsZygoteLargeObject(Thread::Current(), obj)) {
1080 heap_type = HPROF_HEAP_ZYGOTE;
1081 }
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001082 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001083 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001084
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001085 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001086 HprofStringId nameId;
1087
1088 // This object is in a different heap than the current one.
1089 // Emit a HEAP_DUMP_INFO tag to change heaps.
Andreas Gampe3a913092015-01-10 00:26:17 -08001090 __ AddU1(HPROF_HEAP_DUMP_INFO);
1091 __ AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001092 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001093 case HPROF_HEAP_APP:
1094 nameId = LookupStringId("app");
1095 break;
1096 case HPROF_HEAP_ZYGOTE:
1097 nameId = LookupStringId("zygote");
1098 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001099 case HPROF_HEAP_IMAGE:
1100 nameId = LookupStringId("image");
1101 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001102 default:
1103 // Internal error
1104 LOG(ERROR) << "Unexpected desiredHeap";
1105 nameId = LookupStringId("<ILLEGAL>");
1106 break;
1107 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001108 __ AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -07001109 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001110 }
1111
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001112 mirror::Class* c = obj->GetClass();
Andreas Gampe3a913092015-01-10 00:26:17 -08001113 if (c == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001114 // This object will bother HprofReader, because it has a null
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001115 // class, so just don't dump it. It could be
1116 // gDvm.unlinkedJavaLangClass or it could be an object just
1117 // allocated which hasn't been initialized yet.
1118 } else {
1119 if (obj->IsClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001120 DumpHeapClass(obj->AsClass());
Elliott Hughese84278b2012-03-22 10:06:53 -07001121 } else if (c->IsArrayClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001122 DumpHeapArray(obj->AsArray(), c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001123 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001124 DumpHeapInstanceObject(obj, c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001125 }
1126 }
1127
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001128 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001129}
1130
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001131void Hprof::DumpHeapClass(mirror::Class* klass) {
Sebastien Hertzca068b22015-04-07 10:28:53 +02001132 if (!klass->IsLoaded() && !klass->IsErroneous()) {
1133 // Class is allocated but not yet loaded: we cannot access its fields or super class.
1134 return;
1135 }
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001136 const size_t num_static_fields = klass->NumStaticFields();
1137 // Total class size including embedded IMT, embedded vtable, and static fields.
1138 const size_t class_size = klass->GetClassSize();
1139 // Class size excluding static fields (relies on reference fields being the first static fields).
1140 const size_t class_size_without_overhead = sizeof(mirror::Class);
1141 CHECK_LE(class_size_without_overhead, class_size);
1142 const size_t overhead_size = class_size - class_size_without_overhead;
1143
1144 if (overhead_size != 0) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001145 // Create a byte array to reflect the allocation of the
1146 // StaticField array at the end of this class.
1147 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1148 __ AddClassStaticsId(klass);
Man Cao8c2ff642015-05-27 17:25:30 -07001149 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(klass));
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001150 __ AddU4(overhead_size);
Andreas Gampe3a913092015-01-10 00:26:17 -08001151 __ AddU1(hprof_basic_byte);
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001152 for (size_t i = 0; i < overhead_size; ++i) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001153 __ AddU1(0);
1154 }
1155 }
1156
1157 __ AddU1(HPROF_CLASS_DUMP);
1158 __ AddClassId(LookupClassId(klass));
Man Cao8c2ff642015-05-27 17:25:30 -07001159 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001160 __ AddClassId(LookupClassId(klass->GetSuperClass()));
1161 __ AddObjectId(klass->GetClassLoader());
1162 __ AddObjectId(nullptr); // no signer
1163 __ AddObjectId(nullptr); // no prot domain
1164 __ AddObjectId(nullptr); // reserved
1165 __ AddObjectId(nullptr); // reserved
1166 if (klass->IsClassClass()) {
1167 // ClassObjects have their static fields appended, so aren't all the same size.
1168 // But they're at least this size.
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001169 __ AddU4(class_size_without_overhead); // instance size
Jeff Hao0ce43532015-05-12 18:58:32 -07001170 } else if (klass->IsStringClass()) {
1171 // Strings are variable length with character data at the end like arrays.
1172 // This outputs the size of an empty string.
1173 __ AddU4(sizeof(mirror::String));
1174 } else if (klass->IsArrayClass() || klass->IsPrimitive()) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001175 __ AddU4(0);
1176 } else {
1177 __ AddU4(klass->GetObjectSize()); // instance size
1178 }
1179
1180 __ AddU2(0); // empty const pool
1181
1182 // Static fields
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001183 if (overhead_size == 0) {
1184 __ AddU2(static_cast<uint16_t>(0));
Andreas Gampe3a913092015-01-10 00:26:17 -08001185 } else {
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001186 __ AddU2(static_cast<uint16_t>(num_static_fields + 1));
1187 __ AddStringId(LookupStringId(kClassOverheadName));
Andreas Gampe3a913092015-01-10 00:26:17 -08001188 __ AddU1(hprof_basic_object);
1189 __ AddClassStaticsId(klass);
1190
Mathieu Chartiera6d3a7e2015-06-03 16:51:09 -07001191 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001192 ArtField* f = klass->GetStaticField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001193
1194 size_t size;
1195 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1196 __ AddStringId(LookupStringId(f->GetName()));
1197 __ AddU1(t);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001198 switch (t) {
1199 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001200 __ AddU1(f->GetByte(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001201 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001202 case hprof_basic_boolean:
1203 __ AddU1(f->GetBoolean(klass));
1204 break;
1205 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001206 __ AddU2(f->GetChar(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001207 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001208 case hprof_basic_short:
1209 __ AddU2(f->GetShort(klass));
1210 break;
1211 case hprof_basic_float:
1212 case hprof_basic_int:
1213 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001214 __ AddU4(f->Get32(klass));
1215 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001216 case hprof_basic_double:
1217 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001218 __ AddU8(f->Get64(klass));
1219 break;
1220 default:
1221 LOG(FATAL) << "Unexpected size " << size;
1222 UNREACHABLE();
1223 }
1224 }
1225 }
1226
1227 // Instance fields for this class (no superclass fields)
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001228 int iFieldCount = klass->NumInstanceFields();
Jeff Hao848f70a2014-01-15 13:49:50 -08001229 if (klass->IsStringClass()) {
1230 __ AddU2((uint16_t)iFieldCount + 1);
1231 } else {
1232 __ AddU2((uint16_t)iFieldCount);
1233 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001234 for (int i = 0; i < iFieldCount; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001235 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001236 __ AddStringId(LookupStringId(f->GetName()));
1237 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), nullptr);
1238 __ AddU1(t);
1239 }
Jeff Hao848f70a2014-01-15 13:49:50 -08001240 // Add native value character array for strings.
1241 if (klass->IsStringClass()) {
1242 __ AddStringId(LookupStringId("value"));
1243 __ AddU1(hprof_basic_object);
1244 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001245}
1246
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001247void Hprof::DumpHeapArray(mirror::Array* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001248 uint32_t length = obj->GetLength();
1249
1250 if (obj->IsObjectArray()) {
1251 // obj is an object array.
1252 __ AddU1(HPROF_OBJECT_ARRAY_DUMP);
1253
1254 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001255 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001256 __ AddU4(length);
1257 __ AddClassId(LookupClassId(klass));
1258
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001259 // Dump the elements, which are always objects or null.
Andreas Gampe3a913092015-01-10 00:26:17 -08001260 __ AddIdList(obj->AsObjectArray<mirror::Object>());
1261 } else {
1262 size_t size;
1263 HprofBasicType t = SignatureToBasicTypeAndSize(
1264 Primitive::Descriptor(klass->GetComponentType()->GetPrimitiveType()), &size);
1265
1266 // obj is a primitive array.
1267 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1268
1269 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001270 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001271 __ AddU4(length);
1272 __ AddU1(t);
1273
1274 // Dump the raw, packed element values.
1275 if (size == 1) {
1276 __ AddU1List(reinterpret_cast<const uint8_t*>(obj->GetRawData(sizeof(uint8_t), 0)), length);
1277 } else if (size == 2) {
1278 __ AddU2List(reinterpret_cast<const uint16_t*>(obj->GetRawData(sizeof(uint16_t), 0)), length);
1279 } else if (size == 4) {
1280 __ AddU4List(reinterpret_cast<const uint32_t*>(obj->GetRawData(sizeof(uint32_t), 0)), length);
1281 } else if (size == 8) {
1282 __ AddU8List(reinterpret_cast<const uint64_t*>(obj->GetRawData(sizeof(uint64_t), 0)), length);
1283 }
1284 }
1285}
1286
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001287void Hprof::DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001288 // obj is an instance object.
1289 __ AddU1(HPROF_INSTANCE_DUMP);
1290 __ AddObjectId(obj);
Man Cao8c2ff642015-05-27 17:25:30 -07001291 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Andreas Gampe3a913092015-01-10 00:26:17 -08001292 __ AddClassId(LookupClassId(klass));
1293
1294 // Reserve some space for the length of the instance data, which we won't
1295 // know until we're done writing it.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001296 size_t size_patch_offset = output_->Length();
Andreas Gampe3a913092015-01-10 00:26:17 -08001297 __ AddU4(0x77777777);
1298
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001299 // What we will use for the string value if the object is a string.
1300 mirror::Object* string_value = nullptr;
1301
1302 // Write the instance data; fields for this class, followed by super class fields, and so on.
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001303 do {
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001304 const size_t instance_fields = klass->NumInstanceFields();
1305 for (size_t i = 0; i < instance_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001306 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001307 size_t size;
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001308 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001309 switch (t) {
1310 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001311 __ AddU1(f->GetByte(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001312 break;
1313 case hprof_basic_boolean:
1314 __ AddU1(f->GetBoolean(obj));
1315 break;
1316 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001317 __ AddU2(f->GetChar(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001318 break;
1319 case hprof_basic_short:
1320 __ AddU2(f->GetShort(obj));
1321 break;
1322 case hprof_basic_float:
1323 case hprof_basic_int:
1324 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001325 __ AddU4(f->Get32(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001326 break;
1327 case hprof_basic_double:
1328 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001329 __ AddU8(f->Get64(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001330 break;
Andreas Gampe3a913092015-01-10 00:26:17 -08001331 }
1332 }
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001333 // Add value field for String if necessary.
1334 if (klass->IsStringClass()) {
1335 mirror::String* s = obj->AsString();
1336 if (s->GetLength() == 0) {
1337 // If string is empty, use an object-aligned address within the string for the value.
1338 string_value = reinterpret_cast<mirror::Object*>(
1339 reinterpret_cast<uintptr_t>(s) + kObjectAlignment);
1340 } else {
1341 string_value = reinterpret_cast<mirror::Object*>(s->GetValue());
1342 }
1343 __ AddObjectId(string_value);
1344 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001345
1346 klass = klass->GetSuperClass();
Mathieu Chartier7c1f53e2015-06-03 10:51:13 -07001347 } while (klass != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -08001348
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001349 // Patch the instance field length.
1350 __ UpdateU4(size_patch_offset, output_->Length() - (size_patch_offset + 4));
1351
Jeff Hao848f70a2014-01-15 13:49:50 -08001352 // Output native value character array for strings.
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001353 CHECK_EQ(obj->IsString(), string_value != nullptr);
1354 if (string_value != nullptr) {
Jeff Hao848f70a2014-01-15 13:49:50 -08001355 mirror::String* s = obj->AsString();
Jeff Hao848f70a2014-01-15 13:49:50 -08001356 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
Mathieu Chartier07d7eab2015-06-23 15:45:15 -07001357 __ AddObjectId(string_value);
Man Cao8c2ff642015-05-27 17:25:30 -07001358 __ AddStackTraceSerialNumber(LookupStackTraceSerialNumber(obj));
Jeff Hao848f70a2014-01-15 13:49:50 -08001359 __ AddU4(s->GetLength());
1360 __ AddU1(hprof_basic_char);
1361 __ AddU2List(s->GetValue(), s->GetLength());
Jeff Hao848f70a2014-01-15 13:49:50 -08001362 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001363}
1364
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001365void Hprof::VisitRoot(mirror::Object* obj, const RootInfo& info) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001366 static const HprofHeapTag xlate[] = {
1367 HPROF_ROOT_UNKNOWN,
1368 HPROF_ROOT_JNI_GLOBAL,
1369 HPROF_ROOT_JNI_LOCAL,
1370 HPROF_ROOT_JAVA_FRAME,
1371 HPROF_ROOT_NATIVE_STACK,
1372 HPROF_ROOT_STICKY_CLASS,
1373 HPROF_ROOT_THREAD_BLOCK,
1374 HPROF_ROOT_MONITOR_USED,
1375 HPROF_ROOT_THREAD_OBJECT,
1376 HPROF_ROOT_INTERNED_STRING,
1377 HPROF_ROOT_FINALIZING,
1378 HPROF_ROOT_DEBUGGER,
1379 HPROF_ROOT_REFERENCE_CLEANUP,
1380 HPROF_ROOT_VM_INTERNAL,
1381 HPROF_ROOT_JNI_MONITOR,
1382 };
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001383 CHECK_LT(info.GetType(), sizeof(xlate) / sizeof(HprofHeapTag));
Andreas Gampe3a913092015-01-10 00:26:17 -08001384 if (obj == nullptr) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001385 return;
1386 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001387 MarkRootObject(obj, 0, xlate[info.GetType()], info.GetThreadId());
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001388}
1389
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001390// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1391// sent directly to DDMS.
1392// If "fd" is >= 0, the output will be written to that file descriptor.
1393// Otherwise, "filename" is used to create an output file.
1394void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001395 CHECK(filename != nullptr);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001396
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001397 Thread* self = Thread::Current();
1398 gc::Heap* heap = Runtime::Current()->GetHeap();
1399 if (heap->IsGcConcurrentAndMoving()) {
1400 // Need to take a heap dump while GC isn't running. See the
1401 // comment in Heap::VisitObjects().
1402 heap->IncrementDisableMovingGC(self);
1403 }
Mathieu Chartierbf44d422015-06-02 11:42:18 -07001404 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__, true /* long suspend */);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001405 Hprof hprof(filename, fd, direct_to_ddms);
1406 hprof.Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001407 Runtime::Current()->GetThreadList()->ResumeAll();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001408 if (heap->IsGcConcurrentAndMoving()) {
1409 heap->DecrementDisableMovingGC(self);
1410 }
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001411}
1412
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001413} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001414} // namespace art