blob: 42d2610e3e08ff6aefff9ea1c70f47147df43b5b [file] [log] [blame]
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Preparation and completion of hprof data generation. The output is
19 * written into two files and then combined. This is necessary because
20 * we generate some of the data (strings and classes) while we dump the
21 * heap, and some analysis tools require that the class and string data
22 * appear first.
23 */
24
25#include "hprof.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080026
Elliott Hughes622a6982012-06-08 17:58:54 -070027#include <cutils/open_memstream.h>
28#include <errno.h>
29#include <fcntl.h>
30#include <stdio.h>
31#include <string.h>
32#include <sys/time.h>
33#include <sys/uio.h>
34#include <time.h>
35#include <time.h>
36#include <unistd.h>
37
38#include <set>
39
Elliott Hughes07ed66b2012-12-12 18:34:25 -080040#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080041#include "base/stringprintf.h"
Elliott Hughes76160052012-12-12 16:31:20 -080042#include "base/unix_file/fd_file.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080043#include "class_linker.h"
Ian Rogers62d6c772013-02-27 08:32:07 -080044#include "common_throws.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040045#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070046#include "dex_file-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070047#include "gc/accounting/heap_bitmap.h"
48#include "gc/heap.h"
49#include "gc/space/space.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070050#include "globals.h"
Mathieu Chartierad466ad2015-01-08 16:28:08 -080051#include "jdwp/jdwp.h"
52#include "jdwp/jdwp_priv.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070053#include "mirror/art_field-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "mirror/class.h"
55#include "mirror/class-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/object-inl.h"
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -070057#include "os.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070058#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070059#include "scoped_thread_state_change.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070060#include "thread_list.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040061
62namespace art {
63
64namespace hprof {
65
Mathieu Chartierad466ad2015-01-08 16:28:08 -080066static constexpr bool kDirectStream = true;
Jesse Wilson0c54ac12011-11-09 15:14:05 -050067
Elliott Hughes622a6982012-06-08 17:58:54 -070068#define HPROF_TIME 0
69#define HPROF_NULL_STACK_TRACE 0
70#define HPROF_NULL_THREAD 0
71
72#define U2_TO_BUF_BE(buf, offset, value) \
73 do { \
74 unsigned char* buf_ = (unsigned char*)(buf); \
Brian Carlstrom2d888622013-07-18 17:02:00 -070075 int offset_ = static_cast<int>(offset); \
Elliott Hughes622a6982012-06-08 17:58:54 -070076 uint16_t value_ = (uint16_t)(value); \
77 buf_[offset_ + 0] = (unsigned char)(value_ >> 8); \
78 buf_[offset_ + 1] = (unsigned char)(value_ ); \
79 } while (0)
80
81#define U4_TO_BUF_BE(buf, offset, value) \
82 do { \
83 unsigned char* buf_ = (unsigned char*)(buf); \
Brian Carlstrom2d888622013-07-18 17:02:00 -070084 int offset_ = static_cast<int>(offset); \
Elliott Hughes622a6982012-06-08 17:58:54 -070085 uint32_t value_ = (uint32_t)(value); \
86 buf_[offset_ + 0] = (unsigned char)(value_ >> 24); \
87 buf_[offset_ + 1] = (unsigned char)(value_ >> 16); \
88 buf_[offset_ + 2] = (unsigned char)(value_ >> 8); \
89 buf_[offset_ + 3] = (unsigned char)(value_ ); \
90 } while (0)
91
92#define U8_TO_BUF_BE(buf, offset, value) \
93 do { \
94 unsigned char* buf_ = (unsigned char*)(buf); \
Brian Carlstrom2d888622013-07-18 17:02:00 -070095 int offset_ = static_cast<int>(offset); \
Elliott Hughes622a6982012-06-08 17:58:54 -070096 uint64_t value_ = (uint64_t)(value); \
97 buf_[offset_ + 0] = (unsigned char)(value_ >> 56); \
98 buf_[offset_ + 1] = (unsigned char)(value_ >> 48); \
99 buf_[offset_ + 2] = (unsigned char)(value_ >> 40); \
100 buf_[offset_ + 3] = (unsigned char)(value_ >> 32); \
101 buf_[offset_ + 4] = (unsigned char)(value_ >> 24); \
102 buf_[offset_ + 5] = (unsigned char)(value_ >> 16); \
103 buf_[offset_ + 6] = (unsigned char)(value_ >> 8); \
104 buf_[offset_ + 7] = (unsigned char)(value_ ); \
105 } while (0)
106
107enum HprofTag {
108 HPROF_TAG_STRING = 0x01,
109 HPROF_TAG_LOAD_CLASS = 0x02,
110 HPROF_TAG_UNLOAD_CLASS = 0x03,
111 HPROF_TAG_STACK_FRAME = 0x04,
112 HPROF_TAG_STACK_TRACE = 0x05,
113 HPROF_TAG_ALLOC_SITES = 0x06,
114 HPROF_TAG_HEAP_SUMMARY = 0x07,
115 HPROF_TAG_START_THREAD = 0x0A,
116 HPROF_TAG_END_THREAD = 0x0B,
117 HPROF_TAG_HEAP_DUMP = 0x0C,
118 HPROF_TAG_HEAP_DUMP_SEGMENT = 0x1C,
119 HPROF_TAG_HEAP_DUMP_END = 0x2C,
120 HPROF_TAG_CPU_SAMPLES = 0x0D,
121 HPROF_TAG_CONTROL_SETTINGS = 0x0E,
122};
123
124// Values for the first byte of HEAP_DUMP and HEAP_DUMP_SEGMENT records:
125enum HprofHeapTag {
126 // Traditional.
127 HPROF_ROOT_UNKNOWN = 0xFF,
128 HPROF_ROOT_JNI_GLOBAL = 0x01,
129 HPROF_ROOT_JNI_LOCAL = 0x02,
130 HPROF_ROOT_JAVA_FRAME = 0x03,
131 HPROF_ROOT_NATIVE_STACK = 0x04,
132 HPROF_ROOT_STICKY_CLASS = 0x05,
133 HPROF_ROOT_THREAD_BLOCK = 0x06,
134 HPROF_ROOT_MONITOR_USED = 0x07,
135 HPROF_ROOT_THREAD_OBJECT = 0x08,
136 HPROF_CLASS_DUMP = 0x20,
137 HPROF_INSTANCE_DUMP = 0x21,
138 HPROF_OBJECT_ARRAY_DUMP = 0x22,
139 HPROF_PRIMITIVE_ARRAY_DUMP = 0x23,
140
141 // Android.
142 HPROF_HEAP_DUMP_INFO = 0xfe,
143 HPROF_ROOT_INTERNED_STRING = 0x89,
144 HPROF_ROOT_FINALIZING = 0x8a, // Obsolete.
145 HPROF_ROOT_DEBUGGER = 0x8b,
146 HPROF_ROOT_REFERENCE_CLEANUP = 0x8c, // Obsolete.
147 HPROF_ROOT_VM_INTERNAL = 0x8d,
148 HPROF_ROOT_JNI_MONITOR = 0x8e,
149 HPROF_UNREACHABLE = 0x90, // Obsolete.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700150 HPROF_PRIMITIVE_ARRAY_NODATA_DUMP = 0xc3, // Obsolete.
Elliott Hughes622a6982012-06-08 17:58:54 -0700151};
152
153enum HprofHeapId {
154 HPROF_HEAP_DEFAULT = 0,
155 HPROF_HEAP_ZYGOTE = 'Z',
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700156 HPROF_HEAP_APP = 'A',
157 HPROF_HEAP_IMAGE = 'I',
Elliott Hughes622a6982012-06-08 17:58:54 -0700158};
159
160enum HprofBasicType {
161 hprof_basic_object = 2,
162 hprof_basic_boolean = 4,
163 hprof_basic_char = 5,
164 hprof_basic_float = 6,
165 hprof_basic_double = 7,
166 hprof_basic_byte = 8,
167 hprof_basic_short = 9,
168 hprof_basic_int = 10,
169 hprof_basic_long = 11,
170};
171
Ian Rogersef7d42f2014-01-06 12:55:46 -0800172typedef uint32_t HprofStringId;
173typedef uint32_t HprofClassObjectId;
Elliott Hughes622a6982012-06-08 17:58:54 -0700174
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800175class Hprof;
176
Elliott Hughes622a6982012-06-08 17:58:54 -0700177// Represents a top-level hprof record, whose serialized format is:
178// U1 TAG: denoting the type of the record
179// U4 TIME: number of microseconds since the time stamp in the header
180// U4 LENGTH: number of bytes that follow this uint32_t field and belong to this record
181// U1* BODY: as many bytes as specified in the above uint32_t field
182class HprofRecord {
183 public:
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800184 explicit HprofRecord(Hprof* hprof) : alloc_length_(128), fp_(nullptr), tag_(0), time_(0),
185 length_(0), dirty_(false), hprof_(hprof) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700186 body_ = reinterpret_cast<unsigned char*>(malloc(alloc_length_));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700187 }
188
189 ~HprofRecord() {
190 free(body_);
191 }
192
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800193 // Returns how many characters were in the buffer (or written).
194 size_t StartNewRecord(FILE* fp, uint8_t tag, uint32_t time) WARN_UNUSED {
195 const size_t ret = Flush();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700196 fp_ = fp;
197 tag_ = tag;
198 time_ = time;
199 length_ = 0;
200 dirty_ = true;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800201 return ret;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700202 }
203
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800204 // Returns how many characters were in the buffer (or written).
205 size_t Flush() WARN_UNUSED;
Elliott Hughes622a6982012-06-08 17:58:54 -0700206
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800207 void AddU1(uint8_t value);
Elliott Hughes622a6982012-06-08 17:58:54 -0700208
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800209 void AddU2(uint16_t value) {
210 AddU2List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700211 }
212
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800213 void AddU4(uint32_t value) {
214 AddU4List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700215 }
216
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800217 void AddU8(uint64_t value) {
218 AddU8List(&value, 1);
Elliott Hughes622a6982012-06-08 17:58:54 -0700219 }
220
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800221 void AddObjectId(const mirror::Object* value) {
222 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800223 }
224
225 // The ID for the synthetic object generated to account for class static overhead.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800226 void AddClassStaticsId(const mirror::Class* value) {
227 AddU4(1 | PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800228 }
229
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800230 void AddJniGlobalRefId(jobject value) {
231 AddU4(PointerToLowMemUInt32(value));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800232 }
233
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800234 void AddClassId(HprofClassObjectId value) {
235 AddU4(value);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800236 }
237
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800238 void AddStringId(HprofStringId value) {
239 AddU4(value);
Elliott Hughes622a6982012-06-08 17:58:54 -0700240 }
241
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800242 void AddU1List(const uint8_t* values, size_t numValues);
243 void AddU2List(const uint16_t* values, size_t numValues);
244 void AddU4List(const uint32_t* values, size_t numValues);
245 void UpdateU4(size_t offset, uint32_t new_value);
246 void AddU8List(const uint64_t* values, size_t numValues);
Elliott Hughes622a6982012-06-08 17:58:54 -0700247
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800248 void AddIdList(mirror::ObjectArray<mirror::Object>* values)
Ian Rogersef7d42f2014-01-06 12:55:46 -0800249 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800250 const int32_t length = values->GetLength();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800251 for (int32_t i = 0; i < length; ++i) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800252 AddObjectId(values->GetWithoutChecks(i));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800253 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700254 }
255
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800256 void AddUtf8String(const char* str) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700257 // The terminating NUL character is NOT written.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800258 AddU1List((const uint8_t*)str, strlen(str));
Elliott Hughes622a6982012-06-08 17:58:54 -0700259 }
260
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700261 size_t Size() const {
262 return length_;
263 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700264
265 private:
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800266 void GuaranteeRecordAppend(size_t nmore) {
267 const size_t min_size = length_ + nmore;
268 if (min_size > alloc_length_) {
269 const size_t new_alloc_len = std::max(alloc_length_ * 2, min_size);
270 body_ = (unsigned char*)realloc(body_, new_alloc_len);
271 CHECK(body_ != nullptr);
272 alloc_length_ = new_alloc_len;
Elliott Hughes622a6982012-06-08 17:58:54 -0700273 }
Elliott Hughes622a6982012-06-08 17:58:54 -0700274 CHECK_LE(length_ + nmore, alloc_length_);
Elliott Hughes622a6982012-06-08 17:58:54 -0700275 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700276
277 size_t alloc_length_;
278 unsigned char* body_;
279
280 FILE* fp_;
281 uint8_t tag_;
282 uint32_t time_;
283 size_t length_;
284 bool dirty_;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800285 Hprof* hprof_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700286
287 DISALLOW_COPY_AND_ASSIGN(HprofRecord);
Elliott Hughes622a6982012-06-08 17:58:54 -0700288};
289
290class Hprof {
291 public:
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700292 Hprof(const char* output_filename, int fd, bool direct_to_ddms)
293 : filename_(output_filename),
294 fd_(fd),
295 direct_to_ddms_(direct_to_ddms),
296 start_ns_(NanoTime()),
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800297 current_record_(this),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700298 gc_thread_serial_number_(0),
299 gc_scan_state_(0),
300 current_heap_(HPROF_HEAP_DEFAULT),
301 objects_in_segment_(0),
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800302 header_fp_(nullptr),
303 header_data_ptr_(nullptr),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700304 header_data_size_(0),
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800305 body_fp_(nullptr),
306 body_data_ptr_(nullptr),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700307 body_data_size_(0),
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800308 net_state_(nullptr),
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700309 next_string_id_(0x400000) {
310 LOG(INFO) << "hprof: heap dump \"" << filename_ << "\" starting...";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500311 }
312
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700313 ~Hprof() {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800314 if (header_fp_ != nullptr) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700315 fclose(header_fp_);
316 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800317 if (body_fp_ != nullptr) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700318 fclose(body_fp_);
319 }
320 free(header_data_ptr_);
321 free(body_data_ptr_);
322 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500323
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800324 void ProcessBody() EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
325 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
326 Runtime* runtime = Runtime::Current();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700327 // Walk the roots and the heap.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800328 total_body_bytes_ += current_record_.StartNewRecord(body_fp_, HPROF_TAG_HEAP_DUMP_SEGMENT,
329 HPROF_TIME);
330 runtime->VisitRoots(RootVisitor, this);
331 runtime->GetHeap()->VisitObjects(VisitObjectCallback, this);
332 total_body_bytes_ += current_record_.StartNewRecord(body_fp_, HPROF_TAG_HEAP_DUMP_END,
333 HPROF_TIME);
334 total_body_bytes_ += current_record_.Flush();
335 if (allow_writing_) {
336 fflush(body_fp_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700337 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800338 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500339
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800340 void ProcessHeader() EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700341 // Write the header.
342 WriteFixedHeader();
343 // Write the string and class tables, and any stack traces, to the header.
344 // (jhat requires that these appear before any of the data in the body that refers to them.)
345 WriteStringTable();
346 WriteClassTable();
347 WriteStackTraces();
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800348 total_header_bytes_ += current_record_.Flush();
349 if (allow_writing_) {
350 fflush(header_fp_);
351 }
352 }
353
354 void ProcessHeapStreaming(size_t data_len, uint32_t chunk_type)
355 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
356 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
357 total_body_bytes_ = 0;
358 total_header_bytes_ = 0;
359 allow_writing_ = true;
360 CHECK(direct_to_ddms_);
361 JDWP::JdwpState* state = Dbg::GetJdwpState();
362 CHECK(state != nullptr);
363 net_state_ = state->netState;
364 CHECK(net_state_ != nullptr);
365 // Hold the socket lock for the whole tiem since we want this to be atomic.
366 MutexLock mu(Thread::Current(), *net_state_->GetSocketLock());
367 total_body_bytes_ = 0;
368 total_header_bytes_ = 0;
369 constexpr size_t kChunkHeaderSize = kJDWPHeaderLen + 8;
370 uint8_t chunk_header[kChunkHeaderSize] = { 0 };
371 state->SetupChunkHeader(chunk_type, data_len, kChunkHeaderSize, chunk_header);
372 Write(chunk_header, kChunkHeaderSize, nullptr); // Send the header chunk to DDMS.
373 ProcessHeader();
374 ProcessBody();
375 CHECK_EQ(total_body_bytes_ + total_header_bytes_, data_len);
376 net_state_ = nullptr;
377 }
378 void ProcessHeap(bool allow_writing) EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
379 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
380 allow_writing_ = allow_writing;
381 total_body_bytes_ = 0;
382 total_header_bytes_ = 0;
383 if (allow_writing) {
384 header_fp_ = open_memstream(&header_data_ptr_, &header_data_size_);
385 CHECK(header_fp_ != nullptr) << "header open_memstream failed";
386 body_fp_ = open_memstream(&body_data_ptr_, &body_data_size_);
387 CHECK(body_fp_ != nullptr) << "body open_memstream failed";
388 }
389 ProcessBody();
390 ProcessHeader();
391 }
392
393 void Dump() EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_)
394 LOCKS_EXCLUDED(Locks::heap_bitmap_lock_) {
395 {
396 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
397 // First pass to measure the size of the dump.
398 ProcessHeap(false);
399 const size_t header_bytes = total_header_bytes_;
400 const size_t body_bytes = total_body_bytes_;
401 if (direct_to_ddms_ && kDirectStream) {
402 ProcessHeapStreaming(header_bytes + body_bytes, CHUNK_TYPE("HPDS"));
403 } else {
404 ProcessHeap(true);
405 CHECK_EQ(header_data_size_, header_bytes);
406 CHECK_EQ(body_data_size_, body_bytes);
407 }
408 CHECK_EQ(total_header_bytes_, header_bytes);
409 CHECK_EQ(total_body_bytes_, body_bytes);
410 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700411
412 bool okay = true;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800413 if (!kDirectStream) {
414 if (direct_to_ddms_) {
415 // Send the data off to DDMS.
416 iovec iov[2];
417 iov[0].iov_base = header_data_ptr_;
418 iov[0].iov_len = header_data_size_;
419 iov[1].iov_base = body_data_ptr_;
420 iov[1].iov_len = body_data_size_;
421 Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700422 } else {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800423 // Where exactly are we writing to?
424 int out_fd;
425 if (fd_ >= 0) {
426 out_fd = dup(fd_);
427 if (out_fd < 0) {
428 ThrowRuntimeException("Couldn't dump heap; dup(%d) failed: %s", fd_, strerror(errno));
429 return;
430 }
431 } else {
432 out_fd = open(filename_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
433 if (out_fd < 0) {
434 ThrowRuntimeException("Couldn't dump heap; open(\"%s\") failed: %s", filename_.c_str(),
435 strerror(errno));
436 return;
437 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700438 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700439
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800440 std::unique_ptr<File> file(new File(out_fd, filename_, true));
441 okay = file->WriteFully(header_data_ptr_, header_data_size_) &&
442 file->WriteFully(body_data_ptr_, body_data_size_);
443 if (okay) {
444 okay = file->FlushCloseOrErase() == 0;
445 } else {
446 file->Erase();
447 }
448 if (!okay) {
449 std::string msg(StringPrintf("Couldn't dump heap; writing \"%s\" failed: %s",
450 filename_.c_str(), strerror(errno)));
451 ThrowRuntimeException("%s", msg.c_str());
452 LOG(ERROR) << msg;
453 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700454 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700455 }
456
457 // Throw out a log message for the benefit of "runhat".
458 if (okay) {
459 uint64_t duration = NanoTime() - start_ns_;
Ian Rogers50b35e22012-10-04 10:09:15 -0700460 LOG(INFO) << "hprof: heap dump completed ("
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800461 << PrettySize(total_header_bytes_ + total_body_bytes_ + 1023)
Ian Rogers50b35e22012-10-04 10:09:15 -0700462 << ") in " << PrettyDuration(duration);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700463 }
464 }
465
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800466 bool AllowWriting() const {
467 return allow_writing_;
468 }
469
470 size_t Write(const void* ptr, size_t len, FILE* fp) {
471 if (allow_writing_) {
472 if (net_state_ != nullptr) {
473 CHECK(fp == nullptr);
474 std::vector<iovec> iov;
475 iov.push_back(iovec());
476 iov[0].iov_base = const_cast<void*>(ptr);
477 iov[0].iov_len = len;
478 net_state_->WriteBufferedPacketLocked(iov);
479 } else {
480 const size_t n = fwrite(ptr, 1, len, fp);
481 CHECK_EQ(n, len);
482 }
483 }
484 return len;
485 }
486
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700487 private:
Mathieu Chartier815873e2014-02-13 18:02:13 -0800488 static void RootVisitor(mirror::Object** obj, void* arg, uint32_t thread_id, RootType root_type)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700489 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier815873e2014-02-13 18:02:13 -0800490 DCHECK(arg != nullptr);
491 DCHECK(obj != nullptr);
492 DCHECK(*obj != nullptr);
493 reinterpret_cast<Hprof*>(arg)->VisitRoot(*obj, thread_id, root_type);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700494 }
495
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800496 static void VisitObjectCallback(mirror::Object* obj, void* arg)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700497 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800498 DCHECK(obj != nullptr);
499 DCHECK(arg != nullptr);
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800500 reinterpret_cast<Hprof*>(arg)->DumpHeapObject(obj);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700501 }
502
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800503 void VisitRoot(const mirror::Object* obj, uint32_t thread_id, RootType type)
504 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700505
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800506 int DumpHeapObject(mirror::Object* obj) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700507
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800508 void WriteClassTable() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700509 HprofRecord* rec = &current_record_;
510 uint32_t nextSerialNumber = 1;
511
Ian Rogersef7d42f2014-01-06 12:55:46 -0800512 for (mirror::Class* c : classes_) {
513 CHECK(c != nullptr);
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800514 total_header_bytes_ += current_record_.StartNewRecord(header_fp_, HPROF_TAG_LOAD_CLASS,
515 HPROF_TIME);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700516 // LOAD CLASS format:
517 // U4: class serial number (always > 0)
518 // ID: class object ID. We use the address of the class object structure as its ID.
519 // U4: stack trace serial number
520 // ID: class name string ID
521 rec->AddU4(nextSerialNumber++);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800522 rec->AddObjectId(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700523 rec->AddU4(HPROF_NULL_STACK_TRACE);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800524 rec->AddStringId(LookupClassNameId(c));
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700525 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700526 }
527
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800528 void WriteStringTable() {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700529 HprofRecord* rec = &current_record_;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800530 for (const std::pair<std::string, HprofStringId>& p : strings_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800531 const std::string& string = p.first;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800532 const size_t id = p.second;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700533
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800534 total_header_bytes_ += current_record_.StartNewRecord(header_fp_, HPROF_TAG_STRING,
535 HPROF_TIME);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700536
537 // STRING format:
538 // ID: ID for this string
539 // U1*: UTF8 characters for string (NOT NULL terminated)
540 // (the record format encodes the length)
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800541 rec->AddU4(id);
542 rec->AddUtf8String(string.c_str());
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700543 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700544 }
545
546 void StartNewHeapDumpSegment() {
547 // This flushes the old segment and starts a new one.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800548 total_body_bytes_ += current_record_.StartNewRecord(body_fp_, HPROF_TAG_HEAP_DUMP_SEGMENT,
549 HPROF_TIME);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700550 objects_in_segment_ = 0;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700551 // Starting a new HEAP_DUMP resets the heap to default.
552 current_heap_ = HPROF_HEAP_DEFAULT;
553 }
554
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800555 int MarkRootObject(const mirror::Object* obj, jobject jniObj);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700556
Ian Rogersef7d42f2014-01-06 12:55:46 -0800557 HprofClassObjectId LookupClassId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800558 if (c != nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800559 auto result = classes_.insert(c);
560 const mirror::Class* present = *result.first;
561 CHECK_EQ(present, c);
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800562 // Make sure that we've assigned a string ID for this class' name
563 LookupClassNameId(c);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800564 }
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800565 return PointerToLowMemUInt32(c);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700566 }
567
Ian Rogersef7d42f2014-01-06 12:55:46 -0800568 HprofStringId LookupStringId(mirror::String* string) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700569 return LookupStringId(string->ToModifiedUtf8());
570 }
571
572 HprofStringId LookupStringId(const char* string) {
573 return LookupStringId(std::string(string));
574 }
575
576 HprofStringId LookupStringId(const std::string& string) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800577 auto it = strings_.find(string);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700578 if (it != strings_.end()) {
579 return it->second;
580 }
581 HprofStringId id = next_string_id_++;
582 strings_.Put(string, id);
583 return id;
584 }
585
Ian Rogersef7d42f2014-01-06 12:55:46 -0800586 HprofStringId LookupClassNameId(mirror::Class* c) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700587 return LookupStringId(PrettyDescriptor(c));
588 }
589
590 void WriteFixedHeader() {
Elliott Hughes622a6982012-06-08 17:58:54 -0700591 char magic[] = "JAVA PROFILE 1.0.3";
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800592 unsigned char buf[4] = { 0 };
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500593 // Write the file header.
594 // U1: NUL-terminated magic string.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800595 total_header_bytes_ += Write(magic, sizeof(magic), header_fp_);
Calin Juravle32805172014-07-04 16:24:03 +0100596 // U4: size of identifiers. We're using addresses as IDs and our heap references are stored
597 // as uint32_t.
598 // Note of warning: hprof-conv hard-codes the size of identifiers to 4.
Andreas Gampe575e78c2014-11-03 23:41:03 -0800599 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == sizeof(uint32_t),
600 "Unexpected HeapReference size");
Calin Juravle32805172014-07-04 16:24:03 +0100601 U4_TO_BUF_BE(buf, 0, sizeof(uint32_t));
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800602 total_header_bytes_ += Write(buf, sizeof(uint32_t), header_fp_);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500603 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700604 timeval now;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800605 const uint64_t nowMs = (gettimeofday(&now, NULL) < 0) ? 0 :
606 (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500607 // U4: high word of the 64-bit time.
608 U4_TO_BUF_BE(buf, 0, (uint32_t)(nowMs >> 32));
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800609 total_header_bytes_ += Write(buf, sizeof(uint32_t), header_fp_);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500610 // U4: low word of the 64-bit time.
611 U4_TO_BUF_BE(buf, 0, (uint32_t)(nowMs & 0xffffffffULL));
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800612 total_header_bytes_ += Write(buf, sizeof(uint32_t), header_fp_); // xxx fix the time
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500613 }
614
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700615 void WriteStackTraces() {
616 // Write a dummy stack trace record so the analysis tools don't freak out.
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800617 total_header_bytes_ +=
618 current_record_.StartNewRecord(header_fp_, HPROF_TAG_STACK_TRACE, HPROF_TIME);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700619 current_record_.AddU4(HPROF_NULL_STACK_TRACE);
620 current_record_.AddU4(HPROF_NULL_THREAD);
621 current_record_.AddU4(0); // no frames
622 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500623
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700624 // If direct_to_ddms_ is set, "filename_" and "fd" will be ignored.
625 // Otherwise, "filename_" must be valid, though if "fd" >= 0 it will
626 // only be used for debug messages.
627 std::string filename_;
628 int fd_;
629 bool direct_to_ddms_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500630
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800631 // Whether or not we are in the size calculating mode or writing mode.
632 bool allow_writing_;
633
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700634 uint64_t start_ns_;
635
636 HprofRecord current_record_;
637
638 uint32_t gc_thread_serial_number_;
639 uint8_t gc_scan_state_;
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700640 HprofHeapId current_heap_; // Which heap we're currently dumping.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700641 size_t objects_in_segment_;
642
643 FILE* header_fp_;
644 char* header_data_ptr_;
645 size_t header_data_size_;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800646 size_t total_header_bytes_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700647
648 FILE* body_fp_;
649 char* body_data_ptr_;
650 size_t body_data_size_;
Mathieu Chartierad466ad2015-01-08 16:28:08 -0800651 size_t total_body_bytes_;
652
653 JDWP::JdwpNetStateBase* net_state_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700654
Ian Rogersef7d42f2014-01-06 12:55:46 -0800655 std::set<mirror::Class*> classes_;
656 HprofStringId next_string_id_;
657 SafeMap<std::string, HprofStringId> strings_;
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700658
659 DISALLOW_COPY_AND_ASSIGN(Hprof);
660};
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500661
662#define OBJECTS_PER_SEGMENT ((size_t)128)
663#define BYTES_PER_SEGMENT ((size_t)4096)
664
Ian Rogersef7d42f2014-01-06 12:55:46 -0800665// The static field-name for the synthetic object generated to account for class static overhead.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500666#define STATIC_OVERHEAD_NAME "$staticOverhead"
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500667
Elliott Hughes622a6982012-06-08 17:58:54 -0700668static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* sizeOut) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500669 char c = sig[0];
670 HprofBasicType ret;
671 size_t size;
672
673 switch (c) {
674 case '[':
675 case 'L': ret = hprof_basic_object; size = 4; break;
676 case 'Z': ret = hprof_basic_boolean; size = 1; break;
677 case 'C': ret = hprof_basic_char; size = 2; break;
678 case 'F': ret = hprof_basic_float; size = 4; break;
679 case 'D': ret = hprof_basic_double; size = 8; break;
680 case 'B': ret = hprof_basic_byte; size = 1; break;
681 case 'S': ret = hprof_basic_short; size = 2; break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500682 case 'I': ret = hprof_basic_int; size = 4; break;
683 case 'J': ret = hprof_basic_long; size = 8; break;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700684 default: LOG(FATAL) << "UNREACHABLE"; UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500685 }
686
687 if (sizeOut != NULL) {
688 *sizeOut = size;
689 }
690
691 return ret;
692}
693
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700694static HprofBasicType PrimitiveToBasicTypeAndSize(Primitive::Type prim, size_t* sizeOut) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500695 HprofBasicType ret;
696 size_t size;
697
698 switch (prim) {
699 case Primitive::kPrimBoolean: ret = hprof_basic_boolean; size = 1; break;
700 case Primitive::kPrimChar: ret = hprof_basic_char; size = 2; break;
701 case Primitive::kPrimFloat: ret = hprof_basic_float; size = 4; break;
702 case Primitive::kPrimDouble: ret = hprof_basic_double; size = 8; break;
703 case Primitive::kPrimByte: ret = hprof_basic_byte; size = 1; break;
704 case Primitive::kPrimShort: ret = hprof_basic_short; size = 2; break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500705 case Primitive::kPrimInt: ret = hprof_basic_int; size = 4; break;
706 case Primitive::kPrimLong: ret = hprof_basic_long; size = 8; break;
Ian Rogersfc787ec2014-10-09 21:56:44 -0700707 default: LOG(FATAL) << "UNREACHABLE"; UNREACHABLE();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500708 }
709
710 if (sizeOut != NULL) {
711 *sizeOut = size;
712 }
713
714 return ret;
715}
716
717// Always called when marking objects, but only does
718// something when ctx->gc_scan_state_ is non-zero, which is usually
719// only true when marking the root set or unreachable
720// objects. Used to add rootset references to obj.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800721int Hprof::MarkRootObject(const mirror::Object* obj, jobject jniObj) {
Elliott Hughes73e66f72012-05-09 09:34:45 -0700722 HprofRecord* rec = &current_record_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500723 HprofHeapTag heapTag = (HprofHeapTag)gc_scan_state_;
724
725 if (heapTag == 0) {
726 return 0;
727 }
728
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700729 if (objects_in_segment_ >= OBJECTS_PER_SEGMENT || rec->Size() >= BYTES_PER_SEGMENT) {
730 StartNewHeapDumpSegment();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500731 }
732
733 switch (heapTag) {
734 // ID: object ID
735 case HPROF_ROOT_UNKNOWN:
736 case HPROF_ROOT_STICKY_CLASS:
737 case HPROF_ROOT_MONITOR_USED:
738 case HPROF_ROOT_INTERNED_STRING:
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500739 case HPROF_ROOT_DEBUGGER:
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500740 case HPROF_ROOT_VM_INTERNAL:
741 rec->AddU1(heapTag);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800742 rec->AddObjectId(obj);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500743 break;
744
745 // ID: object ID
746 // ID: JNI global ref ID
747 case HPROF_ROOT_JNI_GLOBAL:
748 rec->AddU1(heapTag);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800749 rec->AddObjectId(obj);
750 rec->AddJniGlobalRefId(jniObj);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500751 break;
752
753 // ID: object ID
754 // U4: thread serial number
755 // U4: frame number in stack trace (-1 for empty)
756 case HPROF_ROOT_JNI_LOCAL:
757 case HPROF_ROOT_JNI_MONITOR:
758 case HPROF_ROOT_JAVA_FRAME:
759 rec->AddU1(heapTag);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800760 rec->AddObjectId(obj);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500761 rec->AddU4(gc_thread_serial_number_);
762 rec->AddU4((uint32_t)-1);
763 break;
764
765 // ID: object ID
766 // U4: thread serial number
767 case HPROF_ROOT_NATIVE_STACK:
768 case HPROF_ROOT_THREAD_BLOCK:
769 rec->AddU1(heapTag);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800770 rec->AddObjectId(obj);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500771 rec->AddU4(gc_thread_serial_number_);
772 break;
773
774 // ID: thread object ID
775 // U4: thread serial number
776 // U4: stack trace serial number
777 case HPROF_ROOT_THREAD_OBJECT:
778 rec->AddU1(heapTag);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800779 rec->AddObjectId(obj);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500780 rec->AddU4(gc_thread_serial_number_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700781 rec->AddU4((uint32_t)-1); // xxx
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500782 break;
783
Elliott Hughes73e66f72012-05-09 09:34:45 -0700784 case HPROF_CLASS_DUMP:
785 case HPROF_INSTANCE_DUMP:
786 case HPROF_OBJECT_ARRAY_DUMP:
787 case HPROF_PRIMITIVE_ARRAY_DUMP:
788 case HPROF_HEAP_DUMP_INFO:
789 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
790 // Ignored.
791 break;
792
793 case HPROF_ROOT_FINALIZING:
794 case HPROF_ROOT_REFERENCE_CLEANUP:
795 case HPROF_UNREACHABLE:
796 LOG(FATAL) << "obsolete tag " << static_cast<int>(heapTag);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500797 break;
798 }
799
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700800 ++objects_in_segment_;
Elliott Hughes73e66f72012-05-09 09:34:45 -0700801 return 0;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500802}
803
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800804static int StackTraceSerialNumber(const mirror::Object* /*obj*/) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500805 return HPROF_NULL_STACK_TRACE;
806}
807
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800808int Hprof::DumpHeapObject(mirror::Object* obj) {
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700809 HprofRecord* rec = &current_record_;
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700810 gc::space::ContinuousSpace* space =
811 Runtime::Current()->GetHeap()->FindContinuousSpaceFromObject(obj, true);
812 HprofHeapId heap_type = HPROF_HEAP_APP;
813 if (space != nullptr) {
814 if (space->IsZygoteSpace()) {
815 heap_type = HPROF_HEAP_ZYGOTE;
816 } else if (space->IsImageSpace()) {
817 heap_type = HPROF_HEAP_IMAGE;
818 }
819 }
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700820 if (objects_in_segment_ >= OBJECTS_PER_SEGMENT || rec->Size() >= BYTES_PER_SEGMENT) {
821 StartNewHeapDumpSegment();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500822 }
823
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700824 if (heap_type != current_heap_) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500825 HprofStringId nameId;
826
827 // This object is in a different heap than the current one.
828 // Emit a HEAP_DUMP_INFO tag to change heaps.
829 rec->AddU1(HPROF_HEAP_DUMP_INFO);
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700830 rec->AddU4(static_cast<uint32_t>(heap_type)); // uint32_t: heap type
831 switch (heap_type) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500832 case HPROF_HEAP_APP:
833 nameId = LookupStringId("app");
834 break;
835 case HPROF_HEAP_ZYGOTE:
836 nameId = LookupStringId("zygote");
837 break;
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700838 case HPROF_HEAP_IMAGE:
839 nameId = LookupStringId("image");
840 break;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500841 default:
842 // Internal error
843 LOG(ERROR) << "Unexpected desiredHeap";
844 nameId = LookupStringId("<ILLEGAL>");
845 break;
846 }
Ian Rogersef7d42f2014-01-06 12:55:46 -0800847 rec->AddStringId(nameId);
Mathieu Chartierae1ad002014-07-18 17:58:22 -0700848 current_heap_ = heap_type;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500849 }
850
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800851 mirror::Class* c = obj->GetClass();
Elliott Hughese84278b2012-03-22 10:06:53 -0700852 if (c == NULL) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500853 // This object will bother HprofReader, because it has a NULL
854 // class, so just don't dump it. It could be
855 // gDvm.unlinkedJavaLangClass or it could be an object just
856 // allocated which hasn't been initialized yet.
857 } else {
858 if (obj->IsClass()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800859 mirror::Class* thisClass = obj->AsClass();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500860 // obj is a ClassObject.
861 size_t sFieldCount = thisClass->NumStaticFields();
862 if (sFieldCount != 0) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800863 int byteLength = sFieldCount * sizeof(JValue); // TODO bogus; fields are packed
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500864 // Create a byte array to reflect the allocation of the
865 // StaticField array at the end of this class.
866 rec->AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800867 rec->AddClassStaticsId(thisClass);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500868 rec->AddU4(StackTraceSerialNumber(obj));
869 rec->AddU4(byteLength);
870 rec->AddU1(hprof_basic_byte);
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700871 for (int i = 0; i < byteLength; ++i) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500872 rec->AddU1(0);
873 }
874 }
875
876 rec->AddU1(HPROF_CLASS_DUMP);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800877 rec->AddClassId(LookupClassId(thisClass));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500878 rec->AddU4(StackTraceSerialNumber(thisClass));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800879 rec->AddClassId(LookupClassId(thisClass->GetSuperClass()));
880 rec->AddObjectId(thisClass->GetClassLoader());
881 rec->AddObjectId(nullptr); // no signer
882 rec->AddObjectId(nullptr); // no prot domain
883 rec->AddObjectId(nullptr); // reserved
884 rec->AddObjectId(nullptr); // reserved
Elliott Hughesdbb40792011-11-18 17:05:22 -0800885 if (thisClass->IsClassClass()) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500886 // ClassObjects have their static fields appended, so aren't all the same size.
887 // But they're at least this size.
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700888 rec->AddU4(sizeof(mirror::Class)); // instance size
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500889 } else if (thisClass->IsArrayClass() || thisClass->IsPrimitive()) {
890 rec->AddU4(0);
891 } else {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700892 rec->AddU4(thisClass->GetObjectSize()); // instance size
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500893 }
894
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700895 rec->AddU2(0); // empty const pool
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500896
897 // Static fields
898 if (sFieldCount == 0) {
899 rec->AddU2((uint16_t)0);
900 } else {
901 rec->AddU2((uint16_t)(sFieldCount+1));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800902 rec->AddStringId(LookupStringId(STATIC_OVERHEAD_NAME));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500903 rec->AddU1(hprof_basic_object);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800904 rec->AddClassStaticsId(thisClass);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500905
906 for (size_t i = 0; i < sFieldCount; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700907 mirror::ArtField* f = thisClass->GetStaticField(i);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500908
909 size_t size;
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700910 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
911 rec->AddStringId(LookupStringId(f->GetName()));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500912 rec->AddU1(t);
913 if (size == 1) {
Ian Rogersa3b59cb2013-03-19 19:50:20 -0700914 rec->AddU1(static_cast<uint8_t>(f->Get32(thisClass)));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500915 } else if (size == 2) {
Ian Rogersa3b59cb2013-03-19 19:50:20 -0700916 rec->AddU2(static_cast<uint16_t>(f->Get32(thisClass)));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500917 } else if (size == 4) {
Ian Rogersa3b59cb2013-03-19 19:50:20 -0700918 rec->AddU4(f->Get32(thisClass));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500919 } else if (size == 8) {
Ian Rogersa3b59cb2013-03-19 19:50:20 -0700920 rec->AddU8(f->Get64(thisClass));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500921 } else {
922 CHECK(false);
923 }
924 }
925 }
926
927 // Instance fields for this class (no superclass fields)
928 int iFieldCount = thisClass->IsObjectClass() ? 0 : thisClass->NumInstanceFields();
929 rec->AddU2((uint16_t)iFieldCount);
930 for (int i = 0; i < iFieldCount; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700931 mirror::ArtField* f = thisClass->GetInstanceField(i);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700932 HprofBasicType t = SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), NULL);
933 rec->AddStringId(LookupStringId(f->GetName()));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500934 rec->AddU1(t);
935 }
Elliott Hughese84278b2012-03-22 10:06:53 -0700936 } else if (c->IsArrayClass()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800937 mirror::Array* aobj = obj->AsArray();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500938 uint32_t length = aobj->GetLength();
939
940 if (obj->IsObjectArray()) {
941 // obj is an object array.
942 rec->AddU1(HPROF_OBJECT_ARRAY_DUMP);
943
Ian Rogersef7d42f2014-01-06 12:55:46 -0800944 rec->AddObjectId(obj);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500945 rec->AddU4(StackTraceSerialNumber(obj));
946 rec->AddU4(length);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800947 rec->AddClassId(LookupClassId(c));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500948
949 // Dump the elements, which are always objects or NULL.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800950 rec->AddIdList(aobj->AsObjectArray<mirror::Object>());
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500951 } else {
952 size_t size;
Elliott Hughese84278b2012-03-22 10:06:53 -0700953 HprofBasicType t = PrimitiveToBasicTypeAndSize(c->GetComponentType()->GetPrimitiveType(), &size);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500954
955 // obj is a primitive array.
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500956 rec->AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500957
Ian Rogersef7d42f2014-01-06 12:55:46 -0800958 rec->AddObjectId(obj);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500959 rec->AddU4(StackTraceSerialNumber(obj));
960 rec->AddU4(length);
961 rec->AddU1(t);
962
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500963 // Dump the raw, packed element values.
964 if (size == 1) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800965 rec->AddU1List((const uint8_t*)aobj->GetRawData(sizeof(uint8_t), 0), length);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500966 } else if (size == 2) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800967 rec->AddU2List((const uint16_t*)aobj->GetRawData(sizeof(uint16_t), 0), length);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500968 } else if (size == 4) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800969 rec->AddU4List((const uint32_t*)aobj->GetRawData(sizeof(uint32_t), 0), length);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500970 } else if (size == 8) {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800971 rec->AddU8List((const uint64_t*)aobj->GetRawData(sizeof(uint64_t), 0), length);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500972 }
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500973 }
974 } else {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500975 // obj is an instance object.
976 rec->AddU1(HPROF_INSTANCE_DUMP);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800977 rec->AddObjectId(obj);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500978 rec->AddU4(StackTraceSerialNumber(obj));
Ian Rogersef7d42f2014-01-06 12:55:46 -0800979 rec->AddClassId(LookupClassId(c));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500980
981 // Reserve some space for the length of the instance data, which we won't
982 // know until we're done writing it.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700983 size_t size_patch_offset = rec->Size();
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500984 rec->AddU4(0x77777777);
985
986 // Write the instance data; fields for this class, followed by super class fields,
987 // and so on. Don't write the klass or monitor fields of Object.class.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800988 mirror::Class* sclass = c;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500989 while (!sclass->IsObjectClass()) {
990 int ifieldCount = sclass->NumInstanceFields();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -0700991 for (int i = 0; i < ifieldCount; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700992 mirror::ArtField* f = sclass->GetInstanceField(i);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500993 size_t size;
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700994 SignatureToBasicTypeAndSize(f->GetTypeDescriptor(), &size);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500995 if (size == 1) {
996 rec->AddU1(f->Get32(obj));
997 } else if (size == 2) {
998 rec->AddU2(f->Get32(obj));
999 } else if (size == 4) {
1000 rec->AddU4(f->Get32(obj));
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001001 } else {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001002 CHECK_EQ(size, 8U);
1003 rec->AddU8(f->Get64(obj));
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001004 }
1005 }
1006
1007 sclass = sclass->GetSuperClass();
1008 }
1009
1010 // Patch the instance field length.
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001011 rec->UpdateU4(size_patch_offset, rec->Size() - (size_patch_offset + 4));
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001012 }
1013 }
1014
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001015 ++objects_in_segment_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001016 return 0;
1017}
1018
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001019void Hprof::VisitRoot(const mirror::Object* obj, uint32_t thread_id, RootType type) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001020 static const HprofHeapTag xlate[] = {
1021 HPROF_ROOT_UNKNOWN,
1022 HPROF_ROOT_JNI_GLOBAL,
1023 HPROF_ROOT_JNI_LOCAL,
1024 HPROF_ROOT_JAVA_FRAME,
1025 HPROF_ROOT_NATIVE_STACK,
1026 HPROF_ROOT_STICKY_CLASS,
1027 HPROF_ROOT_THREAD_BLOCK,
1028 HPROF_ROOT_MONITOR_USED,
1029 HPROF_ROOT_THREAD_OBJECT,
1030 HPROF_ROOT_INTERNED_STRING,
1031 HPROF_ROOT_FINALIZING,
1032 HPROF_ROOT_DEBUGGER,
1033 HPROF_ROOT_REFERENCE_CLEANUP,
1034 HPROF_ROOT_VM_INTERNAL,
1035 HPROF_ROOT_JNI_MONITOR,
1036 };
Jesse Wilson0b075f12011-11-09 10:57:41 -05001037 CHECK_LT(type, sizeof(xlate) / sizeof(HprofHeapTag));
1038 if (obj == NULL) {
1039 return;
1040 }
1041 gc_scan_state_ = xlate[type];
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001042 gc_thread_serial_number_ = thread_id;
Jesse Wilson0b075f12011-11-09 10:57:41 -05001043 MarkRootObject(obj, 0);
1044 gc_scan_state_ = 0;
1045 gc_thread_serial_number_ = 0;
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001046}
1047
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001048// If "direct_to_ddms" is true, the other arguments are ignored, and data is
1049// sent directly to DDMS.
1050// If "fd" is >= 0, the output will be written to that file descriptor.
1051// Otherwise, "filename" is used to create an output file.
1052void DumpHeap(const char* filename, int fd, bool direct_to_ddms) {
1053 CHECK(filename != NULL);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001054
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001055 Runtime::Current()->GetThreadList()->SuspendAll();
Elliott Hughesdcfdd2b2012-07-09 18:27:46 -07001056 Hprof hprof(filename, fd, direct_to_ddms);
1057 hprof.Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001058 Runtime::Current()->GetThreadList()->ResumeAll();
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001059}
1060
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001061// Returns how many characters were in the buffer (or written).
1062size_t HprofRecord::Flush() {
1063 size_t chars = 0;
1064 if (dirty_) {
1065 unsigned char headBuf[sizeof(uint8_t) + 2 * sizeof(uint32_t)];
1066 headBuf[0] = tag_;
1067 U4_TO_BUF_BE(headBuf, 1, time_);
1068 U4_TO_BUF_BE(headBuf, 5, length_);
1069 chars += hprof_->Write(headBuf, sizeof(headBuf), fp_);
1070 chars += hprof_->Write(body_, length_, fp_);
1071 dirty_ = false;
1072 }
1073 return chars;
1074}
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001075
Mathieu Chartierad466ad2015-01-08 16:28:08 -08001076void HprofRecord::AddU1(uint8_t value) {
1077 if (hprof_->AllowWriting()) {
1078 GuaranteeRecordAppend(1);
1079 body_[length_] = value;
1080 }
1081 ++length_;
1082}
1083
1084void HprofRecord::AddU1List(const uint8_t* values, size_t numValues) {
1085 if (hprof_->AllowWriting()) {
1086 GuaranteeRecordAppend(numValues);
1087 memcpy(body_ + length_, values, numValues);
1088 }
1089 length_ += numValues;
1090}
1091
1092void HprofRecord::AddU2List(const uint16_t* values, size_t numValues) {
1093 if (hprof_->AllowWriting()) {
1094 GuaranteeRecordAppend(numValues * 2);
1095 unsigned char* insert = body_ + length_;
1096 for (size_t i = 0; i < numValues; ++i) {
1097 U2_TO_BUF_BE(insert, 0, *values++);
1098 insert += sizeof(*values);
1099 }
1100 }
1101 length_ += numValues * 2;
1102}
1103
1104void HprofRecord::AddU4List(const uint32_t* values, size_t numValues) {
1105 if (hprof_->AllowWriting()) {
1106 GuaranteeRecordAppend(numValues * 4);
1107 unsigned char* insert = body_ + length_;
1108 for (size_t i = 0; i < numValues; ++i) {
1109 U4_TO_BUF_BE(insert, 0, *values++);
1110 insert += sizeof(*values);
1111 }
1112 }
1113 length_ += numValues * 4;
1114}
1115
1116void HprofRecord::UpdateU4(size_t offset, uint32_t new_value) {
1117 if (hprof_->AllowWriting()) {
1118 U4_TO_BUF_BE(body_, offset, new_value);
1119 }
1120}
1121
1122void HprofRecord::AddU8List(const uint64_t* values, size_t numValues) {
1123 if (hprof_->AllowWriting()) {
1124 GuaranteeRecordAppend(numValues * 8);
1125 unsigned char* insert = body_ + length_;
1126 for (size_t i = 0; i < numValues; ++i) {
1127 U8_TO_BUF_BE(insert, 0, *values++);
1128 insert += sizeof(*values);
1129 }
1130 }
1131 length_ += numValues * 8;
1132}
1133
1134} // namespace hprof
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001135} // namespace art