blob: efead51800bc668fa53c4decf78174c3fa032848 [file] [log] [blame]
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Preparation and completion of hprof data generation. The output is
19 * written into two files and then combined. This is necessary because
20 * we generate some of the data (strings and classes) while we dump the
21 * heap, and some analysis tools require that the class and string data
22 * appear first.
23 */
24
25#include "hprof.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080026
Elliott Hughes622a6982012-06-08 17:58:54 -070027#include <cutils/open_memstream.h>
28#include <errno.h>
29#include <fcntl.h>
30#include <stdio.h>
31#include <string.h>
32#include <sys/time.h>
33#include <sys/uio.h>
34#include <time.h>
35#include <time.h>
36#include <unistd.h>
37
38#include <set>
39
Mathieu Chartierc7853442015-03-27 14:35:38 -070040#include "art_field-inl.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080041#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080042#include "base/stringprintf.h"
Elliott Hughes76160052012-12-12 16:31:20 -080043#include "base/unix_file/fd_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080044#include "class_linker.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080045#include "common_throws.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040046#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070047#include "dex_file-inl.h"
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -080048#include "gc_root.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070049#include "gc/accounting/heap_bitmap.h"
50#include "gc/heap.h"
51#include "gc/space/space.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070052#include "globals.h"
Mathieu Chartierad466ad2015-01-08 16:28:08 -080053#include "jdwp/jdwp.h"
54#include "jdwp/jdwp_priv.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 }
Andreas Gampeca714582015-04-03 19:41:34 -0700225 virtual void UpdateU4(size_t offset, uint32_t new_value ATTRIBUTE_UNUSED) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800226 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
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700406#define __ output_->
Andreas Gampe3a913092015-01-10 00:26:17 -0800407
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700408class Hprof : public SingleRootVisitor {
Elliott Hughes622a6982012-06-08 17:58:54 -0700409 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;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700429 output_ = &count_output;
430 ProcessHeap(false);
Andreas Gampe3a913092015-01-10 00:26:17 -0800431 overall_size = count_output.SumLength();
432 max_length = count_output.MaxLength();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700433 output_ = nullptr;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800434 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700435
Andreas Gampe3a913092015-01-10 00:26:17 -0800436 bool okay;
437 if (direct_to_ddms_) {
438 if (kDirectStream) {
439 okay = DumpToDdmsDirect(overall_size, max_length, CHUNK_TYPE("HPDS"));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700440 } else {
Andreas Gampe3a913092015-01-10 00:26:17 -0800441 okay = DumpToDdmsBuffered(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700442 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800443 } else {
444 okay = DumpToFile(overall_size, max_length);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700445 }
446
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700447 if (okay) {
448 uint64_t duration = NanoTime() - start_ns_;
Ian Rogers50b35e22012-10-04 10:09:15 -0700449 LOG(INFO) << "hprof: heap dump completed ("
Andreas Gampe3a913092015-01-10 00:26:17 -0800450 << PrettySize(RoundUp(overall_size, 1024))
Ian Rogers50b35e22012-10-04 10:09:15 -0700451 << ") in " << PrettyDuration(duration);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700452 }
453 }
454
455 private:
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800456 static void VisitObjectCallback(mirror::Object* obj, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700457 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800458 DCHECK(obj != nullptr);
459 DCHECK(arg != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700460 reinterpret_cast<Hprof*>(arg)->DumpHeapObject(obj);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700461 }
462
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700463 void DumpHeapObject(mirror::Object* obj)
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800464 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700465
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700466 void DumpHeapClass(mirror::Class* klass)
Andreas Gampe3a913092015-01-10 00:26:17 -0800467 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700468
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700469 void DumpHeapArray(mirror::Array* obj, mirror::Class* klass)
Andreas Gampe3a913092015-01-10 00:26:17 -0800470 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
471
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700472 void DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass)
Andreas Gampe3a913092015-01-10 00:26:17 -0800473 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
474
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700475 void ProcessHeap(bool header_first)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800476 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800477 // Reset current heap and object count.
478 current_heap_ = HPROF_HEAP_DEFAULT;
479 objects_in_segment_ = 0;
480
481 if (header_first) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700482 ProcessHeader();
483 ProcessBody();
Andreas Gampe3a913092015-01-10 00:26:17 -0800484 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700485 ProcessBody();
486 ProcessHeader();
Andreas Gampe3a913092015-01-10 00:26:17 -0800487 }
488 }
489
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700490 void ProcessBody() EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
491 Runtime* const runtime = Runtime::Current();
Andreas Gampe3a913092015-01-10 00:26:17 -0800492 // Walk the roots and the heap.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700493 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Andreas Gampe3a913092015-01-10 00:26:17 -0800494
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700495 runtime->VisitRoots(this);
496 runtime->VisitImageRoots(this);
497 runtime->GetHeap()->VisitObjectsPaused(VisitObjectCallback, this);
Andreas Gampe3a913092015-01-10 00:26:17 -0800498
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700499 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_END, kHprofTime);
500 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800501 }
502
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700503 void ProcessHeader() EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800504 // Write the header.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700505 WriteFixedHeader();
Andreas Gampe3a913092015-01-10 00:26:17 -0800506 // Write the string and class tables, and any stack traces, to the header.
507 // (jhat requires that these appear before any of the data in the body that refers to them.)
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700508 WriteStringTable();
509 WriteClassTable();
510 WriteStackTraces();
511 output_->EndRecord();
Andreas Gampe3a913092015-01-10 00:26:17 -0800512 }
513
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700514 void WriteClassTable() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700515 uint32_t nextSerialNumber = 1;
516
Ian Rogersef7d42f2014-01-06 12:55:46 -0800517 for (mirror::Class* c : classes_) {
518 CHECK(c != nullptr);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700519 output_->StartNewRecord(HPROF_TAG_LOAD_CLASS, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700520 // LOAD CLASS format:
521 // U4: class serial number (always > 0)
522 // ID: class object ID. We use the address of the class object structure as its ID.
523 // U4: stack trace serial number
524 // ID: class name string ID
Andreas Gampe3a913092015-01-10 00:26:17 -0800525 __ AddU4(nextSerialNumber++);
526 __ AddObjectId(c);
527 __ AddU4(kHprofNullStackTrace);
528 __ AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700529 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700530 }
531
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700532 void WriteStringTable() {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800533 for (const std::pair<std::string, HprofStringId>& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800534 const std::string& string = p.first;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800535 const size_t id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700536
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700537 output_->StartNewRecord(HPROF_TAG_STRING, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700538
539 // STRING format:
540 // ID: ID for this string
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700541 // U1*: UTF8 characters for string (NOT null terminated)
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700542 // (the record format encodes the length)
Andreas Gampe3a913092015-01-10 00:26:17 -0800543 __ AddU4(id);
544 __ AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700545 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700546 }
547
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700548 void StartNewHeapDumpSegment() {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700549 // This flushes the old segment and starts a new one.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700550 output_->StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, kHprofTime);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700551 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700552 // Starting a new HEAP_DUMP resets the heap to default.
553 current_heap_ = HPROF_HEAP_DEFAULT;
554 }
555
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700556 void CheckHeapSegmentConstraints() {
557 if (objects_in_segment_ >= kMaxObjectsPerSegment || output_->Length() >= kMaxBytesPerSegment) {
558 StartNewHeapDumpSegment();
Andreas Gampe3a913092015-01-10 00:26:17 -0800559 }
560 }
561
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700562 void VisitRoot(mirror::Object* obj, const RootInfo& root_info)
563 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Andreas Gampe3a913092015-01-10 00:26:17 -0800564 void MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700565 uint32_t thread_serial);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700566
Ian Rogersef7d42f2014-01-06 12:55:46 -0800567 HprofClassObjectId LookupClassId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800568 if (c != nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800569 auto result = classes_.insert(c);
570 const mirror::Class* present = *result.first;
571 CHECK_EQ(present, c);
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800572 // Make sure that we've assigned a string ID for this class' name
573 LookupClassNameId(c);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800574 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800575 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700576 }
577
Ian Rogersef7d42f2014-01-06 12:55:46 -0800578 HprofStringId LookupStringId(mirror::String* string) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700579 return LookupStringId(string->ToModifiedUtf8());
580 }
581
582 HprofStringId LookupStringId(const char* string) {
583 return LookupStringId(std::string(string));
584 }
585
586 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800587 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700588 if (it != strings_.end()) {
589 return it->second;
590 }
591 HprofStringId id = next_string_id_++;
592 strings_.Put(string, id);
593 return id;
594 }
595
Ian Rogersef7d42f2014-01-06 12:55:46 -0800596 HprofStringId LookupClassNameId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700597 return LookupStringId(PrettyDescriptor(c));
598 }
599
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700600 void WriteFixedHeader() {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500601 // Write the file header.
602 // U1: NUL-terminated magic string.
Andreas Gampe3a913092015-01-10 00:26:17 -0800603 const char magic[] = "JAVA PROFILE 1.0.3";
604 __ AddU1List(reinterpret_cast<const uint8_t*>(magic), sizeof(magic));
605
Calin Juravle32805172014-07-04 16:24:03 +0100606 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
607 // as uint32_t.
608 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800609 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
610 "Unexpected HeapReference size");
Andreas Gampe3a913092015-01-10 00:26:17 -0800611 __ AddU4(sizeof(uint32_t));
612
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500613 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700614 timeval now;
Andreas Gampe3a913092015-01-10 00:26:17 -0800615 const uint64_t nowMs = (gettimeofday(&now, nullptr) < 0) ? 0 :
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800616 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Andreas Gampe3a913092015-01-10 00:26:17 -0800617 // TODO: It seems it would be correct to use U8.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500618 // U4: high word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800619 __ AddU4(static_cast<uint32_t>(nowMs >> 32));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500620 // U4: low word of the 64-bit time.
Andreas Gampe3a913092015-01-10 00:26:17 -0800621 __ AddU4(static_cast<uint32_t>(nowMs & 0xFFFFFFFF));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500622 }
623
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700624 void WriteStackTraces() {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700625 // Write a dummy stack trace record so the analysis tools don't freak out.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700626 output_->StartNewRecord(HPROF_TAG_STACK_TRACE, kHprofTime);
Andreas Gampe3a913092015-01-10 00:26:17 -0800627 __ AddU4(kHprofNullStackTrace);
628 __ AddU4(kHprofNullThread);
629 __ AddU4(0); // no frames
630 }
631
632 bool DumpToDdmsBuffered(size_t overall_size ATTRIBUTE_UNUSED, size_t max_length ATTRIBUTE_UNUSED)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800633 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800634 LOG(FATAL) << "Unimplemented";
635 UNREACHABLE();
636 // // Send the data off to DDMS.
637 // iovec iov[2];
638 // iov[0].iov_base = header_data_ptr_;
639 // iov[0].iov_len = header_data_size_;
640 // iov[1].iov_base = body_data_ptr_;
641 // iov[1].iov_len = body_data_size_;
642 // Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
643 }
644
645 bool DumpToFile(size_t overall_size, size_t max_length)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800646 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800647 // Where exactly are we writing to?
648 int out_fd;
649 if (fd_ >= 0) {
650 out_fd = dup(fd_);
651 if (out_fd < 0) {
652 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
653 return false;
654 }
655 } else {
656 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
657 if (out_fd < 0) {
658 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
659 strerror(errno));
660 return false;
661 }
662 }
663
664 std::unique_ptr<File> file(new File(out_fd, filename_, true));
665 bool okay;
666 {
667 FileEndianOutput file_output(file.get(), max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700668 output_ = &file_output;
669 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800670 okay = !file_output.Errors();
671
672 if (okay) {
673 // Check for expected size.
674 CHECK_EQ(file_output.SumLength(), overall_size);
675 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700676 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800677 }
678
679 if (okay) {
680 okay = file->FlushCloseOrErase() == 0;
681 } else {
682 file->Erase();
683 }
684 if (!okay) {
685 std::string msg(StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
686 filename_.c_str(), strerror(errno)));
687 ThrowRuntimeException("%s", msg.c_str());
688 LOG(ERROR) << msg;
689 }
690
691 return okay;
692 }
693
694 bool DumpToDdmsDirect(size_t overall_size, size_t max_length, uint32_t chunk_type)
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800695 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800696 CHECK(direct_to_ddms_);
697 JDWP::JdwpState* state = Dbg::GetJdwpState();
698 CHECK(state != nullptr);
699 JDWP::JdwpNetStateBase* net_state = state->netState;
700 CHECK(net_state != nullptr);
701
702 // Hold the socket lock for the whole time since we want this to be atomic.
703 MutexLock mu(Thread::Current(), *net_state->GetSocketLock());
704
705 // Prepare the Ddms chunk.
706 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
707 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
708 state->SetupChunkHeader(chunk_type, overall_size, kChunkHeaderSize, chunk_header);
709
710 // Prepare the output and send the chunk header.
711 NetStateEndianOutput net_output(net_state, max_length);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700712 output_ = &net_output;
Andreas Gampe3a913092015-01-10 00:26:17 -0800713 net_output.AddU1List(chunk_header, kChunkHeaderSize);
714
715 // Write the dump.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700716 ProcessHeap(true);
Andreas Gampe3a913092015-01-10 00:26:17 -0800717
718 // Check for expected size.
719 CHECK_EQ(net_output.SumLength(), overall_size + kChunkHeaderSize);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700720 output_ = nullptr;
Andreas Gampe3a913092015-01-10 00:26:17 -0800721
722 return true;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700723 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500724
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700725 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
726 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
727 // only be used for debug messages.
728 std::string filename_;
729 int fd_;
730 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500731
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700732 uint64_t start_ns_;
733
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700734 EndianOutput* output_;
735
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700736 HprofHeapId current_heap_; // Which heap we're currently dumping.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700737 size_t objects_in_segment_;
738
Ian Rogersef7d42f2014-01-06 12:55:46 -0800739 std::set<mirror::Class*> classes_;
740 HprofStringId next_string_id_;
741 SafeMap<std::string, HprofStringId> strings_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700742
743 DISALLOW_COPY_AND_ASSIGN(Hprof);
744};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500745
Andreas Gampe3a913092015-01-10 00:26:17 -0800746static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* size_out) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500747 char c = sig[0];
748 HprofBasicType ret;
749 size_t size;
750
751 switch (c) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800752 case '[':
753 case 'L':
754 ret = hprof_basic_object;
755 size = 4;
756 break;
757 case 'Z':
758 ret = hprof_basic_boolean;
759 size = 1;
760 break;
761 case 'C':
762 ret = hprof_basic_char;
763 size = 2;
764 break;
765 case 'F':
766 ret = hprof_basic_float;
767 size = 4;
768 break;
769 case 'D':
770 ret = hprof_basic_double;
771 size = 8;
772 break;
773 case 'B':
774 ret = hprof_basic_byte;
775 size = 1;
776 break;
777 case 'S':
778 ret = hprof_basic_short;
779 size = 2;
780 break;
781 case 'I':
782 ret = hprof_basic_int;
783 size = 4;
784 break;
785 case 'J':
786 ret = hprof_basic_long;
787 size = 8;
788 break;
789 default:
790 LOG(FATAL) << "UNREACHABLE";
791 UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500792 }
793
Andreas Gampe3a913092015-01-10 00:26:17 -0800794 if (size_out != nullptr) {
795 *size_out = size;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500796 }
797
798 return ret;
799}
800
801// Always called when marking objects, but only does
802// something when ctx->gc_scan_state_ is non-zero, which is usually
803// only true when marking the root set or unreachable
804// objects. Used to add rootset references to obj.
Andreas Gampe3a913092015-01-10 00:26:17 -0800805void Hprof::MarkRootObject(const mirror::Object* obj, jobject jni_obj, HprofHeapTag heap_tag,
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700806 uint32_t thread_serial) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800807 if (heap_tag == 0) {
808 return;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500809 }
810
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700811 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500812
Andreas Gampe3a913092015-01-10 00:26:17 -0800813 switch (heap_tag) {
814 // ID: object ID
815 case HPROF_ROOT_UNKNOWN:
816 case HPROF_ROOT_STICKY_CLASS:
817 case HPROF_ROOT_MONITOR_USED:
818 case HPROF_ROOT_INTERNED_STRING:
819 case HPROF_ROOT_DEBUGGER:
820 case HPROF_ROOT_VM_INTERNAL:
821 __ AddU1(heap_tag);
822 __ AddObjectId(obj);
823 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500824
Andreas Gampe3a913092015-01-10 00:26:17 -0800825 // ID: object ID
826 // ID: JNI global ref ID
827 case HPROF_ROOT_JNI_GLOBAL:
828 __ AddU1(heap_tag);
829 __ AddObjectId(obj);
830 __ AddJniGlobalRefId(jni_obj);
831 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500832
Andreas Gampe3a913092015-01-10 00:26:17 -0800833 // ID: object ID
834 // U4: thread serial number
835 // U4: frame number in stack trace (-1 for empty)
836 case HPROF_ROOT_JNI_LOCAL:
837 case HPROF_ROOT_JNI_MONITOR:
838 case HPROF_ROOT_JAVA_FRAME:
839 __ AddU1(heap_tag);
840 __ AddObjectId(obj);
841 __ AddU4(thread_serial);
842 __ AddU4((uint32_t)-1);
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 case HPROF_ROOT_NATIVE_STACK:
848 case HPROF_ROOT_THREAD_BLOCK:
849 __ AddU1(heap_tag);
850 __ AddObjectId(obj);
851 __ AddU4(thread_serial);
852 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500853
Andreas Gampe3a913092015-01-10 00:26:17 -0800854 // ID: thread object ID
855 // U4: thread serial number
856 // U4: stack trace serial number
857 case HPROF_ROOT_THREAD_OBJECT:
858 __ AddU1(heap_tag);
859 __ AddObjectId(obj);
860 __ AddU4(thread_serial);
861 __ AddU4((uint32_t)-1); // xxx
862 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500863
Andreas Gampe3a913092015-01-10 00:26:17 -0800864 case HPROF_CLASS_DUMP:
865 case HPROF_INSTANCE_DUMP:
866 case HPROF_OBJECT_ARRAY_DUMP:
867 case HPROF_PRIMITIVE_ARRAY_DUMP:
868 case HPROF_HEAP_DUMP_INFO:
869 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
870 // Ignored.
871 break;
Elliott Hughes73e66f72012-05-09 09:34:45 -0700872
Andreas Gampe3a913092015-01-10 00:26:17 -0800873 case HPROF_ROOT_FINALIZING:
874 case HPROF_ROOT_REFERENCE_CLEANUP:
875 case HPROF_UNREACHABLE:
876 LOG(FATAL) << "obsolete tag " << static_cast<int>(heap_tag);
877 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500878 }
879
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700880 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500881}
882
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800883static int StackTraceSerialNumber(const mirror::Object* /*obj*/) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800884 return kHprofNullStackTrace;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500885}
886
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700887void Hprof::DumpHeapObject(mirror::Object* obj) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800888 // Ignore classes that are retired.
889 if (obj->IsClass() && obj->AsClass()->IsRetired()) {
890 return;
891 }
892
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700893 gc::space::ContinuousSpace* space =
894 Runtime::Current()->GetHeap()->FindContinuousSpaceFromObject(obj, true);
895 HprofHeapId heap_type = HPROF_HEAP_APP;
896 if (space != nullptr) {
897 if (space->IsZygoteSpace()) {
898 heap_type = HPROF_HEAP_ZYGOTE;
899 } else if (space->IsImageSpace()) {
900 heap_type = HPROF_HEAP_IMAGE;
901 }
902 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700903 CheckHeapSegmentConstraints();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500904
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700905 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500906 HprofStringId nameId;
907
908 // This object is in a different heap than the current one.
909 // Emit a HEAP_DUMP_INFO tag to change heaps.
Andreas Gampe3a913092015-01-10 00:26:17 -0800910 __ AddU1(HPROF_HEAP_DUMP_INFO);
911 __ AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700912 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500913 case HPROF_HEAP_APP:
914 nameId = LookupStringId("app");
915 break;
916 case HPROF_HEAP_ZYGOTE:
917 nameId = LookupStringId("zygote");
918 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700919 case HPROF_HEAP_IMAGE:
920 nameId = LookupStringId("image");
921 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500922 default:
923 // Internal error
924 LOG(ERROR) << "Unexpected desiredHeap";
925 nameId = LookupStringId("<ILLEGAL>");
926 break;
927 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800928 __ AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700929 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500930 }
931
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800932 mirror::Class* c = obj->GetClass();
Andreas Gampe3a913092015-01-10 00:26:17 -0800933 if (c == nullptr) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700934 // This object will bother HprofReader, because it has a null
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500935 // class, so just don't dump it. It could be
936 // gDvm.unlinkedJavaLangClass or it could be an object just
937 // allocated which hasn't been initialized yet.
938 } else {
939 if (obj->IsClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700940 DumpHeapClass(obj->AsClass());
Elliott Hughese84278b2012-03-22 10:06:53 -0700941 } else if (c->IsArrayClass()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700942 DumpHeapArray(obj->AsArray(), c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500943 } else {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700944 DumpHeapInstanceObject(obj, c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500945 }
946 }
947
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700948 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500949}
950
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700951void Hprof::DumpHeapClass(mirror::Class* klass) {
Sebastien Hertzca068b22015-04-07 10:28:53 +0200952 if (!klass->IsLoaded() && !klass->IsErroneous()) {
953 // Class is allocated but not yet loaded: we cannot access its fields or super class.
954 return;
955 }
Andreas Gampe3a913092015-01-10 00:26:17 -0800956 size_t sFieldCount = klass->NumStaticFields();
957 if (sFieldCount != 0) {
958 int byteLength = sFieldCount * sizeof(JValue); // TODO bogus; fields are packed
959 // Create a byte array to reflect the allocation of the
960 // StaticField array at the end of this class.
961 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
962 __ AddClassStaticsId(klass);
963 __ AddU4(StackTraceSerialNumber(klass));
964 __ AddU4(byteLength);
965 __ AddU1(hprof_basic_byte);
966 for (int i = 0; i < byteLength; ++i) {
967 __ AddU1(0);
968 }
969 }
970
971 __ AddU1(HPROF_CLASS_DUMP);
972 __ AddClassId(LookupClassId(klass));
973 __ AddU4(StackTraceSerialNumber(klass));
974 __ AddClassId(LookupClassId(klass->GetSuperClass()));
975 __ AddObjectId(klass->GetClassLoader());
976 __ AddObjectId(nullptr); // no signer
977 __ AddObjectId(nullptr); // no prot domain
978 __ AddObjectId(nullptr); // reserved
979 __ AddObjectId(nullptr); // reserved
980 if (klass->IsClassClass()) {
981 // ClassObjects have their static fields appended, so aren't all the same size.
982 // But they're at least this size.
983 __ AddU4(sizeof(mirror::Class)); // instance size
Jeff Hao0ce43532015-05-12 18:58:32 -0700984 } else if (klass->IsStringClass()) {
985 // Strings are variable length with character data at the end like arrays.
986 // This outputs the size of an empty string.
987 __ AddU4(sizeof(mirror::String));
988 } else if (klass->IsArrayClass() || klass->IsPrimitive()) {
Andreas Gampe3a913092015-01-10 00:26:17 -0800989 __ AddU4(0);
990 } else {
991 __ AddU4(klass->GetObjectSize()); // instance size
992 }
993
994 __ AddU2(0); // empty const pool
995
996 // Static fields
997 if (sFieldCount == 0) {
998 __ AddU2((uint16_t)0);
999 } else {
1000 __ AddU2((uint16_t)(sFieldCount+1));
1001 __ AddStringId(LookupStringId(kStaticOverheadName));
1002 __ AddU1(hprof_basic_object);
1003 __ AddClassStaticsId(klass);
1004
1005 for (size_t i = 0; i < sFieldCount; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001006 ArtField* f = klass->GetStaticField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001007
1008 size_t size;
1009 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1010 __ AddStringId(LookupStringId(f->GetName()));
1011 __ AddU1(t);
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001012 switch (t) {
1013 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001014 __ AddU1(f->GetByte(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001015 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001016 case hprof_basic_boolean:
1017 __ AddU1(f->GetBoolean(klass));
1018 break;
1019 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001020 __ AddU2(f->GetChar(klass));
Andreas Gampe3a913092015-01-10 00:26:17 -08001021 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001022 case hprof_basic_short:
1023 __ AddU2(f->GetShort(klass));
1024 break;
1025 case hprof_basic_float:
1026 case hprof_basic_int:
1027 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001028 __ AddU4(f->Get32(klass));
1029 break;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001030 case hprof_basic_double:
1031 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001032 __ AddU8(f->Get64(klass));
1033 break;
1034 default:
1035 LOG(FATAL) << "Unexpected size " << size;
1036 UNREACHABLE();
1037 }
1038 }
1039 }
1040
1041 // Instance fields for this class (no superclass fields)
1042 int iFieldCount = klass->IsObjectClass() ? 0 : klass->NumInstanceFields();
Jeff Hao848f70a2014-01-15 13:49:50 -08001043 if (klass->IsStringClass()) {
1044 __ AddU2((uint16_t)iFieldCount + 1);
1045 } else {
1046 __ AddU2((uint16_t)iFieldCount);
1047 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001048 for (int i = 0; i < iFieldCount; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001049 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001050 __ AddStringId(LookupStringId(f->GetName()));
1051 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), nullptr);
1052 __ AddU1(t);
1053 }
Jeff Hao848f70a2014-01-15 13:49:50 -08001054 // Add native value character array for strings.
1055 if (klass->IsStringClass()) {
1056 __ AddStringId(LookupStringId("value"));
1057 __ AddU1(hprof_basic_object);
1058 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001059}
1060
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001061void Hprof::DumpHeapArray(mirror::Array* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001062 uint32_t length = obj->GetLength();
1063
1064 if (obj->IsObjectArray()) {
1065 // obj is an object array.
1066 __ AddU1(HPROF_OBJECT_ARRAY_DUMP);
1067
1068 __ AddObjectId(obj);
1069 __ AddU4(StackTraceSerialNumber(obj));
1070 __ AddU4(length);
1071 __ AddClassId(LookupClassId(klass));
1072
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001073 // Dump the elements, which are always objects or null.
Andreas Gampe3a913092015-01-10 00:26:17 -08001074 __ AddIdList(obj->AsObjectArray<mirror::Object>());
1075 } else {
1076 size_t size;
1077 HprofBasicType t = SignatureToBasicTypeAndSize(
1078 Primitive::Descriptor(klass->GetComponentType()->GetPrimitiveType()), &size);
1079
1080 // obj is a primitive array.
1081 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
1082
1083 __ AddObjectId(obj);
1084 __ AddU4(StackTraceSerialNumber(obj));
1085 __ AddU4(length);
1086 __ AddU1(t);
1087
1088 // Dump the raw, packed element values.
1089 if (size == 1) {
1090 __ AddU1List(reinterpret_cast<const uint8_t*>(obj->GetRawData(sizeof(uint8_t), 0)), length);
1091 } else if (size == 2) {
1092 __ AddU2List(reinterpret_cast<const uint16_t*>(obj->GetRawData(sizeof(uint16_t), 0)), length);
1093 } else if (size == 4) {
1094 __ AddU4List(reinterpret_cast<const uint32_t*>(obj->GetRawData(sizeof(uint32_t), 0)), length);
1095 } else if (size == 8) {
1096 __ AddU8List(reinterpret_cast<const uint64_t*>(obj->GetRawData(sizeof(uint64_t), 0)), length);
1097 }
1098 }
1099}
1100
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001101void Hprof::DumpHeapInstanceObject(mirror::Object* obj, mirror::Class* klass) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001102 // obj is an instance object.
1103 __ AddU1(HPROF_INSTANCE_DUMP);
1104 __ AddObjectId(obj);
1105 __ AddU4(StackTraceSerialNumber(obj));
1106 __ AddClassId(LookupClassId(klass));
1107
1108 // Reserve some space for the length of the instance data, which we won't
1109 // know until we're done writing it.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001110 size_t size_patch_offset = output_->Length();
Andreas Gampe3a913092015-01-10 00:26:17 -08001111 __ AddU4(0x77777777);
1112
1113 // Write the instance data; fields for this class, followed by super class fields,
1114 // and so on. Don't write the klass or monitor fields of Object.class.
Jeff Hao848f70a2014-01-15 13:49:50 -08001115 mirror::Class* orig_klass = klass;
Andreas Gampe3a913092015-01-10 00:26:17 -08001116 while (!klass->IsObjectClass()) {
1117 int ifieldCount = klass->NumInstanceFields();
1118 for (int i = 0; i < ifieldCount; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001119 ArtField* f = klass->GetInstanceField(i);
Andreas Gampe3a913092015-01-10 00:26:17 -08001120 size_t size;
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001121 auto t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
1122 switch (t) {
1123 case hprof_basic_byte:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001124 __ AddU1(f->GetByte(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001125 break;
1126 case hprof_basic_boolean:
1127 __ AddU1(f->GetBoolean(obj));
1128 break;
1129 case hprof_basic_char:
Mathieu Chartierff38c042015-03-06 11:33:36 -08001130 __ AddU2(f->GetChar(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001131 break;
1132 case hprof_basic_short:
1133 __ AddU2(f->GetShort(obj));
1134 break;
1135 case hprof_basic_float:
1136 case hprof_basic_int:
1137 case hprof_basic_object:
Andreas Gampe3a913092015-01-10 00:26:17 -08001138 __ AddU4(f->Get32(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001139 break;
1140 case hprof_basic_double:
1141 case hprof_basic_long:
Andreas Gampe3a913092015-01-10 00:26:17 -08001142 __ AddU8(f->Get64(obj));
Mathieu Chartier15f345c2015-03-06 12:45:44 -08001143 break;
Andreas Gampe3a913092015-01-10 00:26:17 -08001144 }
1145 }
1146
1147 klass = klass->GetSuperClass();
1148 }
1149
Jeff Hao848f70a2014-01-15 13:49:50 -08001150 // Output native value character array for strings.
1151 if (orig_klass->IsStringClass()) {
1152 mirror::String* s = obj->AsString();
Jeff Hao90bcbd52015-05-14 17:19:15 -07001153 mirror::Object* value;
1154 if (s->GetLength() == 0) {
1155 // If string is empty, use an object-aligned address within the string for the value.
1156 value = reinterpret_cast<mirror::Object*>(reinterpret_cast<uintptr_t>(s) + kObjectAlignment);
1157 } else {
1158 value = reinterpret_cast<mirror::Object*>(s->GetValue());
1159 }
1160 __ AddObjectId(value);
Jeff Hao848f70a2014-01-15 13:49:50 -08001161
1162 // Patch the instance field length.
1163 __ UpdateU4(size_patch_offset, output_->Length() - (size_patch_offset + 4));
1164
1165 __ AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
Jeff Hao90bcbd52015-05-14 17:19:15 -07001166 __ AddObjectId(value);
Jeff Hao848f70a2014-01-15 13:49:50 -08001167 __ AddU4(StackTraceSerialNumber(obj));
1168 __ AddU4(s->GetLength());
1169 __ AddU1(hprof_basic_char);
1170 __ AddU2List(s->GetValue(), s->GetLength());
1171 } else {
1172 // Patch the instance field length.
1173 __ UpdateU4(size_patch_offset, output_->Length() - (size_patch_offset + 4));
1174 }
Andreas Gampe3a913092015-01-10 00:26:17 -08001175}
1176
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001177void Hprof::VisitRoot(mirror::Object* obj, const RootInfo& info) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001178 static const HprofHeapTag xlate[] = {
1179 HPROF_ROOT_UNKNOWN,
1180 HPROF_ROOT_JNI_GLOBAL,
1181 HPROF_ROOT_JNI_LOCAL,
1182 HPROF_ROOT_JAVA_FRAME,
1183 HPROF_ROOT_NATIVE_STACK,
1184 HPROF_ROOT_STICKY_CLASS,
1185 HPROF_ROOT_THREAD_BLOCK,
1186 HPROF_ROOT_MONITOR_USED,
1187 HPROF_ROOT_THREAD_OBJECT,
1188 HPROF_ROOT_INTERNED_STRING,
1189 HPROF_ROOT_FINALIZING,
1190 HPROF_ROOT_DEBUGGER,
1191 HPROF_ROOT_REFERENCE_CLEANUP,
1192 HPROF_ROOT_VM_INTERNAL,
1193 HPROF_ROOT_JNI_MONITOR,
1194 };
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001195 CHECK_LT(info.GetType(), sizeof(xlate) / sizeof(HprofHeapTag));
Andreas Gampe3a913092015-01-10 00:26:17 -08001196 if (obj == nullptr) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001197 return;
1198 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001199 MarkRootObject(obj, 0, xlate[info.GetType()], info.GetThreadId());
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001200}
1201
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001202// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1203// sent directly to DDMS.
1204// If "fd" is >= 0, the output will be written to that file descriptor.
1205// Otherwise, "filename" is used to create an output file.
1206void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
Andreas Gampe3a913092015-01-10 00:26:17 -08001207 CHECK(filename != nullptr);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001208
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001209 Thread* self = Thread::Current();
1210 gc::Heap* heap = Runtime::Current()->GetHeap();
1211 if (heap->IsGcConcurrentAndMoving()) {
1212 // Need to take a heap dump while GC isn't running. See the
1213 // comment in Heap::VisitObjects().
1214 heap->IncrementDisableMovingGC(self);
1215 }
Mathieu Chartierbf9fc582015-03-13 17:21:25 -07001216 Runtime::Current()->GetThreadList()->SuspendAll(__FUNCTION__);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001217 Hprof hprof(filename, fd, direct_to_ddms);
1218 hprof.Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001219 Runtime::Current()->GetThreadList()->ResumeAll();
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001220 if (heap->IsGcConcurrentAndMoving()) {
1221 heap->DecrementDisableMovingGC(self);
1222 }
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001223}
1224
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001225} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001226} // namespace art