blob: 0b04276a83d263b0551cb1f519f66bfa42072e5b [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"
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -080047#include "gc_root.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070048#include "gc/accounting/heap_bitmap.h"
49#include "gc/heap.h"
50#include "gc/space/space.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070051#include "globals.h"
Mathieu Chartierad466ad2015-01-08 16:28:08 -080052#include "jdwp/jdwp.h"
53#include "jdwp/jdwp_priv.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070054#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/class.h"
56#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object-inl.h"
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -070058#include "os.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070059#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070060#include "scoped_thread_state_change.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070061#include "thread_list.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040062
63namespace art {
64
65namespace hprof {
66
Mathieu Chartierad466ad2015-01-08 16:28:08 -080067static constexpr bool kDirectStream = true;
Jesse Wilson0c54ac12011-11-09 15:14:05 -050068
Andreas Gampe3a913092015-01-10 00:26:17 -080069static constexpr uint32_t kHprofTime = 0;
70static constexpr uint32_t kHprofNullStackTrace = 0;
71static constexpr uint32_t kHprofNullThread = 0;
Elliott Hughes622a6982012-06-08 17:58:54 -070072
Andreas Gampe3a913092015-01-10 00:26:17 -080073static constexpr size_t kMaxObjectsPerSegment = 128;
74static constexpr size_t kMaxBytesPerSegment = 4096;
Elliott Hughes622a6982012-06-08 17:58:54 -070075
Andreas Gampe3a913092015-01-10 00:26:17 -080076// The static field-name for the synthetic object generated to account for class static overhead.
77static constexpr const char* kStaticOverheadName = "$staticOverhead";
Elliott Hughes622a6982012-06-08 17:58:54 -070078
79enum HprofTag {
80 HPROF_TAG_STRING = 0x01,
81 HPROF_TAG_LOAD_CLASS = 0x02,
82 HPROF_TAG_UNLOAD_CLASS = 0x03,
83 HPROF_TAG_STACK_FRAME = 0x04,
84 HPROF_TAG_STACK_TRACE = 0x05,
85 HPROF_TAG_ALLOC_SITES = 0x06,
86 HPROF_TAG_HEAP_SUMMARY = 0x07,
87 HPROF_TAG_START_THREAD = 0x0A,
88 HPROF_TAG_END_THREAD = 0x0B,
89 HPROF_TAG_HEAP_DUMP = 0x0C,
90 HPROF_TAG_HEAP_DUMP_SEGMENT = 0x1C,
91 HPROF_TAG_HEAP_DUMP_END = 0x2C,
92 HPROF_TAG_CPU_SAMPLES = 0x0D,
93 HPROF_TAG_CONTROL_SETTINGS = 0x0E,
94};
95
96// Values for the first byte of HEAP_DUMP and HEAP_DUMP_SEGMENT records:
97enum HprofHeapTag {
98 // Traditional.
99 HPROF_ROOT_UNKNOWN = 0xFF,
100 HPROF_ROOT_JNI_GLOBAL = 0x01,
101 HPROF_ROOT_JNI_LOCAL = 0x02,
102 HPROF_ROOT_JAVA_FRAME = 0x03,
103 HPROF_ROOT_NATIVE_STACK = 0x04,
104 HPROF_ROOT_STICKY_CLASS = 0x05,
105 HPROF_ROOT_THREAD_BLOCK = 0x06,
106 HPROF_ROOT_MONITOR_USED = 0x07,
107 HPROF_ROOT_THREAD_OBJECT = 0x08,
108 HPROF_CLASS_DUMP = 0x20,
109 HPROF_INSTANCE_DUMP = 0x21,
110 HPROF_OBJECT_ARRAY_DUMP = 0x22,
111 HPROF_PRIMITIVE_ARRAY_DUMP = 0x23,
112
113 // Android.
114 HPROF_HEAP_DUMP_INFO = 0xfe,
115 HPROF_ROOT_INTERNED_STRING = 0x89,
116 HPROF_ROOT_FINALIZING = 0x8a, // Obsolete.
117 HPROF_ROOT_DEBUGGER = 0x8b,
118 HPROF_ROOT_REFERENCE_CLEANUP = 0x8c, // Obsolete.
119 HPROF_ROOT_VM_INTERNAL = 0x8d,
120 HPROF_ROOT_JNI_MONITOR = 0x8e,
121 HPROF_UNREACHABLE = 0x90, // Obsolete.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700122 HPROF_PRIMITIVE_ARRAY_NODATA_DUMP = 0xc3, // Obsolete.
Elliott Hughes622a6982012-06-08 17:58:54 -0700123};
124
125enum HprofHeapId {
126 HPROF_HEAP_DEFAULT = 0,
127 HPROF_HEAP_ZYGOTE = 'Z',
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700128 HPROF_HEAP_APP = 'A',
129 HPROF_HEAP_IMAGE = 'I',
Elliott Hughes622a6982012-06-08 17:58:54 -0700130};
131
132enum HprofBasicType {
133 hprof_basic_object = 2,
134 hprof_basic_boolean = 4,
135 hprof_basic_char = 5,
136 hprof_basic_float = 6,
137 hprof_basic_double = 7,
138 hprof_basic_byte = 8,
139 hprof_basic_short = 9,
140 hprof_basic_int = 10,
141 hprof_basic_long = 11,
142};
143
Ian Rogersef7d42f2014-01-06 12:55:46 -0800144typedef uint32_t HprofStringId;
145typedef uint32_t HprofClassObjectId;
Elliott Hughes622a6982012-06-08 17:58:54 -0700146
Andreas Gampe3a913092015-01-10 00:26:17 -0800147class EndianOutput {
Elliott Hughes622a6982012-06-08 17:58:54 -0700148 public:
Andreas Gampe3a913092015-01-10 00:26:17 -0800149 EndianOutput() : length_(0), sum_length_(0), max_length_(0), started_(false) {}
150 virtual ~EndianOutput() {}
151
152 void StartNewRecord(uint8_t tag, uint32_t time) {
153 if (length_ > 0) {
154 EndRecord();
155 }
156 DCHECK_EQ(length_, 0U);
157 AddU1(tag);
158 AddU4(time);
159 AddU4(0xdeaddead); // Length, replaced on flush.
160 started_ = true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700161 }
162
Andreas Gampe3a913092015-01-10 00:26:17 -0800163 void EndRecord() {
164 // Replace length in header.
165 if (started_) {
166 UpdateU4(sizeof(uint8_t) + sizeof(uint32_t),
167 length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
168 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700169
Andreas Gampe3a913092015-01-10 00:26:17 -0800170 HandleEndRecord();
171
172 sum_length_ += length_;
173 max_length_ = std::max(max_length_, length_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700174 length_ = 0;
Andreas Gampe3a913092015-01-10 00:26:17 -0800175 started_ = false;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700176 }
177
Andreas Gampe3a913092015-01-10 00:26:17 -0800178 void AddU1(uint8_t value) {
179 AddU1List(&value, 1);
180 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800181 void AddU2(uint16_t value) {
182 AddU2List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700183 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800184 void AddU4(uint32_t value) {
185 AddU4List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700186 }
187
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800188 void AddU8(uint64_t value) {
189 AddU8List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700190 }
191
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800192 void AddObjectId(const mirror::Object* value) {
193 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800194 }
195
196 // The ID for the synthetic object generated to account for class static overhead.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800197 void AddClassStaticsId(const mirror::Class* value) {
198 AddU4(1 | PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800199 }
200
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800201 void AddJniGlobalRefId(jobject value) {
202 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800203 }
204
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800205 void AddClassId(HprofClassObjectId value) {
206 AddU4(value);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800207 }
208
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800209 void AddStringId(HprofStringId value) {
210 AddU4(value);
Elliott Hughes622a6982012-06-08 17:58:54 -0700211 }
212
Andreas Gampe3a913092015-01-10 00:26:17 -0800213 void AddU1List(const uint8_t* values, size_t count) {
214 HandleU1List(values, count);
215 length_ += count;
216 }
217 void AddU2List(const uint16_t* values, size_t count) {
218 HandleU2List(values, count);
219 length_ += count * sizeof(uint16_t);
220 }
221 void AddU4List(const uint32_t* values, size_t count) {
222 HandleU4List(values, count);
223 length_ += count * sizeof(uint32_t);
224 }
225 virtual void UpdateU4(size_t offset ATTRIBUTE_UNUSED, uint32_t new_value ATTRIBUTE_UNUSED) {
226 DCHECK_LE(offset, length_ - 4);
227 }
228 void AddU8List(const uint64_t* values, size_t count) {
229 HandleU8List(values, count);
230 length_ += count * sizeof(uint64_t);
231 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700232
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800233 void AddIdList(mirror::ObjectArray<mirror::Object>* values)
Andreas Gampe3a913092015-01-10 00:26:17 -0800234 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800235 const int32_t length = values->GetLength();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800236 for (int32_t i = 0; i < length; ++i) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800237 AddObjectId(values->GetWithoutChecks(i));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800238 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700239 }
240
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800241 void AddUtf8String(const char* str) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700242 // The terminating NUL character is NOT written.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800243 AddU1List((const uint8_t*)str, strlen(str));
Elliott Hughes622a6982012-06-08 17:58:54 -0700244 }
245
Andreas Gampe3a913092015-01-10 00:26:17 -0800246 size_t Length() const {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700247 return length_;
248 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700249
Andreas Gampe3a913092015-01-10 00:26:17 -0800250 size_t SumLength() const {
251 return sum_length_;
Elliott Hughes622a6982012-06-08 17:58:54 -0700252 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700253
Andreas Gampe3a913092015-01-10 00:26:17 -0800254 size_t MaxLength() const {
255 return max_length_;
256 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700257
Andreas Gampe3a913092015-01-10 00:26:17 -0800258 protected:
259 virtual void HandleU1List(const uint8_t* values ATTRIBUTE_UNUSED,
260 size_t count ATTRIBUTE_UNUSED) {
261 }
262 virtual void HandleU2List(const uint16_t* values ATTRIBUTE_UNUSED,
263 size_t count ATTRIBUTE_UNUSED) {
264 }
265 virtual void HandleU4List(const uint32_t* values ATTRIBUTE_UNUSED,
266 size_t count ATTRIBUTE_UNUSED) {
267 }
268 virtual void HandleU8List(const uint64_t* values ATTRIBUTE_UNUSED,
269 size_t count ATTRIBUTE_UNUSED) {
270 }
271 virtual void HandleEndRecord() {
272 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700273
Andreas Gampe3a913092015-01-10 00:26:17 -0800274 size_t length_; // Current record size.
275 size_t sum_length_; // Size of all data.
276 size_t max_length_; // Maximum seen length.
277 bool started_; // Was StartRecord called?
Elliott Hughes622a6982012-06-08 17:58:54 -0700278};
279
Andreas Gampe3a913092015-01-10 00:26:17 -0800280// This keeps things buffered until flushed.
281class EndianOutputBuffered : public EndianOutput {
282 public:
283 explicit EndianOutputBuffered(size_t reserve_size) {
284 buffer_.reserve(reserve_size);
285 }
286 virtual ~EndianOutputBuffered() {}
287
288 void UpdateU4(size_t offset, uint32_t new_value) OVERRIDE {
289 DCHECK_LE(offset, length_ - 4);
290 buffer_[offset + 0] = static_cast<uint8_t>((new_value >> 24) & 0xFF);
291 buffer_[offset + 1] = static_cast<uint8_t>((new_value >> 16) & 0xFF);
292 buffer_[offset + 2] = static_cast<uint8_t>((new_value >> 8) & 0xFF);
293 buffer_[offset + 3] = static_cast<uint8_t>((new_value >> 0) & 0xFF);
294 }
295
296 protected:
297 void HandleU1List(const uint8_t* values, size_t count) OVERRIDE {
298 DCHECK_EQ(length_, buffer_.size());
299 buffer_.insert(buffer_.end(), values, values + count);
300 }
301
302 void HandleU2List(const uint16_t* values, size_t count) OVERRIDE {
303 DCHECK_EQ(length_, buffer_.size());
304 for (size_t i = 0; i < count; ++i) {
305 uint16_t value = *values;
306 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
307 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
308 values++;
309 }
310 }
311
312 void HandleU4List(const uint32_t* values, size_t count) OVERRIDE {
313 DCHECK_EQ(length_, buffer_.size());
314 for (size_t i = 0; i < count; ++i) {
315 uint32_t value = *values;
316 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
317 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
318 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
319 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
320 values++;
321 }
322 }
323
324 void HandleU8List(const uint64_t* values, size_t count) OVERRIDE {
325 DCHECK_EQ(length_, buffer_.size());
326 for (size_t i = 0; i < count; ++i) {
327 uint64_t value = *values;
328 buffer_.push_back(static_cast<uint8_t>((value >> 56) & 0xFF));
329 buffer_.push_back(static_cast<uint8_t>((value >> 48) & 0xFF));
330 buffer_.push_back(static_cast<uint8_t>((value >> 40) & 0xFF));
331 buffer_.push_back(static_cast<uint8_t>((value >> 32) & 0xFF));
332 buffer_.push_back(static_cast<uint8_t>((value >> 24) & 0xFF));
333 buffer_.push_back(static_cast<uint8_t>((value >> 16) & 0xFF));
334 buffer_.push_back(static_cast<uint8_t>((value >> 8) & 0xFF));
335 buffer_.push_back(static_cast<uint8_t>((value >> 0) & 0xFF));
336 values++;
337 }
338 }
339
340 void HandleEndRecord() OVERRIDE {
341 DCHECK_EQ(buffer_.size(), length_);
342 if (kIsDebugBuild && started_) {
343 uint32_t stored_length =
344 static_cast<uint32_t>(buffer_[5]) << 24 |
345 static_cast<uint32_t>(buffer_[6]) << 16 |
346 static_cast<uint32_t>(buffer_[7]) << 8 |
347 static_cast<uint32_t>(buffer_[8]);
348 DCHECK_EQ(stored_length, length_ - sizeof(uint8_t) - 2 * sizeof(uint32_t));
349 }
350 HandleFlush(buffer_.data(), length_);
351 buffer_.clear();
352 }
353
354 virtual void HandleFlush(const uint8_t* buffer ATTRIBUTE_UNUSED, size_t length ATTRIBUTE_UNUSED) {
355 }
356
357 std::vector<uint8_t> buffer_;
358};
359
360class FileEndianOutput FINAL : public EndianOutputBuffered {
361 public:
362 FileEndianOutput(File* fp, size_t reserved_size)
363 : EndianOutputBuffered(reserved_size), fp_(fp), errors_(false) {
364 DCHECK(fp != nullptr);
365 }
366 ~FileEndianOutput() {
367 }
368
369 bool Errors() {
370 return errors_;
371 }
372
373 protected:
374 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
375 if (!errors_) {
376 errors_ = !fp_->WriteFully(buffer, length);
377 }
378 }
379
380 private:
381 File* fp_;
382 bool errors_;
383};
384
385class NetStateEndianOutput FINAL : public EndianOutputBuffered {
386 public:
387 NetStateEndianOutput(JDWP::JdwpNetStateBase* net_state, size_t reserved_size)
388 : EndianOutputBuffered(reserved_size), net_state_(net_state) {
389 DCHECK(net_state != nullptr);
390 }
391 ~NetStateEndianOutput() {}
392
393 protected:
394 void HandleFlush(const uint8_t* buffer, size_t length) OVERRIDE {
395 std::vector<iovec> iov;
396 iov.push_back(iovec());
397 iov[0].iov_base = const_cast<void*>(reinterpret_cast<const void*>(buffer));
398 iov[0].iov_len = length;
399 net_state_->WriteBufferedPacketLocked(iov);
400 }
401
402 private:
403 JDWP::JdwpNetStateBase* net_state_;
404};
405
406#define __ output->
407
Elliott Hughes622a6982012-06-08 17:58:54 -0700408class Hprof {
409 public:
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700410 Hprof(const char* output_filename, int fd, bool direct_to_ddms)
411 : filename_(output_filename),
412 fd_(fd),
413 direct_to_ddms_(direct_to_ddms),
414 start_ns_(NanoTime()),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700415 current_heap_(HPROF_HEAP_DEFAULT),
416 objects_in_segment_(0),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700417 next_string_id_(0x400000) {
418 LOG(INFO) << "hprof: heap dump \"" << filename_ << "\" starting...";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500419 }
420
Andreas Gampe3a913092015-01-10 00:26:17 -0800421 void Dump()
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800422 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800423 LOCKS_EXCLUDED(Locks::heap_bitmap_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800424 // 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 Chartiere34fa1d2015-01-14 14:55:47 -0800459 static void RootVisitor(mirror::Object** obj, void* arg, const RootInfo& root_info)
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);
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800465 env->hprof->VisitRoot(*obj, root_info, 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)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800489 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800490 // Reset current heap and object count.
491 current_heap_ = HPROF_HEAP_DEFAULT;
492 objects_in_segment_ = 0;
493
494 if (header_first) {
495 ProcessHeader(output);
496 ProcessBody(output);
497 } else {
498 ProcessBody(output);
499 ProcessHeader(output);
500 }
501 }
502
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800503 void ProcessBody(EndianOutput* output) EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800504 Runtime* runtime = Runtime::Current();
505 // Walk the roots and the heap.
506 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
507
508 Env env = { this, output };
509 runtime->VisitRoots(RootVisitor, &env);
510 runtime->GetHeap()->VisitObjects(VisitObjectCallback, &env);
511
512 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_END, kHprofTime);
513 output->EndRecord();
514 }
515
516 void ProcessHeader(EndianOutput* output) EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
517 // Write the header.
518 WriteFixedHeader(output);
519 // Write the string and class tables, and any stack traces, to the header.
520 // (jhat requires that these appear before any of the data in the body that refers to them.)
521 WriteStringTable(output);
522 WriteClassTable(output);
523 WriteStackTraces(output);
524 output->EndRecord();
525 }
526
527 void WriteClassTable(EndianOutput* output) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700528 uint32_t nextSerialNumber = 1;
529
Ian Rogersef7d42f2014-01-06 12:55:46 -0800530 for (mirror::Class* c : classes_) {
531 CHECK(c != nullptr);
Andreas Gampe3a913092015-01-10 00:26:17 -0800532 output->StartNewRecord(HPROF_TAG_LOAD_CLASS, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700533 // LOAD CLASS format:
534 // U4: class serial number (always > 0)
535 // ID: class object ID. We use the address of the class object structure as its ID.
536 // U4: stack trace serial number
537 // ID: class name string ID
Andreas Gampe3a913092015-01-10 00:26:17 -0800538 __ AddU4(nextSerialNumber++);
539 __ AddObjectId(c);
540 __ AddU4(kHprofNullStackTrace);
541 __ AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700542 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700543 }
544
Andreas Gampe3a913092015-01-10 00:26:17 -0800545 void WriteStringTable(EndianOutput* output) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800546 for (const std::pair<std::string, HprofStringId>& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800547 const std::string& string = p.first;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800548 const size_t id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700549
Andreas Gampe3a913092015-01-10 00:26:17 -0800550 output->StartNewRecord(HPROF_TAG_STRING, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700551
552 // STRING format:
553 // ID: ID for this string
554 // U1*: UTF8 characters for string (NOT NULL terminated)
555 // (the record format encodes the length)
Andreas Gampe3a913092015-01-10 00:26:17 -0800556 __ AddU4(id);
557 __ AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700558 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700559 }
560
Andreas Gampe3a913092015-01-10 00:26:17 -0800561 void StartNewHeapDumpSegment(EndianOutput* output) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700562 // This flushes the old segment and starts a new one.
Andreas Gampe3a913092015-01-10 00:26:17 -0800563 output->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700564 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700565 // Starting a new HEAP_DUMP resets the heap to default.
566 current_heap_ = HPROF_HEAP_DEFAULT;
567 }
568
Andreas Gampe3a913092015-01-10 00:26:17 -0800569 void CheckHeapSegmentConstraints(EndianOutput* output) {
570 if (objects_in_segment_ >= kMaxObjectsPerSegment || output->Length() >= kMaxBytesPerSegment) {
571 StartNewHeapDumpSegment(output);
572 }
573 }
574
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800575 void VisitRoot(const mirror::Object* obj, const RootInfo& root_info, EndianOutput* output)
Andreas Gampe3a913092015-01-10 00:26:17 -0800576 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
577 void MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
578 uint32_t thread_serial, EndianOutput* output);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700579
Ian Rogersef7d42f2014-01-06 12:55:46 -0800580 HprofClassObjectId LookupClassId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800581 if (c != nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800582 auto result = classes_.insert(c);
583 const mirror::Class* present = *result.first;
584 CHECK_EQ(present, c);
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800585 // Make sure that we've assigned a string ID for this class' name
586 LookupClassNameId(c);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800587 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800588 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700589 }
590
Ian Rogersef7d42f2014-01-06 12:55:46 -0800591 HprofStringId LookupStringId(mirror::String* string) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700592 return LookupStringId(string->ToModifiedUtf8());
593 }
594
595 HprofStringId LookupStringId(const char* string) {
596 return LookupStringId(std::string(string));
597 }
598
599 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800600 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700601 if (it != strings_.end()) {
602 return it->second;
603 }
604 HprofStringId id = next_string_id_++;
605 strings_.Put(string, id);
606 return id;
607 }
608
Ian Rogersef7d42f2014-01-06 12:55:46 -0800609 HprofStringId LookupClassNameId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700610 return LookupStringId(PrettyDescriptor(c));
611 }
612
Andreas Gampe3a913092015-01-10 00:26:17 -0800613 void WriteFixedHeader(EndianOutput* output) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500614 // Write the file header.
615 // U1: NUL-terminated magic string.
Andreas Gampe3a913092015-01-10 00:26:17 -0800616 const char magic[] = "JAVA PROFILE 1.0.3";
617 __ AddU1List(reinterpret_cast<const uint8_t*>(magic), sizeof(magic));
618
Calin Juravle32805172014-07-04 16:24:03 +0100619 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
620 // as uint32_t.
621 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800622 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
623 "Unexpected HeapReference size");
Andreas Gampe3a913092015-01-10 00:26:17 -0800624 __ AddU4(sizeof(uint32_t));
625
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500626 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700627 timeval now;
Andreas Gampe3a913092015-01-10 00:26:17 -0800628 const uint64_t nowMs = (gettimeofday(&now, nullptr) < 0) ? 0 :
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800629 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Andreas Gampe3a913092015-01-10 00:26:17 -0800630 // TODO: It seems it would be correct to use U8.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500631 // U4: high word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800632 __ AddU4(static_cast<uint32_t>(nowMs >> 32));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500633 // U4: low word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800634 __ AddU4(static_cast<uint32_t>(nowMs & 0xFFFFFFFF));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500635 }
636
Andreas Gampe3a913092015-01-10 00:26:17 -0800637 void WriteStackTraces(EndianOutput* output) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700638 // Write a dummy stack trace record so the analysis tools don't freak out.
Andreas Gampe3a913092015-01-10 00:26:17 -0800639 output->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
640 __ AddU4(kHprofNullStackTrace);
641 __ AddU4(kHprofNullThread);
642 __ AddU4(0); // no frames
643 }
644
645 bool DumpToDdmsBuffered(size_t overall_size ATTRIBUTE_UNUSED, size_t max_length ATTRIBUTE_UNUSED)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800646 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800647 LOG(FATAL) << "Unimplemented";
648 UNREACHABLE();
649 // // Send the data off to DDMS.
650 // iovec iov[2];
651 // iov[0].iov_base = header_data_ptr_;
652 // iov[0].iov_len = header_data_size_;
653 // iov[1].iov_base = body_data_ptr_;
654 // iov[1].iov_len = body_data_size_;
655 // Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
656 }
657
658 bool DumpToFile(size_t overall_size, size_t max_length)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800659 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800660 // Where exactly are we writing to?
661 int out_fd;
662 if (fd_ >= 0) {
663 out_fd = dup(fd_);
664 if (out_fd < 0) {
665 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
666 return false;
667 }
668 } else {
669 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
670 if (out_fd < 0) {
671 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
672 strerror(errno));
673 return false;
674 }
675 }
676
677 std::unique_ptr<File> file(new File(out_fd, filename_, true));
678 bool okay;
679 {
680 FileEndianOutput file_output(file.get(), max_length);
681 ProcessHeap(&file_output, true);
682 okay = !file_output.Errors();
683
684 if (okay) {
685 // Check for expected size.
686 CHECK_EQ(file_output.SumLength(), overall_size);
687 }
688 }
689
690 if (okay) {
691 okay = file->FlushCloseOrErase() == 0;
692 } else {
693 file->Erase();
694 }
695 if (!okay) {
696 std::string msg(StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
697 filename_.c_str(), strerror(errno)));
698 ThrowRuntimeException("%s", msg.c_str());
699 LOG(ERROR) << msg;
700 }
701
702 return okay;
703 }
704
705 bool DumpToDdmsDirect(size_t overall_size, size_t max_length, uint32_t chunk_type)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800706 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800707 CHECK(direct_to_ddms_);
708 JDWP::JdwpState* state = Dbg::GetJdwpState();
709 CHECK(state != nullptr);
710 JDWP::JdwpNetStateBase* net_state = state->netState;
711 CHECK(net_state != nullptr);
712
713 // Hold the socket lock for the whole time since we want this to be atomic.
714 MutexLock mu(Thread::Current(), *net_state->GetSocketLock());
715
716 // Prepare the Ddms chunk.
717 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
718 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
719 state->SetupChunkHeader(chunk_type, overall_size, kChunkHeaderSize, chunk_header);
720
721 // Prepare the output and send the chunk header.
722 NetStateEndianOutput net_output(net_state, max_length);
723 net_output.AddU1List(chunk_header, kChunkHeaderSize);
724
725 // Write the dump.
726 ProcessHeap(&net_output, true);
727
728 // Check for expected size.
729 CHECK_EQ(net_output.SumLength(), overall_size + kChunkHeaderSize);
730
731 return true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700732 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500733
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700734 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
735 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
736 // only be used for debug messages.
737 std::string filename_;
738 int fd_;
739 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500740
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700741 uint64_t start_ns_;
742
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700743 HprofHeapId current_heap_; // Which heap we're currently dumping.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700744 size_t objects_in_segment_;
745
Ian Rogersef7d42f2014-01-06 12:55:46 -0800746 std::set<mirror::Class*> classes_;
747 HprofStringId next_string_id_;
748 SafeMap<std::string, HprofStringId> strings_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700749
750 DISALLOW_COPY_AND_ASSIGN(Hprof);
751};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500752
Andreas Gampe3a913092015-01-10 00:26:17 -0800753static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* size_out) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500754 char c = sig[0];
755 HprofBasicType ret;
756 size_t size;
757
758 switch (c) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800759 case '[':
760 case 'L':
761 ret = hprof_basic_object;
762 size = 4;
763 break;
764 case 'Z':
765 ret = hprof_basic_boolean;
766 size = 1;
767 break;
768 case 'C':
769 ret = hprof_basic_char;
770 size = 2;
771 break;
772 case 'F':
773 ret = hprof_basic_float;
774 size = 4;
775 break;
776 case 'D':
777 ret = hprof_basic_double;
778 size = 8;
779 break;
780 case 'B':
781 ret = hprof_basic_byte;
782 size = 1;
783 break;
784 case 'S':
785 ret = hprof_basic_short;
786 size = 2;
787 break;
788 case 'I':
789 ret = hprof_basic_int;
790 size = 4;
791 break;
792 case 'J':
793 ret = hprof_basic_long;
794 size = 8;
795 break;
796 default:
797 LOG(FATAL) << "UNREACHABLE";
798 UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500799 }
800
Andreas Gampe3a913092015-01-10 00:26:17 -0800801 if (size_out != nullptr) {
802 *size_out = size;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500803 }
804
805 return ret;
806}
807
808// Always called when marking objects, but only does
809// something when ctx->gc_scan_state_ is non-zero, which is usually
810// only true when marking the root set or unreachable
811// objects. Used to add rootset references to obj.
Andreas Gampe3a913092015-01-10 00:26:17 -0800812void Hprof::MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
813 uint32_t thread_serial, EndianOutput* output) {
814 if (heap_tag == 0) {
815 return;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500816 }
817
Andreas Gampe3a913092015-01-10 00:26:17 -0800818 CheckHeapSegmentConstraints(output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500819
Andreas Gampe3a913092015-01-10 00:26:17 -0800820 switch (heap_tag) {
821 // ID: object ID
822 case HPROF_ROOT_UNKNOWN:
823 case HPROF_ROOT_STICKY_CLASS:
824 case HPROF_ROOT_MONITOR_USED:
825 case HPROF_ROOT_INTERNED_STRING:
826 case HPROF_ROOT_DEBUGGER:
827 case HPROF_ROOT_VM_INTERNAL:
828 __ AddU1(heap_tag);
829 __ AddObjectId(obj);
830 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500831
Andreas Gampe3a913092015-01-10 00:26:17 -0800832 // ID: object ID
833 // ID: JNI global ref ID
834 case HPROF_ROOT_JNI_GLOBAL:
835 __ AddU1(heap_tag);
836 __ AddObjectId(obj);
837 __ AddJniGlobalRefId(jni_obj);
838 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500839
Andreas Gampe3a913092015-01-10 00:26:17 -0800840 // ID: object ID
841 // U4: thread serial number
842 // U4: frame number in stack trace (-1 for empty)
843 case HPROF_ROOT_JNI_LOCAL:
844 case HPROF_ROOT_JNI_MONITOR:
845 case HPROF_ROOT_JAVA_FRAME:
846 __ AddU1(heap_tag);
847 __ AddObjectId(obj);
848 __ AddU4(thread_serial);
849 __ AddU4((uint32_t)-1);
850 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500851
Andreas Gampe3a913092015-01-10 00:26:17 -0800852 // ID: object ID
853 // U4: thread serial number
854 case HPROF_ROOT_NATIVE_STACK:
855 case HPROF_ROOT_THREAD_BLOCK:
856 __ AddU1(heap_tag);
857 __ AddObjectId(obj);
858 __ AddU4(thread_serial);
859 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500860
Andreas Gampe3a913092015-01-10 00:26:17 -0800861 // ID: thread object ID
862 // U4: thread serial number
863 // U4: stack trace serial number
864 case HPROF_ROOT_THREAD_OBJECT:
865 __ AddU1(heap_tag);
866 __ AddObjectId(obj);
867 __ AddU4(thread_serial);
868 __ AddU4((uint32_t)-1); // xxx
869 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500870
Andreas Gampe3a913092015-01-10 00:26:17 -0800871 case HPROF_CLASS_DUMP:
872 case HPROF_INSTANCE_DUMP:
873 case HPROF_OBJECT_ARRAY_DUMP:
874 case HPROF_PRIMITIVE_ARRAY_DUMP:
875 case HPROF_HEAP_DUMP_INFO:
876 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
877 // Ignored.
878 break;
Elliott Hughes73e66f72012-05-09 09:34:45 -0700879
Andreas Gampe3a913092015-01-10 00:26:17 -0800880 case HPROF_ROOT_FINALIZING:
881 case HPROF_ROOT_REFERENCE_CLEANUP:
882 case HPROF_UNREACHABLE:
883 LOG(FATAL) << "obsolete tag " << static_cast<int>(heap_tag);
884 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500885 }
886
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700887 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500888}
889
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800890static int StackTraceSerialNumber(const mirror::Object* /*obj*/) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800891 return kHprofNullStackTrace;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500892}
893
Andreas Gampe3a913092015-01-10 00:26:17 -0800894void Hprof::DumpHeapObject(mirror::Object* obj, EndianOutput* output) {
895 // Ignore classes that are retired.
896 if (obj->IsClass() && obj->AsClass()->IsRetired()) {
897 return;
898 }
899
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700900 gc::space::ContinuousSpace* space =
901 Runtime::Current()->GetHeap()->FindContinuousSpaceFromObject(obj, true);
902 HprofHeapId heap_type = HPROF_HEAP_APP;
903 if (space != nullptr) {
904 if (space->IsZygoteSpace()) {
905 heap_type = HPROF_HEAP_ZYGOTE;
906 } else if (space->IsImageSpace()) {
907 heap_type = HPROF_HEAP_IMAGE;
908 }
909 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800910 CheckHeapSegmentConstraints(output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500911
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700912 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500913 HprofStringId nameId;
914
915 // This object is in a different heap than the current one.
916 // Emit a HEAP_DUMP_INFO tag to change heaps.
Andreas Gampe3a913092015-01-10 00:26:17 -0800917 __ AddU1(HPROF_HEAP_DUMP_INFO);
918 __ AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700919 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500920 case HPROF_HEAP_APP:
921 nameId = LookupStringId("app");
922 break;
923 case HPROF_HEAP_ZYGOTE:
924 nameId = LookupStringId("zygote");
925 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700926 case HPROF_HEAP_IMAGE:
927 nameId = LookupStringId("image");
928 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500929 default:
930 // Internal error
931 LOG(ERROR) << "Unexpected desiredHeap";
932 nameId = LookupStringId("<ILLEGAL>");
933 break;
934 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800935 __ AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700936 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500937 }
938
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800939 mirror::Class* c = obj->GetClass();
Andreas Gampe3a913092015-01-10 00:26:17 -0800940 if (c == nullptr) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500941 // This object will bother HprofReader, because it has a NULL
942 // class, so just don't dump it. It could be
943 // gDvm.unlinkedJavaLangClass or it could be an object just
944 // allocated which hasn't been initialized yet.
945 } else {
946 if (obj->IsClass()) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800947 DumpHeapClass(obj->AsClass(), output);
Elliott Hughese84278b2012-03-22 10:06:53 -0700948 } else if (c->IsArrayClass()) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800949 DumpHeapArray(obj->AsArray(), c, output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500950 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800951 DumpHeapInstanceObject(obj, c, output);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500952 }
953 }
954
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700955 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500956}
957
Andreas Gampe3a913092015-01-10 00:26:17 -0800958void Hprof::DumpHeapClass(mirror::Class* klass, EndianOutput* output) {
959 size_t sFieldCount = klass->NumStaticFields();
960 if (sFieldCount != 0) {
961 int byteLength = sFieldCount * sizeof(JValue); // TODO bogus; fields are packed
962 // Create a byte array to reflect the allocation of the
963 // StaticField array at the end of this class.
964 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
965 __ AddClassStaticsId(klass);
966 __ AddU4(StackTraceSerialNumber(klass));
967 __ AddU4(byteLength);
968 __ AddU1(hprof_basic_byte);
969 for (int i = 0; i < byteLength; ++i) {
970 __ AddU1(0);
971 }
972 }
973
974 __ AddU1(HPROF_CLASS_DUMP);
975 __ AddClassId(LookupClassId(klass));
976 __ AddU4(StackTraceSerialNumber(klass));
977 __ AddClassId(LookupClassId(klass->GetSuperClass()));
978 __ AddObjectId(klass->GetClassLoader());
979 __ AddObjectId(nullptr); // no signer
980 __ AddObjectId(nullptr); // no prot domain
981 __ AddObjectId(nullptr); // reserved
982 __ AddObjectId(nullptr); // reserved
983 if (klass->IsClassClass()) {
984 // ClassObjects have their static fields appended, so aren't all the same size.
985 // But they're at least this size.
986 __ AddU4(sizeof(mirror::Class)); // instance size
987 } else if (klass->IsArrayClass() || klass->IsPrimitive()) {
988 __ AddU4(0);
989 } else {
990 __ AddU4(klass->GetObjectSize()); // instance size
991 }
992
993 __ AddU2(0); // empty const pool
994
995 // Static fields
996 if (sFieldCount == 0) {
997 __ AddU2((uint16_t)0);
998 } else {
999 __ AddU2((uint16_t)(sFieldCount+1));
1000 __ AddStringId(LookupStringId(kStaticOverheadName));
1001 __ AddU1(hprof_basic_object);
1002 __ AddClassStaticsId(klass);
1003
1004 for (size_t i = 0; i < sFieldCount; ++i) {
1005 mirror::ArtField* f = klass->GetStaticField(i);
1006
1007 size_t size;
1008 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1009 __ AddStringId(LookupStringId(f->GetName()));
1010 __ AddU1(t);
1011 switch (size) {
1012 case 1:
1013 __ AddU1(static_cast<uint8_t>(f->Get32(klass)));
1014 break;
1015 case 2:
1016 __ AddU2(static_cast<uint16_t>(f->Get32(klass)));
1017 break;
1018 case 4:
1019 __ AddU4(f->Get32(klass));
1020 break;
1021 case 8:
1022 __ AddU8(f->Get64(klass));
1023 break;
1024 default:
1025 LOG(FATAL) << "Unexpected size " << size;
1026 UNREACHABLE();
1027 }
1028 }
1029 }
1030
1031 // Instance fields for this class (no superclass fields)
1032 int iFieldCount = klass->IsObjectClass() ? 0 : klass->NumInstanceFields();
1033 __ AddU2((uint16_t)iFieldCount);
1034 for (int i = 0; i < iFieldCount; ++i) {
1035 mirror::ArtField* f = klass->GetInstanceField(i);
1036 __ AddStringId(LookupStringId(f->GetName()));
1037 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), nullptr);
1038 __ AddU1(t);
1039 }
1040}
1041
1042void Hprof::DumpHeapArray(mirror::Array* obj, mirror::Class* klass, EndianOutput* output) {
1043 uint32_t length = obj->GetLength();
1044
1045 if (obj->IsObjectArray()) {
1046 // obj is an object array.
1047 __ AddU1(HPROF_OBJECT_ARRAY_DUMP);
1048
1049 __ AddObjectId(obj);
1050 __ AddU4(StackTraceSerialNumber(obj));
1051 __ AddU4(length);
1052 __ AddClassId(LookupClassId(klass));
1053
1054 // Dump the elements, which are always objects or NULL.
1055 __ AddIdList(obj->AsObjectArray<mirror::Object>());
1056 } else {
1057 size_t size;
1058 HprofBasicType t = SignatureToBasicTypeAndSize(
1059 Primitive::Descriptor(klass->GetComponentType()->GetPrimitiveType()), &size);
1060
1061 // obj is a primitive array.
1062 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1063
1064 __ AddObjectId(obj);
1065 __ AddU4(StackTraceSerialNumber(obj));
1066 __ AddU4(length);
1067 __ AddU1(t);
1068
1069 // Dump the raw, packed element values.
1070 if (size == 1) {
1071 __ AddU1List(reinterpret_cast<const uint8_t*>(obj->GetRawData(sizeof(uint8_t), 0)), length);
1072 } else if (size == 2) {
1073 __ AddU2List(reinterpret_cast<const uint16_t*>(obj->GetRawData(sizeof(uint16_t), 0)), length);
1074 } else if (size == 4) {
1075 __ AddU4List(reinterpret_cast<const uint32_t*>(obj->GetRawData(sizeof(uint32_t), 0)), length);
1076 } else if (size == 8) {
1077 __ AddU8List(reinterpret_cast<const uint64_t*>(obj->GetRawData(sizeof(uint64_t), 0)), length);
1078 }
1079 }
1080}
1081
1082void Hprof::DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass,
1083 EndianOutput* output) {
1084 // obj is an instance object.
1085 __ AddU1(HPROF_INSTANCE_DUMP);
1086 __ AddObjectId(obj);
1087 __ AddU4(StackTraceSerialNumber(obj));
1088 __ AddClassId(LookupClassId(klass));
1089
1090 // Reserve some space for the length of the instance data, which we won't
1091 // know until we're done writing it.
1092 size_t size_patch_offset = output->Length();
1093 __ AddU4(0x77777777);
1094
1095 // Write the instance data; fields for this class, followed by super class fields,
1096 // and so on. Don't write the klass or monitor fields of Object.class.
1097 while (!klass->IsObjectClass()) {
1098 int ifieldCount = klass->NumInstanceFields();
1099 for (int i = 0; i < ifieldCount; ++i) {
1100 mirror::ArtField* f = klass->GetInstanceField(i);
1101 size_t size;
1102 SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1103 if (size == 1) {
1104 __ AddU1(f->Get32(obj));
1105 } else if (size == 2) {
1106 __ AddU2(f->Get32(obj));
1107 } else if (size == 4) {
1108 __ AddU4(f->Get32(obj));
1109 } else {
1110 CHECK_EQ(size, 8U);
1111 __ AddU8(f->Get64(obj));
1112 }
1113 }
1114
1115 klass = klass->GetSuperClass();
1116 }
1117
1118 // Patch the instance field length.
1119 __ UpdateU4(size_patch_offset, output->Length() - (size_patch_offset + 4));
1120}
1121
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001122void Hprof::VisitRoot(const mirror::Object* obj, const RootInfo& info, EndianOutput* output) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001123 static const HprofHeapTag xlate[] = {
1124 HPROF_ROOT_UNKNOWN,
1125 HPROF_ROOT_JNI_GLOBAL,
1126 HPROF_ROOT_JNI_LOCAL,
1127 HPROF_ROOT_JAVA_FRAME,
1128 HPROF_ROOT_NATIVE_STACK,
1129 HPROF_ROOT_STICKY_CLASS,
1130 HPROF_ROOT_THREAD_BLOCK,
1131 HPROF_ROOT_MONITOR_USED,
1132 HPROF_ROOT_THREAD_OBJECT,
1133 HPROF_ROOT_INTERNED_STRING,
1134 HPROF_ROOT_FINALIZING,
1135 HPROF_ROOT_DEBUGGER,
1136 HPROF_ROOT_REFERENCE_CLEANUP,
1137 HPROF_ROOT_VM_INTERNAL,
1138 HPROF_ROOT_JNI_MONITOR,
1139 };
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001140 CHECK_LT(info.GetType(), sizeof(xlate) / sizeof(HprofHeapTag));
Andreas Gampe3a913092015-01-10 00:26:17 -08001141 if (obj == nullptr) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001142 return;
1143 }
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001144 MarkRootObject(obj, 0, xlate[info.GetType()], info.GetThreadId(), output);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001145}
1146
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001147// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1148// sent directly to DDMS.
1149// If "fd" is >= 0, the output will be written to that file descriptor.
1150// Otherwise, "filename" is used to create an output file.
1151void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001152 CHECK(filename != nullptr);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001153
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001154 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001155 Hprof hprof(filename, fd, direct_to_ddms);
1156 hprof.Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001157 Runtime::Current()->GetThreadList()->ResumeAll();
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001158}
1159
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001160} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001161} // namespace art