blob: 1716d5e0e7b9d3d4b4d0c394b010a70a6fd4f9c0 [file] [log] [blame]
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Preparation and completion of hprof data generation. The output is
19 * written into two files and then combined. This is necessary because
20 * we generate some of the data (strings and classes) while we dump the
21 * heap, and some analysis tools require that the class and string data
22 * appear first.
23 */
24
25#include "hprof.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080026
Elliott Hughes622a6982012-06-08 17:58:54 -070027#include <cutils/open_memstream.h>
28#include <errno.h>
29#include <fcntl.h>
30#include <stdio.h>
31#include <string.h>
32#include <sys/time.h>
33#include <sys/uio.h>
34#include <time.h>
35#include <time.h>
36#include <unistd.h>
37
38#include <set>
39
Elliott Hughes07ed66b2012-12-12 18:34:25 -080040#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080041#include "base/stringprintf.h"
Elliott Hughes76160052012-12-12 16:31:20 -080042#include "base/unix_file/fd_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080043#include "class_linker.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080044#include "common_throws.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040045#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070046#include "dex_file-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070047#include "gc/accounting/heap_bitmap.h"
48#include "gc/heap.h"
49#include "gc/space/space.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070050#include "globals.h"
Mathieu Chartierad466ad2015-01-08 16:28:08 -080051#include "jdwp/jdwp.h"
52#include "jdwp/jdwp_priv.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070053#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "mirror/class.h"
55#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/object-inl.h"
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -070057#include "os.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070058#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070059#include "scoped_thread_state_change.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070060#include "thread_list.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040061
62namespace art {
63
64namespace hprof {
65
Mathieu Chartierad466ad2015-01-08 16:28:08 -080066static constexpr bool kDirectStream = true;
Jesse Wilson0c54ac12011-11-09 15:14:05 -050067
Andreas Gampe3a913092015-01-10 00:26:17 -080068static constexpr uint32_t kHprofTime = 0;
69static constexpr uint32_t kHprofNullStackTrace = 0;
70static constexpr uint32_t kHprofNullThread = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -070071
Andreas Gampe3a913092015-01-10 00:26:17 -080072static constexpr size_t kMaxObjectsPerSegment = 128;
73static constexpr size_t kMaxBytesPerSegment = 4096;
Elliott Hughes622a6982012-06-08 17:58:54 -070074
Andreas Gampe3a913092015-01-10 00:26:17 -080075// The static field-name for the synthetic object generated to account for class static overhead.
76static constexpr const char* kStaticOverheadName = "$staticOverhead";
Elliott Hughes622a6982012-06-08 17:58:54 -070077
78enum HprofTag {
79 HPROF_TAG_STRING = 0x01,
80 HPROF_TAG_LOAD_CLASS = 0x02,
81 HPROF_TAG_UNLOAD_CLASS = 0x03,
82 HPROF_TAG_STACK_FRAME = 0x04,
83 HPROF_TAG_STACK_TRACE = 0x05,
84 HPROF_TAG_ALLOC_SITES = 0x06,
85 HPROF_TAG_HEAP_SUMMARY = 0x07,
86 HPROF_TAG_START_THREAD = 0x0A,
87 HPROF_TAG_END_THREAD = 0x0B,
88 HPROF_TAG_HEAP_DUMP = 0x0C,
89 HPROF_TAG_HEAP_DUMP_SEGMENT = 0x1C,
90 HPROF_TAG_HEAP_DUMP_END = 0x2C,
91 HPROF_TAG_CPU_SAMPLES = 0x0D,
92 HPROF_TAG_CONTROL_SETTINGS = 0x0E,
93};
94
95// Values for the first byte of HEAP_DUMP and HEAP_DUMP_SEGMENT records:
96enum HprofHeapTag {
97 // Traditional.
98 HPROF_ROOT_UNKNOWN = 0xFF,
99 HPROF_ROOT_JNI_GLOBAL = 0x01,
100 HPROF_ROOT_JNI_LOCAL = 0x02,
101 HPROF_ROOT_JAVA_FRAME = 0x03,
102 HPROF_ROOT_NATIVE_STACK = 0x04,
103 HPROF_ROOT_STICKY_CLASS = 0x05,
104 HPROF_ROOT_THREAD_BLOCK = 0x06,
105 HPROF_ROOT_MONITOR_USED = 0x07,
106 HPROF_ROOT_THREAD_OBJECT = 0x08,
107 HPROF_CLASS_DUMP = 0x20,
108 HPROF_INSTANCE_DUMP = 0x21,
109 HPROF_OBJECT_ARRAY_DUMP = 0x22,
110 HPROF_PRIMITIVE_ARRAY_DUMP = 0x23,
111
112 // Android.
113 HPROF_HEAP_DUMP_INFO = 0xfe,
114 HPROF_ROOT_INTERNED_STRING = 0x89,
115 HPROF_ROOT_FINALIZING = 0x8a, // Obsolete.
116 HPROF_ROOT_DEBUGGER = 0x8b,
117 HPROF_ROOT_REFERENCE_CLEANUP = 0x8c, // Obsolete.
118 HPROF_ROOT_VM_INTERNAL = 0x8d,
119 HPROF_ROOT_JNI_MONITOR = 0x8e,
120 HPROF_UNREACHABLE = 0x90, // Obsolete.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700121 HPROF_PRIMITIVE_ARRAY_NODATA_DUMP = 0xc3, // Obsolete.
Elliott Hughes622a6982012-06-08 17:58:54 -0700122};
123
124enum HprofHeapId {
125 HPROF_HEAP_DEFAULT = 0,
126 HPROF_HEAP_ZYGOTE = 'Z',
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700127 HPROF_HEAP_APP = 'A',
128 HPROF_HEAP_IMAGE = 'I',
Elliott Hughes622a6982012-06-08 17:58:54 -0700129};
130
131enum HprofBasicType {
132 hprof_basic_object = 2,
133 hprof_basic_boolean = 4,
134 hprof_basic_char = 5,
135 hprof_basic_float = 6,
136 hprof_basic_double = 7,
137 hprof_basic_byte = 8,
138 hprof_basic_short = 9,
139 hprof_basic_int = 10,
140 hprof_basic_long = 11,
141};
142
Ian Rogersef7d42f2014-01-06 12:55:46 -0800143typedef uint32_t HprofStringId;
144typedef uint32_t HprofClassObjectId;
Elliott Hughes622a6982012-06-08 17:58:54 -0700145
Andreas Gampe3a913092015-01-10 00:26:17 -0800146class EndianOutput {
Elliott Hughes622a6982012-06-08 17:58:54 -0700147 public:
Andreas Gampe3a913092015-01-10 00:26:17 -0800148 EndianOutput() : length_(0), sum_length_(0), max_length_(0), started_(false) {}
149 virtual ~EndianOutput() {}
150
151 void StartNewRecord(uint8_t tag, uint32_t time) {
152 if (length_ > 0) {
153 EndRecord();
154 }
155 DCHECK_EQ(length_, 0U);
156 AddU1(tag);
157 AddU4(time);
158 AddU4(0xdeaddead); // Length, replaced on flush.
159 started_ = true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700160 }
161
Andreas Gampe3a913092015-01-10 00:26:17 -0800162 void EndRecord() {
163 // Replace length in header.
164 if (started_) {
165 UpdateU4(sizeof(uint8_t) + sizeof(uint32_t),
166 length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
167 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700168
Andreas Gampe3a913092015-01-10 00:26:17 -0800169 HandleEndRecord();
170
171 sum_length_ += length_;
172 max_length_ = std::max(max_length_, length_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700173 length_ = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -0800174 started_ = false;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700175 }
176
Andreas Gampe3a913092015-01-10 00:26:17 -0800177 void AddU1(uint8_t value) {
178 AddU1List(&value, 1);
179 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800180 void AddU2(uint16_t value) {
181 AddU2List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700182 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800183 void AddU4(uint32_t value) {
184 AddU4List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700185 }
186
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800187 void AddU8(uint64_t value) {
188 AddU8List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700189 }
190
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800191 void AddObjectId(const mirror::Object* value) {
192 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800193 }
194
195 // The ID for the synthetic object generated to account for class static overhead.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800196 void AddClassStaticsId(const mirror::Class* value) {
197 AddU4(1 | PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800198 }
199
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800200 void AddJniGlobalRefId(jobject value) {
201 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800202 }
203
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800204 void AddClassId(HprofClassObjectId value) {
205 AddU4(value);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800206 }
207
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800208 void AddStringId(HprofStringId value) {
209 AddU4(value);
Elliott Hughes622a6982012-06-08 17:58:54 -0700210 }
211
Andreas Gampe3a913092015-01-10 00:26:17 -0800212 void AddU1List(const uint8_t* values, size_t count) {
213 HandleU1List(values, count);
214 length_ += count;
215 }
216 void AddU2List(const uint16_t* values, size_t count) {
217 HandleU2List(values, count);
218 length_ += count * sizeof(uint16_t);
219 }
220 void AddU4List(const uint32_t* values, size_t count) {
221 HandleU4List(values, count);
222 length_ += count * sizeof(uint32_t);
223 }
224 virtual void UpdateU4(size_t offset ATTRIBUTE_UNUSED, uint32_t new_value ATTRIBUTE_UNUSED) {
225 DCHECK_LE(offset, length_ - 4);
226 }
227 void AddU8List(const uint64_t* values, size_t count) {
228 HandleU8List(values, count);
229 length_ += count * sizeof(uint64_t);
230 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700231
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800232 void AddIdList(mirror::ObjectArray<mirror::Object>* values)
Andreas Gampe3a913092015-01-10 00:26:17 -0800233 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800234 const int32_t length = values->GetLength();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800235 for (int32_t i = 0; i < length; ++i) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800236 AddObjectId(values->GetWithoutChecks(i));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800237 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700238 }
239
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800240 void AddUtf8String(const char* str) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700241 // The terminating NUL character is NOT written.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800242 AddU1List((const uint8_t*)str, strlen(str));
Elliott Hughes622a6982012-06-08 17:58:54 -0700243 }
244
Andreas Gampe3a913092015-01-10 00:26:17 -0800245 size_t Length() const {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700246 return length_;
247 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700248
Andreas Gampe3a913092015-01-10 00:26:17 -0800249 size_t SumLength() const {
250 return sum_length_;
Elliott Hughes622a6982012-06-08 17:58:54 -0700251 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700252
Andreas Gampe3a913092015-01-10 00:26:17 -0800253 size_t MaxLength() const {
254 return max_length_;
255 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700256
Andreas Gampe3a913092015-01-10 00:26:17 -0800257 protected:
258 virtual void HandleU1List(const uint8_t* values ATTRIBUTE_UNUSED,
259 size_t count ATTRIBUTE_UNUSED) {
260 }
261 virtual void HandleU2List(const uint16_t* values ATTRIBUTE_UNUSED,
262 size_t count ATTRIBUTE_UNUSED) {
263 }
264 virtual void HandleU4List(const uint32_t* values ATTRIBUTE_UNUSED,
265 size_t count ATTRIBUTE_UNUSED) {
266 }
267 virtual void HandleU8List(const uint64_t* values ATTRIBUTE_UNUSED,
268 size_t count ATTRIBUTE_UNUSED) {
269 }
270 virtual void HandleEndRecord() {
271 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700272
Andreas Gampe3a913092015-01-10 00:26:17 -0800273 size_t length_; // Current record size.
274 size_t sum_length_; // Size of all data.
275 size_t max_length_; // Maximum seen length.
276 bool started_; // Was StartRecord called?
Elliott Hughes622a6982012-06-08 17:58:54 -0700277};
278
Andreas Gampe3a913092015-01-10 00:26:17 -0800279// This keeps things buffered until flushed.
280class EndianOutputBuffered : public EndianOutput {
281 public:
282 explicit EndianOutputBuffered(size_t reserve_size) {
283 buffer_.reserve(reserve_size);
284 }
285 virtual ~EndianOutputBuffered() {}
286
287 void UpdateU4(size_t offset, uint32_t new_value) OVERRIDE {
288 DCHECK_LE(offset, length_ - 4);
289 buffer_[offset + 0] = static_cast<uint8_t>((new_value >> 24) & 0xFF);
290 buffer_[offset + 1] = static_cast<uint8_t>((new_value >> 16) & 0xFF);
291 buffer_[offset + 2] = static_cast<uint8_t>((new_value >> 8) & 0xFF);
292 buffer_[offset + 3] = static_cast<uint8_t>((new_value >> 0) & 0xFF);
293 }
294
295 protected:
296 void HandleU1List(const uint8_t* values, size_t count) OVERRIDE {
297 DCHECK_EQ(length_, buffer_.size());
298 buffer_.insert(buffer_.end(), values, values + count);
299 }
300
301 void HandleU2List(const uint16_t* values, size_t count) OVERRIDE {
302 DCHECK_EQ(length_, buffer_.size());
303 for (size_t i = 0; i < count; ++i) {
304 uint16_t value = *values;
305 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
306 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
307 values++;
308 }
309 }
310
311 void HandleU4List(const uint32_t* values, size_t count) OVERRIDE {
312 DCHECK_EQ(length_, buffer_.size());
313 for (size_t i = 0; i < count; ++i) {
314 uint32_t value = *values;
315 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
316 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
317 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
318 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
319 values++;
320 }
321 }
322
323 void HandleU8List(const uint64_t* values, size_t count) OVERRIDE {
324 DCHECK_EQ(length_, buffer_.size());
325 for (size_t i = 0; i < count; ++i) {
326 uint64_t value = *values;
327 buffer_.push_back(static_cast<uint8_t>((value >> 56) & 0xFF));
328 buffer_.push_back(static_cast<uint8_t>((value >> 48) & 0xFF));
329 buffer_.push_back(static_cast<uint8_t>((value >> 40) & 0xFF));
330 buffer_.push_back(static_cast<uint8_t>((value >> 32) & 0xFF));
331 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
332 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
333 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
334 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
335 values++;
336 }
337 }
338
339 void HandleEndRecord() OVERRIDE {
340 DCHECK_EQ(buffer_.size(), length_);
341 if (kIsDebugBuild && started_) {
342 uint32_t stored_length =
343 static_cast<uint32_t>(buffer_[5]) << 24 |
344 static_cast<uint32_t>(buffer_[6]) << 16 |
345 static_cast<uint32_t>(buffer_[7]) << 8 |
346 static_cast<uint32_t>(buffer_[8]);
347 DCHECK_EQ(stored_length, length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
348 }
349 HandleFlush(buffer_.data(), length_);
350 buffer_.clear();
351 }
352
353 virtual void HandleFlush(const uint8_t* buffer ATTRIBUTE_UNUSED, size_t length ATTRIBUTE_UNUSED) {
354 }
355
356 std::vector<uint8_t> buffer_;
357};
358
359class FileEndianOutput FINAL : public EndianOutputBuffered {
360 public:
361 FileEndianOutput(File* fp, size_t reserved_size)
362 : EndianOutputBuffered(reserved_size), fp_(fp), errors_(false) {
363 DCHECK(fp != nullptr);
364 }
365 ~FileEndianOutput() {
366 }
367
368 bool Errors() {
369 return errors_;
370 }
371
372 protected:
373 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
374 if (!errors_) {
375 errors_ = !fp_->WriteFully(buffer, length);
376 }
377 }
378
379 private:
380 File* fp_;
381 bool errors_;
382};
383
384class NetStateEndianOutput FINAL : public EndianOutputBuffered {
385 public:
386 NetStateEndianOutput(JDWP::JdwpNetStateBase* net_state, size_t reserved_size)
387 : EndianOutputBuffered(reserved_size), net_state_(net_state) {
388 DCHECK(net_state != nullptr);
389 }
390 ~NetStateEndianOutput() {}
391
392 protected:
393 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
394 std::vector<iovec> iov;
395 iov.push_back(iovec());
396 iov[0].iov_base = const_cast<void*>(reinterpret_cast<const void*>(buffer));
397 iov[0].iov_len = length;
398 net_state_->WriteBufferedPacketLocked(iov);
399 }
400
401 private:
402 JDWP::JdwpNetStateBase* net_state_;
403};
404
405#define __ output->
406
Elliott Hughes622a6982012-06-08 17:58:54 -0700407class Hprof {
408 public:
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700409 Hprof(const char* output_filename, int fd, bool direct_to_ddms)
410 : filename_(output_filename),
411 fd_(fd),
412 direct_to_ddms_(direct_to_ddms),
413 start_ns_(NanoTime()),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700414 current_heap_(HPROF_HEAP_DEFAULT),
415 objects_in_segment_(0),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700416 next_string_id_(0x400000) {
417 LOG(INFO) << "hprof: heap dump \"" << filename_ << "\" starting...";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500418 }
419
Andreas Gampe3a913092015-01-10 00:26:17 -0800420 void Dump()
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800421 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800422 LOCKS_EXCLUDED(Locks::heap_bitmap_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800423 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
424 // First pass to measure the size of the dump.
425 size_t overall_size;
426 size_t max_length;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800427 {
Andreas Gampe3a913092015-01-10 00:26:17 -0800428 EndianOutput count_output;
429 ProcessHeap(&count_output, false);
430 overall_size = count_output.SumLength();
431 max_length = count_output.MaxLength();
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800432 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700433
Andreas Gampe3a913092015-01-10 00:26:17 -0800434 bool okay;
435 if (direct_to_ddms_) {
436 if (kDirectStream) {
437 okay = DumpToDdmsDirect(overall_size, max_length, CHUNK_TYPE("HPDS"));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700438 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800439 okay = DumpToDdmsBuffered(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700440 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800441 } else {
442 okay = DumpToFile(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700443 }
444
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700445 if (okay) {
446 uint64_t duration = NanoTime() - start_ns_;
Ian Rogers50b35e22012-10-04 10:09:15 -0700447 LOG(INFO) << "hprof: heap dump completed ("
Andreas Gampe3a913092015-01-10 00:26:17 -0800448 << PrettySize(RoundUp(overall_size, 1024))
Ian Rogers50b35e22012-10-04 10:09:15 -0700449 << ") in " << PrettyDuration(duration);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700450 }
451 }
452
453 private:
Andreas Gampe3a913092015-01-10 00:26:17 -0800454 struct Env {
455 Hprof* hprof;
456 EndianOutput* output;
457 };
458
Mathieu Chartier815873e2014-02-13 18:02:13 -0800459 static void RootVisitor(mirror::Object** obj, void* arg, uint32_t thread_id, RootType root_type)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700460 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800461 DCHECK(arg != nullptr);
462 DCHECK(obj != nullptr);
463 DCHECK(*obj != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800464 Env* env = reinterpret_cast<Env*>(arg);
465 env->hprof->VisitRoot(*obj, thread_id, root_type, env->output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700466 }
467
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800468 static void VisitObjectCallback(mirror::Object* obj, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700469 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800470 DCHECK(obj != nullptr);
471 DCHECK(arg != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800472 Env* env = reinterpret_cast<Env*>(arg);
473 env->hprof->DumpHeapObject(obj, env->output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700474 }
475
Andreas Gampe3a913092015-01-10 00:26:17 -0800476 void DumpHeapObject(mirror::Object* obj, EndianOutput* output)
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800477 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700478
Andreas Gampe3a913092015-01-10 00:26:17 -0800479 void DumpHeapClass(mirror::Class* klass, EndianOutput* output)
480 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700481
Andreas Gampe3a913092015-01-10 00:26:17 -0800482 void DumpHeapArray(mirror::Array* obj, mirror::Class* klass, EndianOutput* output)
483 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
484
485 void DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass, EndianOutput* output)
486 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
487
488 void ProcessHeap(EndianOutput* output, bool header_first)
489 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
490 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
491 // Reset current heap and object count.
492 current_heap_ = HPROF_HEAP_DEFAULT;
493 objects_in_segment_ = 0;
494
495 if (header_first) {
496 ProcessHeader(output);
497 ProcessBody(output);
498 } else {
499 ProcessBody(output);
500 ProcessHeader(output);
501 }
502 }
503
504 void ProcessBody(EndianOutput* output) EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
505 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
506 Runtime* runtime = Runtime::Current();
507 // Walk the roots and the heap.
508 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
509
510 Env env = { this, output };
511 runtime->VisitRoots(RootVisitor, &env);
512 runtime->GetHeap()->VisitObjects(VisitObjectCallback, &env);
513
514 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_END, kHprofTime);
515 output->EndRecord();
516 }
517
518 void ProcessHeader(EndianOutput* output) EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
519 // Write the header.
520 WriteFixedHeader(output);
521 // Write the string and class tables, and any stack traces, to the header.
522 // (jhat requires that these appear before any of the data in the body that refers to them.)
523 WriteStringTable(output);
524 WriteClassTable(output);
525 WriteStackTraces(output);
526 output->EndRecord();
527 }
528
529 void WriteClassTable(EndianOutput* output) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700530 uint32_t nextSerialNumber = 1;
531
Ian Rogersef7d42f2014-01-06 12:55:46 -0800532 for (mirror::Class* c : classes_) {
533 CHECK(c != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800534 output->StartNewRecord(HPROF_TAG_LOAD_CLASS, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700535 // LOAD CLASS format:
536 // U4: class serial number (always > 0)
537 // ID: class object ID. We use the address of the class object structure as its ID.
538 // U4: stack trace serial number
539 // ID: class name string ID
Andreas Gampe3a913092015-01-10 00:26:17 -0800540 __ AddU4(nextSerialNumber++);
541 __ AddObjectId(c);
542 __ AddU4(kHprofNullStackTrace);
543 __ AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700544 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700545 }
546
Andreas Gampe3a913092015-01-10 00:26:17 -0800547 void WriteStringTable(EndianOutput* output) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800548 for (const std::pair<std::string, HprofStringId>& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800549 const std::string& string = p.first;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800550 const size_t id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700551
Andreas Gampe3a913092015-01-10 00:26:17 -0800552 output->StartNewRecord(HPROF_TAG_STRING, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700553
554 // STRING format:
555 // ID: ID for this string
556 // U1*: UTF8 characters for string (NOT NULL terminated)
557 // (the record format encodes the length)
Andreas Gampe3a913092015-01-10 00:26:17 -0800558 __ AddU4(id);
559 __ AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700560 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700561 }
562
Andreas Gampe3a913092015-01-10 00:26:17 -0800563 void StartNewHeapDumpSegment(EndianOutput* output) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700564 // This flushes the old segment and starts a new one.
Andreas Gampe3a913092015-01-10 00:26:17 -0800565 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700566 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700567 // Starting a new HEAP_DUMP resets the heap to default.
568 current_heap_ = HPROF_HEAP_DEFAULT;
569 }
570
Andreas Gampe3a913092015-01-10 00:26:17 -0800571 void CheckHeapSegmentConstraints(EndianOutput* output) {
572 if (objects_in_segment_ >= kMaxObjectsPerSegment || output->Length() >= kMaxBytesPerSegment) {
573 StartNewHeapDumpSegment(output);
574 }
575 }
576
577 void VisitRoot(const mirror::Object* obj, uint32_t thread_id, RootType type, EndianOutput* output)
578 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
579 void MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
580 uint32_t thread_serial, EndianOutput* output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700581
Ian Rogersef7d42f2014-01-06 12:55:46 -0800582 HprofClassObjectId LookupClassId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800583 if (c != nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800584 auto result = classes_.insert(c);
585 const mirror::Class* present = *result.first;
586 CHECK_EQ(present, c);
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800587 // Make sure that we've assigned a string ID for this class' name
588 LookupClassNameId(c);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800589 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800590 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700591 }
592
Ian Rogersef7d42f2014-01-06 12:55:46 -0800593 HprofStringId LookupStringId(mirror::String* string) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700594 return LookupStringId(string->ToModifiedUtf8());
595 }
596
597 HprofStringId LookupStringId(const char* string) {
598 return LookupStringId(std::string(string));
599 }
600
601 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800602 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700603 if (it != strings_.end()) {
604 return it->second;
605 }
606 HprofStringId id = next_string_id_++;
607 strings_.Put(string, id);
608 return id;
609 }
610
Ian Rogersef7d42f2014-01-06 12:55:46 -0800611 HprofStringId LookupClassNameId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700612 return LookupStringId(PrettyDescriptor(c));
613 }
614
Andreas Gampe3a913092015-01-10 00:26:17 -0800615 void WriteFixedHeader(EndianOutput* output) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500616 // Write the file header.
617 // U1: NUL-terminated magic string.
Andreas Gampe3a913092015-01-10 00:26:17 -0800618 const char magic[] = "JAVA PROFILE 1.0.3";
619 __ AddU1List(reinterpret_cast<const uint8_t*>(magic), sizeof(magic));
620
Calin Juravle32805172014-07-04 16:24:03 +0100621 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
622 // as uint32_t.
623 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800624 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
625 "Unexpected HeapReference size");
Andreas Gampe3a913092015-01-10 00:26:17 -0800626 __ AddU4(sizeof(uint32_t));
627
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500628 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700629 timeval now;
Andreas Gampe3a913092015-01-10 00:26:17 -0800630 const uint64_t nowMs = (gettimeofday(&now, nullptr) < 0) ? 0 :
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800631 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Andreas Gampe3a913092015-01-10 00:26:17 -0800632 // TODO: It seems it would be correct to use U8.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500633 // U4: high word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800634 __ AddU4(static_cast<uint32_t>(nowMs >> 32));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500635 // U4: low word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800636 __ AddU4(static_cast<uint32_t>(nowMs & 0xFFFFFFFF));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500637 }
638
Andreas Gampe3a913092015-01-10 00:26:17 -0800639 void WriteStackTraces(EndianOutput* output) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700640 // Write a dummy stack trace record so the analysis tools don't freak out.
Andreas Gampe3a913092015-01-10 00:26:17 -0800641 output->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
642 __ AddU4(kHprofNullStackTrace);
643 __ AddU4(kHprofNullThread);
644 __ AddU4(0); // no frames
645 }
646
647 bool DumpToDdmsBuffered(size_t overall_size ATTRIBUTE_UNUSED, size_t max_length ATTRIBUTE_UNUSED)
648 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
649 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
650 LOG(FATAL) << "Unimplemented";
651 UNREACHABLE();
652 // // Send the data off to DDMS.
653 // iovec iov[2];
654 // iov[0].iov_base = header_data_ptr_;
655 // iov[0].iov_len = header_data_size_;
656 // iov[1].iov_base = body_data_ptr_;
657 // iov[1].iov_len = body_data_size_;
658 // Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
659 }
660
661 bool DumpToFile(size_t overall_size, size_t max_length)
662 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
663 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
664 // Where exactly are we writing to?
665 int out_fd;
666 if (fd_ >= 0) {
667 out_fd = dup(fd_);
668 if (out_fd < 0) {
669 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
670 return false;
671 }
672 } else {
673 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
674 if (out_fd < 0) {
675 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
676 strerror(errno));
677 return false;
678 }
679 }
680
681 std::unique_ptr<File> file(new File(out_fd, filename_, true));
682 bool okay;
683 {
684 FileEndianOutput file_output(file.get(), max_length);
685 ProcessHeap(&file_output, true);
686 okay = !file_output.Errors();
687
688 if (okay) {
689 // Check for expected size.
690 CHECK_EQ(file_output.SumLength(), overall_size);
691 }
692 }
693
694 if (okay) {
695 okay = file->FlushCloseOrErase() == 0;
696 } else {
697 file->Erase();
698 }
699 if (!okay) {
700 std::string msg(StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
701 filename_.c_str(), strerror(errno)));
702 ThrowRuntimeException("%s", msg.c_str());
703 LOG(ERROR) << msg;
704 }
705
706 return okay;
707 }
708
709 bool DumpToDdmsDirect(size_t overall_size, size_t max_length, uint32_t chunk_type)
710 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
711 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
712 CHECK(direct_to_ddms_);
713 JDWP::JdwpState* state = Dbg::GetJdwpState();
714 CHECK(state != nullptr);
715 JDWP::JdwpNetStateBase* net_state = state->netState;
716 CHECK(net_state != nullptr);
717
718 // Hold the socket lock for the whole time since we want this to be atomic.
719 MutexLock mu(Thread::Current(), *net_state->GetSocketLock());
720
721 // Prepare the Ddms chunk.
722 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
723 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
724 state->SetupChunkHeader(chunk_type, overall_size, kChunkHeaderSize, chunk_header);
725
726 // Prepare the output and send the chunk header.
727 NetStateEndianOutput net_output(net_state, max_length);
728 net_output.AddU1List(chunk_header, kChunkHeaderSize);
729
730 // Write the dump.
731 ProcessHeap(&net_output, true);
732
733 // Check for expected size.
734 CHECK_EQ(net_output.SumLength(), overall_size + kChunkHeaderSize);
735
736 return true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700737 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500738
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700739 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
740 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
741 // only be used for debug messages.
742 std::string filename_;
743 int fd_;
744 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500745
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700746 uint64_t start_ns_;
747
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700748 HprofHeapId current_heap_; // Which heap we're currently dumping.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700749 size_t objects_in_segment_;
750
Ian Rogersef7d42f2014-01-06 12:55:46 -0800751 std::set<mirror::Class*> classes_;
752 HprofStringId next_string_id_;
753 SafeMap<std::string, HprofStringId> strings_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700754
755 DISALLOW_COPY_AND_ASSIGN(Hprof);
756};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500757
Andreas Gampe3a913092015-01-10 00:26:17 -0800758static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* size_out) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500759 char c = sig[0];
760 HprofBasicType ret;
761 size_t size;
762
763 switch (c) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800764 case '[':
765 case 'L':
766 ret = hprof_basic_object;
767 size = 4;
768 break;
769 case 'Z':
770 ret = hprof_basic_boolean;
771 size = 1;
772 break;
773 case 'C':
774 ret = hprof_basic_char;
775 size = 2;
776 break;
777 case 'F':
778 ret = hprof_basic_float;
779 size = 4;
780 break;
781 case 'D':
782 ret = hprof_basic_double;
783 size = 8;
784 break;
785 case 'B':
786 ret = hprof_basic_byte;
787 size = 1;
788 break;
789 case 'S':
790 ret = hprof_basic_short;
791 size = 2;
792 break;
793 case 'I':
794 ret = hprof_basic_int;
795 size = 4;
796 break;
797 case 'J':
798 ret = hprof_basic_long;
799 size = 8;
800 break;
801 default:
802 LOG(FATAL) << "UNREACHABLE";
803 UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500804 }
805
Andreas Gampe3a913092015-01-10 00:26:17 -0800806 if (size_out != nullptr) {
807 *size_out = size;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500808 }
809
810 return ret;
811}
812
813// Always called when marking objects, but only does
814// something when ctx->gc_scan_state_ is non-zero, which is usually
815// only true when marking the root set or unreachable
816// objects. Used to add rootset references to obj.
Andreas Gampe3a913092015-01-10 00:26:17 -0800817void Hprof::MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
818 uint32_t thread_serial, EndianOutput* output) {
819 if (heap_tag == 0) {
820 return;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500821 }
822
Andreas Gampe3a913092015-01-10 00:26:17 -0800823 CheckHeapSegmentConstraints(output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500824
Andreas Gampe3a913092015-01-10 00:26:17 -0800825 switch (heap_tag) {
826 // ID: object ID
827 case HPROF_ROOT_UNKNOWN:
828 case HPROF_ROOT_STICKY_CLASS:
829 case HPROF_ROOT_MONITOR_USED:
830 case HPROF_ROOT_INTERNED_STRING:
831 case HPROF_ROOT_DEBUGGER:
832 case HPROF_ROOT_VM_INTERNAL:
833 __ AddU1(heap_tag);
834 __ AddObjectId(obj);
835 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500836
Andreas Gampe3a913092015-01-10 00:26:17 -0800837 // ID: object ID
838 // ID: JNI global ref ID
839 case HPROF_ROOT_JNI_GLOBAL:
840 __ AddU1(heap_tag);
841 __ AddObjectId(obj);
842 __ AddJniGlobalRefId(jni_obj);
843 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500844
Andreas Gampe3a913092015-01-10 00:26:17 -0800845 // ID: object ID
846 // U4: thread serial number
847 // U4: frame number in stack trace (-1 for empty)
848 case HPROF_ROOT_JNI_LOCAL:
849 case HPROF_ROOT_JNI_MONITOR:
850 case HPROF_ROOT_JAVA_FRAME:
851 __ AddU1(heap_tag);
852 __ AddObjectId(obj);
853 __ AddU4(thread_serial);
854 __ AddU4((uint32_t)-1);
855 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500856
Andreas Gampe3a913092015-01-10 00:26:17 -0800857 // ID: object ID
858 // U4: thread serial number
859 case HPROF_ROOT_NATIVE_STACK:
860 case HPROF_ROOT_THREAD_BLOCK:
861 __ AddU1(heap_tag);
862 __ AddObjectId(obj);
863 __ AddU4(thread_serial);
864 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500865
Andreas Gampe3a913092015-01-10 00:26:17 -0800866 // ID: thread object ID
867 // U4: thread serial number
868 // U4: stack trace serial number
869 case HPROF_ROOT_THREAD_OBJECT:
870 __ AddU1(heap_tag);
871 __ AddObjectId(obj);
872 __ AddU4(thread_serial);
873 __ AddU4((uint32_t)-1); // xxx
874 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500875
Andreas Gampe3a913092015-01-10 00:26:17 -0800876 case HPROF_CLASS_DUMP:
877 case HPROF_INSTANCE_DUMP:
878 case HPROF_OBJECT_ARRAY_DUMP:
879 case HPROF_PRIMITIVE_ARRAY_DUMP:
880 case HPROF_HEAP_DUMP_INFO:
881 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
882 // Ignored.
883 break;
Elliott Hughes73e66f72012-05-09 09:34:45 -0700884
Andreas Gampe3a913092015-01-10 00:26:17 -0800885 case HPROF_ROOT_FINALIZING:
886 case HPROF_ROOT_REFERENCE_CLEANUP:
887 case HPROF_UNREACHABLE:
888 LOG(FATAL) << "obsolete tag " << static_cast<int>(heap_tag);
889 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500890 }
891
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700892 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500893}
894
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800895static int StackTraceSerialNumber(const mirror::Object* /*obj*/) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800896 return kHprofNullStackTrace;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500897}
898
Andreas Gampe3a913092015-01-10 00:26:17 -0800899void Hprof::DumpHeapObject(mirror::Object* obj, EndianOutput* output) {
900 // Ignore classes that are retired.
901 if (obj->IsClass() && obj->AsClass()->IsRetired()) {
902 return;
903 }
904
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700905 gc::space::ContinuousSpace* space =
906 Runtime::Current()->GetHeap()->FindContinuousSpaceFromObject(obj, true);
907 HprofHeapId heap_type = HPROF_HEAP_APP;
908 if (space != nullptr) {
909 if (space->IsZygoteSpace()) {
910 heap_type = HPROF_HEAP_ZYGOTE;
911 } else if (space->IsImageSpace()) {
912 heap_type = HPROF_HEAP_IMAGE;
913 }
914 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800915 CheckHeapSegmentConstraints(output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500916
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700917 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500918 HprofStringId nameId;
919
920 // This object is in a different heap than the current one.
921 // Emit a HEAP_DUMP_INFO tag to change heaps.
Andreas Gampe3a913092015-01-10 00:26:17 -0800922 __ AddU1(HPROF_HEAP_DUMP_INFO);
923 __ AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700924 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500925 case HPROF_HEAP_APP:
926 nameId = LookupStringId("app");
927 break;
928 case HPROF_HEAP_ZYGOTE:
929 nameId = LookupStringId("zygote");
930 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700931 case HPROF_HEAP_IMAGE:
932 nameId = LookupStringId("image");
933 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500934 default:
935 // Internal error
936 LOG(ERROR) << "Unexpected desiredHeap";
937 nameId = LookupStringId("<ILLEGAL>");
938 break;
939 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800940 __ AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700941 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500942 }
943
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800944 mirror::Class* c = obj->GetClass();
Andreas Gampe3a913092015-01-10 00:26:17 -0800945 if (c == nullptr) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500946 // This object will bother HprofReader, because it has a NULL
947 // class, so just don't dump it. It could be
948 // gDvm.unlinkedJavaLangClass or it could be an object just
949 // allocated which hasn't been initialized yet.
950 } else {
951 if (obj->IsClass()) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800952 DumpHeapClass(obj->AsClass(), output);
Elliott Hughese84278b2012-03-22 10:06:53 -0700953 } else if (c->IsArrayClass()) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800954 DumpHeapArray(obj->AsArray(), c, output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500955 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800956 DumpHeapInstanceObject(obj, c, output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500957 }
958 }
959
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700960 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500961}
962
Andreas Gampe3a913092015-01-10 00:26:17 -0800963void Hprof::DumpHeapClass(mirror::Class* klass, EndianOutput* output) {
964 size_t sFieldCount = klass->NumStaticFields();
965 if (sFieldCount != 0) {
966 int byteLength = sFieldCount * sizeof(JValue); // TODO bogus; fields are packed
967 // Create a byte array to reflect the allocation of the
968 // StaticField array at the end of this class.
969 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
970 __ AddClassStaticsId(klass);
971 __ AddU4(StackTraceSerialNumber(klass));
972 __ AddU4(byteLength);
973 __ AddU1(hprof_basic_byte);
974 for (int i = 0; i < byteLength; ++i) {
975 __ AddU1(0);
976 }
977 }
978
979 __ AddU1(HPROF_CLASS_DUMP);
980 __ AddClassId(LookupClassId(klass));
981 __ AddU4(StackTraceSerialNumber(klass));
982 __ AddClassId(LookupClassId(klass->GetSuperClass()));
983 __ AddObjectId(klass->GetClassLoader());
984 __ AddObjectId(nullptr); // no signer
985 __ AddObjectId(nullptr); // no prot domain
986 __ AddObjectId(nullptr); // reserved
987 __ AddObjectId(nullptr); // reserved
988 if (klass->IsClassClass()) {
989 // ClassObjects have their static fields appended, so aren't all the same size.
990 // But they're at least this size.
991 __ AddU4(sizeof(mirror::Class)); // instance size
992 } else if (klass->IsArrayClass() || klass->IsPrimitive()) {
993 __ AddU4(0);
994 } else {
995 __ AddU4(klass->GetObjectSize()); // instance size
996 }
997
998 __ AddU2(0); // empty const pool
999
1000 // Static fields
1001 if (sFieldCount == 0) {
1002 __ AddU2((uint16_t)0);
1003 } else {
1004 __ AddU2((uint16_t)(sFieldCount+1));
1005 __ AddStringId(LookupStringId(kStaticOverheadName));
1006 __ AddU1(hprof_basic_object);
1007 __ AddClassStaticsId(klass);
1008
1009 for (size_t i = 0; i < sFieldCount; ++i) {
1010 mirror::ArtField* f = klass->GetStaticField(i);
1011
1012 size_t size;
1013 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1014 __ AddStringId(LookupStringId(f->GetName()));
1015 __ AddU1(t);
1016 switch (size) {
1017 case 1:
1018 __ AddU1(static_cast<uint8_t>(f->Get32(klass)));
1019 break;
1020 case 2:
1021 __ AddU2(static_cast<uint16_t>(f->Get32(klass)));
1022 break;
1023 case 4:
1024 __ AddU4(f->Get32(klass));
1025 break;
1026 case 8:
1027 __ AddU8(f->Get64(klass));
1028 break;
1029 default:
1030 LOG(FATAL) << "Unexpected size " << size;
1031 UNREACHABLE();
1032 }
1033 }
1034 }
1035
1036 // Instance fields for this class (no superclass fields)
1037 int iFieldCount = klass->IsObjectClass() ? 0 : klass->NumInstanceFields();
1038 __ AddU2((uint16_t)iFieldCount);
1039 for (int i = 0; i < iFieldCount; ++i) {
1040 mirror::ArtField* f = klass->GetInstanceField(i);
1041 __ AddStringId(LookupStringId(f->GetName()));
1042 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), nullptr);
1043 __ AddU1(t);
1044 }
1045}
1046
1047void Hprof::DumpHeapArray(mirror::Array* obj, mirror::Class* klass, EndianOutput* output) {
1048 uint32_t length = obj->GetLength();
1049
1050 if (obj->IsObjectArray()) {
1051 // obj is an object array.
1052 __ AddU1(HPROF_OBJECT_ARRAY_DUMP);
1053
1054 __ AddObjectId(obj);
1055 __ AddU4(StackTraceSerialNumber(obj));
1056 __ AddU4(length);
1057 __ AddClassId(LookupClassId(klass));
1058
1059 // Dump the elements, which are always objects or NULL.
1060 __ AddIdList(obj->AsObjectArray<mirror::Object>());
1061 } else {
1062 size_t size;
1063 HprofBasicType t = SignatureToBasicTypeAndSize(
1064 Primitive::Descriptor(klass->GetComponentType()->GetPrimitiveType()), &size);
1065
1066 // obj is a primitive array.
1067 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1068
1069 __ AddObjectId(obj);
1070 __ AddU4(StackTraceSerialNumber(obj));
1071 __ AddU4(length);
1072 __ AddU1(t);
1073
1074 // Dump the raw, packed element values.
1075 if (size == 1) {
1076 __ AddU1List(reinterpret_cast<const uint8_t*>(obj->GetRawData(sizeof(uint8_t), 0)), length);
1077 } else if (size == 2) {
1078 __ AddU2List(reinterpret_cast<const uint16_t*>(obj->GetRawData(sizeof(uint16_t), 0)), length);
1079 } else if (size == 4) {
1080 __ AddU4List(reinterpret_cast<const uint32_t*>(obj->GetRawData(sizeof(uint32_t), 0)), length);
1081 } else if (size == 8) {
1082 __ AddU8List(reinterpret_cast<const uint64_t*>(obj->GetRawData(sizeof(uint64_t), 0)), length);
1083 }
1084 }
1085}
1086
1087void Hprof::DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass,
1088 EndianOutput* output) {
1089 // obj is an instance object.
1090 __ AddU1(HPROF_INSTANCE_DUMP);
1091 __ AddObjectId(obj);
1092 __ AddU4(StackTraceSerialNumber(obj));
1093 __ AddClassId(LookupClassId(klass));
1094
1095 // Reserve some space for the length of the instance data, which we won't
1096 // know until we're done writing it.
1097 size_t size_patch_offset = output->Length();
1098 __ AddU4(0x77777777);
1099
1100 // Write the instance data; fields for this class, followed by super class fields,
1101 // and so on. Don't write the klass or monitor fields of Object.class.
1102 while (!klass->IsObjectClass()) {
1103 int ifieldCount = klass->NumInstanceFields();
1104 for (int i = 0; i < ifieldCount; ++i) {
1105 mirror::ArtField* f = klass->GetInstanceField(i);
1106 size_t size;
1107 SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1108 if (size == 1) {
1109 __ AddU1(f->Get32(obj));
1110 } else if (size == 2) {
1111 __ AddU2(f->Get32(obj));
1112 } else if (size == 4) {
1113 __ AddU4(f->Get32(obj));
1114 } else {
1115 CHECK_EQ(size, 8U);
1116 __ AddU8(f->Get64(obj));
1117 }
1118 }
1119
1120 klass = klass->GetSuperClass();
1121 }
1122
1123 // Patch the instance field length.
1124 __ UpdateU4(size_patch_offset, output->Length() - (size_patch_offset + 4));
1125}
1126
1127void Hprof::VisitRoot(const mirror::Object* obj, uint32_t thread_id, RootType type,
1128 EndianOutput* output) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001129 static const HprofHeapTag xlate[] = {
1130 HPROF_ROOT_UNKNOWN,
1131 HPROF_ROOT_JNI_GLOBAL,
1132 HPROF_ROOT_JNI_LOCAL,
1133 HPROF_ROOT_JAVA_FRAME,
1134 HPROF_ROOT_NATIVE_STACK,
1135 HPROF_ROOT_STICKY_CLASS,
1136 HPROF_ROOT_THREAD_BLOCK,
1137 HPROF_ROOT_MONITOR_USED,
1138 HPROF_ROOT_THREAD_OBJECT,
1139 HPROF_ROOT_INTERNED_STRING,
1140 HPROF_ROOT_FINALIZING,
1141 HPROF_ROOT_DEBUGGER,
1142 HPROF_ROOT_REFERENCE_CLEANUP,
1143 HPROF_ROOT_VM_INTERNAL,
1144 HPROF_ROOT_JNI_MONITOR,
1145 };
Jesse Wilson0b075f12011-11-09 10:57:41 -05001146 CHECK_LT(type, sizeof(xlate) / sizeof(HprofHeapTag));
Andreas Gampe3a913092015-01-10 00:26:17 -08001147 if (obj == nullptr) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001148 return;
1149 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001150 MarkRootObject(obj, 0, xlate[type], thread_id, output);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001151}
1152
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001153// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1154// sent directly to DDMS.
1155// If "fd" is >= 0, the output will be written to that file descriptor.
1156// Otherwise, "filename" is used to create an output file.
1157void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001158 CHECK(filename != nullptr);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001159
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001160 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001161 Hprof hprof(filename, fd, direct_to_ddms);
1162 hprof.Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001163 Runtime::Current()->GetThreadList()->ResumeAll();
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001164}
1165
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001166} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001167} // namespace art