blob: 03e3a6c3006249a2201cd697f42846806c5ea9d0 [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
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080040#include "class_linker.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040041#include "debugger.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070042#include "file.h"
43#include "globals.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080044#include "heap.h"
45#include "logging.h"
Jesse Wilson0c54ac12011-11-09 15:14:05 -050046#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080047#include "object_utils.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070048#include "safe_map.h"
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080049#include "scoped_heap_lock.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040050#include "stringprintf.h"
Elliott Hughes622a6982012-06-08 17:58:54 -070051#include "thread_list.h"
Jesse Wilsonc4824e62011-11-01 14:39:04 -040052
53namespace art {
54
55namespace hprof {
56
Elliott Hughes622a6982012-06-08 17:58:54 -070057#define UNIQUE_ERROR -((((uintptr_t)__func__) << 16 | __LINE__) & (0x7fffffff))
Jesse Wilson0c54ac12011-11-09 15:14:05 -050058
Elliott Hughes622a6982012-06-08 17:58:54 -070059#define HPROF_TIME 0
60#define HPROF_NULL_STACK_TRACE 0
61#define HPROF_NULL_THREAD 0
62
63#define U2_TO_BUF_BE(buf, offset, value) \
64 do { \
65 unsigned char* buf_ = (unsigned char*)(buf); \
66 int offset_ = (int)(offset); \
67 uint16_t value_ = (uint16_t)(value); \
68 buf_[offset_ + 0] = (unsigned char)(value_ >> 8); \
69 buf_[offset_ + 1] = (unsigned char)(value_ ); \
70 } while (0)
71
72#define U4_TO_BUF_BE(buf, offset, value) \
73 do { \
74 unsigned char* buf_ = (unsigned char*)(buf); \
75 int offset_ = (int)(offset); \
76 uint32_t value_ = (uint32_t)(value); \
77 buf_[offset_ + 0] = (unsigned char)(value_ >> 24); \
78 buf_[offset_ + 1] = (unsigned char)(value_ >> 16); \
79 buf_[offset_ + 2] = (unsigned char)(value_ >> 8); \
80 buf_[offset_ + 3] = (unsigned char)(value_ ); \
81 } while (0)
82
83#define U8_TO_BUF_BE(buf, offset, value) \
84 do { \
85 unsigned char* buf_ = (unsigned char*)(buf); \
86 int offset_ = (int)(offset); \
87 uint64_t value_ = (uint64_t)(value); \
88 buf_[offset_ + 0] = (unsigned char)(value_ >> 56); \
89 buf_[offset_ + 1] = (unsigned char)(value_ >> 48); \
90 buf_[offset_ + 2] = (unsigned char)(value_ >> 40); \
91 buf_[offset_ + 3] = (unsigned char)(value_ >> 32); \
92 buf_[offset_ + 4] = (unsigned char)(value_ >> 24); \
93 buf_[offset_ + 5] = (unsigned char)(value_ >> 16); \
94 buf_[offset_ + 6] = (unsigned char)(value_ >> 8); \
95 buf_[offset_ + 7] = (unsigned char)(value_ ); \
96 } while (0)
97
98enum HprofTag {
99 HPROF_TAG_STRING = 0x01,
100 HPROF_TAG_LOAD_CLASS = 0x02,
101 HPROF_TAG_UNLOAD_CLASS = 0x03,
102 HPROF_TAG_STACK_FRAME = 0x04,
103 HPROF_TAG_STACK_TRACE = 0x05,
104 HPROF_TAG_ALLOC_SITES = 0x06,
105 HPROF_TAG_HEAP_SUMMARY = 0x07,
106 HPROF_TAG_START_THREAD = 0x0A,
107 HPROF_TAG_END_THREAD = 0x0B,
108 HPROF_TAG_HEAP_DUMP = 0x0C,
109 HPROF_TAG_HEAP_DUMP_SEGMENT = 0x1C,
110 HPROF_TAG_HEAP_DUMP_END = 0x2C,
111 HPROF_TAG_CPU_SAMPLES = 0x0D,
112 HPROF_TAG_CONTROL_SETTINGS = 0x0E,
113};
114
115// Values for the first byte of HEAP_DUMP and HEAP_DUMP_SEGMENT records:
116enum HprofHeapTag {
117 // Traditional.
118 HPROF_ROOT_UNKNOWN = 0xFF,
119 HPROF_ROOT_JNI_GLOBAL = 0x01,
120 HPROF_ROOT_JNI_LOCAL = 0x02,
121 HPROF_ROOT_JAVA_FRAME = 0x03,
122 HPROF_ROOT_NATIVE_STACK = 0x04,
123 HPROF_ROOT_STICKY_CLASS = 0x05,
124 HPROF_ROOT_THREAD_BLOCK = 0x06,
125 HPROF_ROOT_MONITOR_USED = 0x07,
126 HPROF_ROOT_THREAD_OBJECT = 0x08,
127 HPROF_CLASS_DUMP = 0x20,
128 HPROF_INSTANCE_DUMP = 0x21,
129 HPROF_OBJECT_ARRAY_DUMP = 0x22,
130 HPROF_PRIMITIVE_ARRAY_DUMP = 0x23,
131
132 // Android.
133 HPROF_HEAP_DUMP_INFO = 0xfe,
134 HPROF_ROOT_INTERNED_STRING = 0x89,
135 HPROF_ROOT_FINALIZING = 0x8a, // Obsolete.
136 HPROF_ROOT_DEBUGGER = 0x8b,
137 HPROF_ROOT_REFERENCE_CLEANUP = 0x8c, // Obsolete.
138 HPROF_ROOT_VM_INTERNAL = 0x8d,
139 HPROF_ROOT_JNI_MONITOR = 0x8e,
140 HPROF_UNREACHABLE = 0x90, // Obsolete.
141 HPROF_PRIMITIVE_ARRAY_NODATA_DUMP = 0xc3,
142};
143
144enum HprofHeapId {
145 HPROF_HEAP_DEFAULT = 0,
146 HPROF_HEAP_ZYGOTE = 'Z',
147 HPROF_HEAP_APP = 'A'
148};
149
150enum HprofBasicType {
151 hprof_basic_object = 2,
152 hprof_basic_boolean = 4,
153 hprof_basic_char = 5,
154 hprof_basic_float = 6,
155 hprof_basic_double = 7,
156 hprof_basic_byte = 8,
157 hprof_basic_short = 9,
158 hprof_basic_int = 10,
159 hprof_basic_long = 11,
160};
161
162typedef uint32_t HprofId;
163typedef HprofId HprofStringId;
164typedef HprofId HprofObjectId;
165typedef HprofId HprofClassObjectId;
166typedef std::set<Class*> ClassSet;
167typedef std::set<Class*>::iterator ClassSetIterator;
168typedef SafeMap<std::string, size_t> StringMap;
169typedef SafeMap<std::string, size_t>::iterator StringMapIterator;
170
171// Represents a top-level hprof record, whose serialized format is:
172// U1 TAG: denoting the type of the record
173// U4 TIME: number of microseconds since the time stamp in the header
174// U4 LENGTH: number of bytes that follow this uint32_t field and belong to this record
175// U1* BODY: as many bytes as specified in the above uint32_t field
176class HprofRecord {
177 public:
178 int Flush(FILE* fp) {
179 if (dirty_) {
180 unsigned char headBuf[sizeof (uint8_t) + 2 * sizeof (uint32_t)];
181
182 headBuf[0] = tag_;
183 U4_TO_BUF_BE(headBuf, 1, time_);
184 U4_TO_BUF_BE(headBuf, 5, length_);
185
186 int nb = fwrite(headBuf, 1, sizeof(headBuf), fp);
187 if (nb != sizeof(headBuf)) {
188 return UNIQUE_ERROR;
189 }
190 nb = fwrite(body_, 1, length_, fp);
191 if (nb != (int)length_) {
192 return UNIQUE_ERROR;
193 }
194
195 dirty_ = false;
196 }
197 // TODO if we used less than half (or whatever) of allocLen, shrink the buffer.
198 return 0;
199 }
200
201 int AddU1(uint8_t value) {
202 int err = GuaranteeRecordAppend(1);
203 if (err != 0) {
204 return err;
205 }
206
207 body_[length_++] = value;
208 return 0;
209 }
210
211 int AddU2(uint16_t value) {
212 return AddU2List(&value, 1);
213 }
214
215 int AddU4(uint32_t value) {
216 return AddU4List(&value, 1);
217 }
218
219 int AddU8(uint64_t value) {
220 return AddU8List(&value, 1);
221 }
222
223 int AddId(HprofObjectId value) {
224 return AddU4((uint32_t) value);
225 }
226
227 int AddU1List(const uint8_t *values, size_t numValues) {
228 int err = GuaranteeRecordAppend(numValues);
229 if (err != 0) {
230 return err;
231 }
232
233 memcpy(body_ + length_, values, numValues);
234 length_ += numValues;
235 return 0;
236 }
237
238 int AddU2List(const uint16_t *values, size_t numValues) {
239 int err = GuaranteeRecordAppend(numValues * 2);
240 if (err != 0) {
241 return err;
242 }
243
244 unsigned char* insert = body_ + length_;
245 for (size_t i = 0; i < numValues; i++) {
246 U2_TO_BUF_BE(insert, 0, *values++);
247 insert += sizeof(*values);
248 }
249 length_ += numValues * 2;
250 return 0;
251 }
252
253 int AddU4List(const uint32_t *values, size_t numValues) {
254 int err = GuaranteeRecordAppend(numValues * 4);
255 if (err != 0) {
256 return err;
257 }
258
259 unsigned char* insert = body_ + length_;
260 for (size_t i = 0; i < numValues; i++) {
261 U4_TO_BUF_BE(insert, 0, *values++);
262 insert += sizeof(*values);
263 }
264 length_ += numValues * 4;
265 return 0;
266 }
267
268 int AddU8List(const uint64_t *values, size_t numValues) {
269 int err = GuaranteeRecordAppend(numValues * 8);
270 if (err != 0) {
271 return err;
272 }
273
274 unsigned char* insert = body_ + length_;
275 for (size_t i = 0; i < numValues; i++) {
276 U8_TO_BUF_BE(insert, 0, *values++);
277 insert += sizeof(*values);
278 }
279 length_ += numValues * 8;
280 return 0;
281 }
282
283 int AddIdList(const HprofObjectId *values, size_t numValues) {
284 return AddU4List((const uint32_t*) values, numValues);
285 }
286
287 int AddUtf8String(const char* str) {
288 // The terminating NUL character is NOT written.
289 return AddU1List((const uint8_t *)str, strlen(str));
290 }
291
292 unsigned char* body_;
293 uint32_t time_;
294 uint32_t length_;
295 size_t alloc_length_;
296 uint8_t tag_;
297 bool dirty_;
298
299 private:
300 int GuaranteeRecordAppend(size_t nmore) {
301 size_t minSize = length_ + nmore;
302 if (minSize > alloc_length_) {
303 size_t newAllocLen = alloc_length_ * 2;
304 if (newAllocLen < minSize) {
305 newAllocLen = alloc_length_ + nmore + nmore/2;
306 }
307 unsigned char* newBody = (unsigned char*)realloc(body_, newAllocLen);
308 if (newBody != NULL) {
309 body_ = newBody;
310 alloc_length_ = newAllocLen;
311 } else {
312 // TODO: set an error flag so future ops will fail
313 return UNIQUE_ERROR;
314 }
315 }
316
317 CHECK_LE(length_ + nmore, alloc_length_);
318 return 0;
319 }
320};
321
322class Hprof {
323 public:
324 Hprof(const char* output_filename, int fd, bool write_header, bool direct_to_ddms);
325 ~Hprof();
326
327 void VisitRoot(const Object* obj);
328 int DumpHeapObject(const Object *obj);
329 void Finish();
330
331 private:
332 int DumpClasses();
333 int DumpStrings();
334 int StartNewRecord(uint8_t tag, uint32_t time);
335 int FlushCurrentRecord();
336 int MarkRootObject(const Object *obj, jobject jniObj);
337 HprofClassObjectId LookupClassId(Class* c);
338 HprofStringId LookupStringId(String* string);
339 HprofStringId LookupStringId(const char* string);
340 HprofStringId LookupStringId(const std::string& string);
341 HprofStringId LookupClassNameId(Class* c);
342
343 // current_record_ *must* be first so that we can cast from a context to a record.
344 HprofRecord current_record_;
345
346 uint32_t gc_thread_serial_number_;
347 uint8_t gc_scan_state_;
348 HprofHeapId current_heap_; // which heap we're currently emitting
349 size_t objects_in_segment_;
350
351 // If direct_to_ddms_ is set, "file_name_" and "fd" will be ignored.
352 // Otherwise, "file_name_" must be valid, though if "fd" >= 0 it will
353 // only be used for debug messages.
354 bool direct_to_ddms_;
355 std::string file_name_;
356 char* file_data_ptr_; // for open_memstream
357 size_t file_data_size_; // for open_memstream
358 FILE *mem_fp_;
359 int fd_;
360
361 ClassSet classes_;
362 size_t next_string_id_;
363 StringMap strings_;
364
365 DISALLOW_COPY_AND_ASSIGN(Hprof);
366};
367
368Hprof::Hprof(const char* output_filename, int fd, bool write_header, bool direct_to_ddms)
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500369 : current_record_(),
370 gc_thread_serial_number_(0),
371 gc_scan_state_(0),
372 current_heap_(HPROF_HEAP_DEFAULT),
373 objects_in_segment_(0),
374 direct_to_ddms_(0),
Elliott Hughes622a6982012-06-08 17:58:54 -0700375 file_name_(output_filename),
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500376 file_data_ptr_(NULL),
377 file_data_size_(0),
378 mem_fp_(NULL),
379 fd_(0),
380 next_string_id_(0x400000) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700381
382 LOG(INFO) << "hprof: heap dump starting (\"" << output_filename << "\", fd=" << fd
383 << ", write_header=" << write_header << ", direct_to_ddms=" << direct_to_ddms << ")";
384
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500385 // Have to do this here, because it must happen after we
386 // memset the struct (want to treat file_data_ptr_/file_data_size_
387 // as read-only while the file is open).
388 FILE *fp = open_memstream(&file_data_ptr_, &file_data_size_);
389 if (fp == NULL) {
390 // not expected
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700391 PLOG(FATAL) << "open_memstream failed";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500392 }
393
Elliott Hughes622a6982012-06-08 17:58:54 -0700394 direct_to_ddms_ = direct_to_ddms;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500395 mem_fp_ = fp;
396 fd_ = fd;
397
398 current_record_.alloc_length_ = 128;
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800399 current_record_.body_ = (unsigned char*)malloc(current_record_.alloc_length_);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500400 // TODO check for/return an error
401
Elliott Hughes622a6982012-06-08 17:58:54 -0700402 if (write_header) {
403 char magic[] = "JAVA PROFILE 1.0.3";
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500404 unsigned char buf[4];
405
406 // Write the file header.
407 // U1: NUL-terminated magic string.
408 fwrite(magic, 1, sizeof(magic), fp);
409
410 // U4: size of identifiers. We're using addresses as IDs, so make sure a pointer fits.
411 U4_TO_BUF_BE(buf, 0, sizeof(void *));
412 fwrite(buf, 1, sizeof(uint32_t), fp);
413
414 // The current time, in milliseconds since 0:00 GMT, 1/1/70.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700415 timeval now;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500416 uint64_t nowMs;
417 if (gettimeofday(&now, NULL) < 0) {
418 nowMs = 0;
419 } else {
420 nowMs = (uint64_t)now.tv_sec * 1000 + now.tv_usec / 1000;
421 }
422
423 // U4: high word of the 64-bit time.
424 U4_TO_BUF_BE(buf, 0, (uint32_t)(nowMs >> 32));
425 fwrite(buf, 1, sizeof(uint32_t), fp);
426
427 // U4: low word of the 64-bit time.
428 U4_TO_BUF_BE(buf, 0, (uint32_t)(nowMs & 0xffffffffULL));
429 fwrite(buf, 1, sizeof(uint32_t), fp); //xxx fix the time
430 }
431}
432
433int Hprof::StartNewRecord(uint8_t tag, uint32_t time) {
434 HprofRecord *rec = &current_record_;
435
436 int err = rec->Flush(mem_fp_);
437 if (err != 0) {
438 return err;
439 } else if (rec->dirty_) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700440 return UNIQUE_ERROR;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500441 }
442
443 rec->dirty_ = true;
444 rec->tag_ = tag;
445 rec->time_ = time;
446 rec->length_ = 0;
447 return 0;
448}
449
450int Hprof::FlushCurrentRecord() {
451 return current_record_.Flush(mem_fp_);
452}
453
454// Set DUMP_PRIM_DATA to 1 if you want to include the contents
455// of primitive arrays (byte arrays, character arrays, etc.)
456// in heap dumps. This can be a large amount of data.
457#define DUMP_PRIM_DATA 1
458
459#define OBJECTS_PER_SEGMENT ((size_t)128)
460#define BYTES_PER_SEGMENT ((size_t)4096)
461
462// The static field-name for the synthetic object generated to account
463// for class static overhead.
464#define STATIC_OVERHEAD_NAME "$staticOverhead"
465// The ID for the synthetic object generated to account for class static overhead.
Elliott Hughese84278b2012-03-22 10:06:53 -0700466#define CLASS_STATICS_ID(c) ((HprofObjectId)(((uint32_t)(c)) | 1))
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500467
Elliott Hughes622a6982012-06-08 17:58:54 -0700468static HprofBasicType SignatureToBasicTypeAndSize(const char* sig, size_t* sizeOut) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500469 char c = sig[0];
470 HprofBasicType ret;
471 size_t size;
472
473 switch (c) {
474 case '[':
475 case 'L': ret = hprof_basic_object; size = 4; break;
476 case 'Z': ret = hprof_basic_boolean; size = 1; break;
477 case 'C': ret = hprof_basic_char; size = 2; break;
478 case 'F': ret = hprof_basic_float; size = 4; break;
479 case 'D': ret = hprof_basic_double; size = 8; break;
480 case 'B': ret = hprof_basic_byte; size = 1; break;
481 case 'S': ret = hprof_basic_short; size = 2; break;
482 default: CHECK(false);
483 case 'I': ret = hprof_basic_int; size = 4; break;
484 case 'J': ret = hprof_basic_long; size = 8; break;
485 }
486
487 if (sizeOut != NULL) {
488 *sizeOut = size;
489 }
490
491 return ret;
492}
493
Elliott Hughes622a6982012-06-08 17:58:54 -0700494static HprofBasicType PrimitiveToBasicTypeAndSize(Primitive::Type prim, size_t *sizeOut) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500495 HprofBasicType ret;
496 size_t size;
497
498 switch (prim) {
499 case Primitive::kPrimBoolean: ret = hprof_basic_boolean; size = 1; break;
500 case Primitive::kPrimChar: ret = hprof_basic_char; size = 2; break;
501 case Primitive::kPrimFloat: ret = hprof_basic_float; size = 4; break;
502 case Primitive::kPrimDouble: ret = hprof_basic_double; size = 8; break;
503 case Primitive::kPrimByte: ret = hprof_basic_byte; size = 1; break;
504 case Primitive::kPrimShort: ret = hprof_basic_short; size = 2; break;
505 default: CHECK(false);
506 case Primitive::kPrimInt: ret = hprof_basic_int; size = 4; break;
507 case Primitive::kPrimLong: ret = hprof_basic_long; size = 8; break;
508 }
509
510 if (sizeOut != NULL) {
511 *sizeOut = size;
512 }
513
514 return ret;
515}
516
517// Always called when marking objects, but only does
518// something when ctx->gc_scan_state_ is non-zero, which is usually
519// only true when marking the root set or unreachable
520// objects. Used to add rootset references to obj.
521int Hprof::MarkRootObject(const Object *obj, jobject jniObj) {
Elliott Hughes73e66f72012-05-09 09:34:45 -0700522 HprofRecord* rec = &current_record_;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500523 HprofHeapTag heapTag = (HprofHeapTag)gc_scan_state_;
524
525 if (heapTag == 0) {
526 return 0;
527 }
528
529 if (objects_in_segment_ >= OBJECTS_PER_SEGMENT || rec->length_ >= BYTES_PER_SEGMENT) {
530 // This flushes the old segment and starts a new one.
531 StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, HPROF_TIME);
532 objects_in_segment_ = 0;
533 }
534
535 switch (heapTag) {
536 // ID: object ID
537 case HPROF_ROOT_UNKNOWN:
538 case HPROF_ROOT_STICKY_CLASS:
539 case HPROF_ROOT_MONITOR_USED:
540 case HPROF_ROOT_INTERNED_STRING:
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500541 case HPROF_ROOT_DEBUGGER:
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500542 case HPROF_ROOT_VM_INTERNAL:
543 rec->AddU1(heapTag);
544 rec->AddId((HprofObjectId)obj);
545 break;
546
547 // ID: object ID
548 // ID: JNI global ref ID
549 case HPROF_ROOT_JNI_GLOBAL:
550 rec->AddU1(heapTag);
551 rec->AddId((HprofObjectId)obj);
552 rec->AddId((HprofId)jniObj);
553 break;
554
555 // ID: object ID
556 // U4: thread serial number
557 // U4: frame number in stack trace (-1 for empty)
558 case HPROF_ROOT_JNI_LOCAL:
559 case HPROF_ROOT_JNI_MONITOR:
560 case HPROF_ROOT_JAVA_FRAME:
561 rec->AddU1(heapTag);
562 rec->AddId((HprofObjectId)obj);
563 rec->AddU4(gc_thread_serial_number_);
564 rec->AddU4((uint32_t)-1);
565 break;
566
567 // ID: object ID
568 // U4: thread serial number
569 case HPROF_ROOT_NATIVE_STACK:
570 case HPROF_ROOT_THREAD_BLOCK:
571 rec->AddU1(heapTag);
572 rec->AddId((HprofObjectId)obj);
573 rec->AddU4(gc_thread_serial_number_);
574 break;
575
576 // ID: thread object ID
577 // U4: thread serial number
578 // U4: stack trace serial number
579 case HPROF_ROOT_THREAD_OBJECT:
580 rec->AddU1(heapTag);
581 rec->AddId((HprofObjectId)obj);
582 rec->AddU4(gc_thread_serial_number_);
583 rec->AddU4((uint32_t)-1); //xxx
584 break;
585
Elliott Hughes73e66f72012-05-09 09:34:45 -0700586 case HPROF_CLASS_DUMP:
587 case HPROF_INSTANCE_DUMP:
588 case HPROF_OBJECT_ARRAY_DUMP:
589 case HPROF_PRIMITIVE_ARRAY_DUMP:
590 case HPROF_HEAP_DUMP_INFO:
591 case HPROF_PRIMITIVE_ARRAY_NODATA_DUMP:
592 // Ignored.
593 break;
594
595 case HPROF_ROOT_FINALIZING:
596 case HPROF_ROOT_REFERENCE_CLEANUP:
597 case HPROF_UNREACHABLE:
598 LOG(FATAL) << "obsolete tag " << static_cast<int>(heapTag);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500599 break;
600 }
601
602 objects_in_segment_++;
Elliott Hughes73e66f72012-05-09 09:34:45 -0700603 return 0;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500604}
605
Elliott Hughes622a6982012-06-08 17:58:54 -0700606static int StackTraceSerialNumber(const void* /*obj*/) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500607 return HPROF_NULL_STACK_TRACE;
608}
609
610int Hprof::DumpHeapObject(const Object* obj) {
611 HprofRecord *rec = &current_record_;
612 HprofHeapId desiredHeap = false ? HPROF_HEAP_ZYGOTE : HPROF_HEAP_APP; // TODO: zygote objects?
613
614 if (objects_in_segment_ >= OBJECTS_PER_SEGMENT || rec->length_ >= BYTES_PER_SEGMENT) {
615 // This flushes the old segment and starts a new one.
616 StartNewRecord(HPROF_TAG_HEAP_DUMP_SEGMENT, HPROF_TIME);
617 objects_in_segment_ = 0;
618
619 // Starting a new HEAP_DUMP resets the heap to default.
620 current_heap_ = HPROF_HEAP_DEFAULT;
621 }
622
623 if (desiredHeap != current_heap_) {
624 HprofStringId nameId;
625
626 // This object is in a different heap than the current one.
627 // Emit a HEAP_DUMP_INFO tag to change heaps.
628 rec->AddU1(HPROF_HEAP_DUMP_INFO);
629 rec->AddU4((uint32_t)desiredHeap); // uint32_t: heap id
630 switch (desiredHeap) {
631 case HPROF_HEAP_APP:
632 nameId = LookupStringId("app");
633 break;
634 case HPROF_HEAP_ZYGOTE:
635 nameId = LookupStringId("zygote");
636 break;
637 default:
638 // Internal error
639 LOG(ERROR) << "Unexpected desiredHeap";
640 nameId = LookupStringId("<ILLEGAL>");
641 break;
642 }
643 rec->AddId(nameId);
644 current_heap_ = desiredHeap;
645 }
646
Elliott Hughese84278b2012-03-22 10:06:53 -0700647 Class* c = obj->GetClass();
648 if (c == NULL) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500649 // This object will bother HprofReader, because it has a NULL
650 // class, so just don't dump it. It could be
651 // gDvm.unlinkedJavaLangClass or it could be an object just
652 // allocated which hasn't been initialized yet.
653 } else {
654 if (obj->IsClass()) {
655 Class* thisClass = (Class*)obj;
656 // obj is a ClassObject.
657 size_t sFieldCount = thisClass->NumStaticFields();
658 if (sFieldCount != 0) {
659 int byteLength = sFieldCount*sizeof(JValue); // TODO bogus; fields are packed
660 // Create a byte array to reflect the allocation of the
661 // StaticField array at the end of this class.
662 rec->AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
663 rec->AddId(CLASS_STATICS_ID(obj));
664 rec->AddU4(StackTraceSerialNumber(obj));
665 rec->AddU4(byteLength);
666 rec->AddU1(hprof_basic_byte);
667 for (int i = 0; i < byteLength; i++) {
668 rec->AddU1(0);
669 }
670 }
671
672 rec->AddU1(HPROF_CLASS_DUMP);
673 rec->AddId(LookupClassId(thisClass));
674 rec->AddU4(StackTraceSerialNumber(thisClass));
675 rec->AddId(LookupClassId(thisClass->GetSuperClass()));
676 rec->AddId((HprofObjectId)thisClass->GetClassLoader());
677 rec->AddId((HprofObjectId)0); // no signer
678 rec->AddId((HprofObjectId)0); // no prot domain
679 rec->AddId((HprofId)0); // reserved
680 rec->AddId((HprofId)0); // reserved
Elliott Hughesdbb40792011-11-18 17:05:22 -0800681 if (thisClass->IsClassClass()) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500682 // ClassObjects have their static fields appended, so aren't all the same size.
683 // But they're at least this size.
684 rec->AddU4(sizeof(Class)); // instance size
685 } else if (thisClass->IsArrayClass() || thisClass->IsPrimitive()) {
686 rec->AddU4(0);
687 } else {
688 rec->AddU4(thisClass->GetObjectSize()); // instance size
689 }
690
691 rec->AddU2(0); // empty const pool
692
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800693 FieldHelper fh;
694
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500695 // Static fields
696 if (sFieldCount == 0) {
697 rec->AddU2((uint16_t)0);
698 } else {
699 rec->AddU2((uint16_t)(sFieldCount+1));
700 rec->AddId(LookupStringId(STATIC_OVERHEAD_NAME));
701 rec->AddU1(hprof_basic_object);
702 rec->AddId(CLASS_STATICS_ID(obj));
703
704 for (size_t i = 0; i < sFieldCount; ++i) {
705 Field* f = thisClass->GetStaticField(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800706 fh.ChangeField(f);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500707
708 size_t size;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800709 HprofBasicType t = SignatureToBasicTypeAndSize(fh.GetTypeDescriptor(), &size);
710 rec->AddId(LookupStringId(fh.GetName()));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500711 rec->AddU1(t);
712 if (size == 1) {
713 rec->AddU1(static_cast<uint8_t>(f->Get32(NULL)));
714 } else if (size == 2) {
715 rec->AddU2(static_cast<uint16_t>(f->Get32(NULL)));
716 } else if (size == 4) {
717 rec->AddU4(f->Get32(NULL));
718 } else if (size == 8) {
719 rec->AddU8(f->Get64(NULL));
720 } else {
721 CHECK(false);
722 }
723 }
724 }
725
726 // Instance fields for this class (no superclass fields)
727 int iFieldCount = thisClass->IsObjectClass() ? 0 : thisClass->NumInstanceFields();
728 rec->AddU2((uint16_t)iFieldCount);
729 for (int i = 0; i < iFieldCount; ++i) {
730 Field* f = thisClass->GetInstanceField(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800731 fh.ChangeField(f);
732 HprofBasicType t = SignatureToBasicTypeAndSize(fh.GetTypeDescriptor(), NULL);
733 rec->AddId(LookupStringId(fh.GetName()));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500734 rec->AddU1(t);
735 }
Elliott Hughese84278b2012-03-22 10:06:53 -0700736 } else if (c->IsArrayClass()) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500737 Array *aobj = (Array *)obj;
738 uint32_t length = aobj->GetLength();
739
740 if (obj->IsObjectArray()) {
741 // obj is an object array.
742 rec->AddU1(HPROF_OBJECT_ARRAY_DUMP);
743
744 rec->AddId((HprofObjectId)obj);
745 rec->AddU4(StackTraceSerialNumber(obj));
746 rec->AddU4(length);
Elliott Hughese84278b2012-03-22 10:06:53 -0700747 rec->AddId(LookupClassId(c));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500748
749 // Dump the elements, which are always objects or NULL.
Ian Rogersa15e67d2012-02-28 13:51:55 -0800750 rec->AddIdList((const HprofObjectId *)aobj->GetRawData(sizeof(Object*)), length);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500751 } else {
752 size_t size;
Elliott Hughese84278b2012-03-22 10:06:53 -0700753 HprofBasicType t = PrimitiveToBasicTypeAndSize(c->GetComponentType()->GetPrimitiveType(), &size);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500754
755 // obj is a primitive array.
756#if DUMP_PRIM_DATA
757 rec->AddU1(HPROF_PRIMITIVE_ARRAY_DUMP);
758#else
759 rec->AddU1(HPROF_PRIMITIVE_ARRAY_NODATA_DUMP);
760#endif
761
762 rec->AddId((HprofObjectId)obj);
763 rec->AddU4(StackTraceSerialNumber(obj));
764 rec->AddU4(length);
765 rec->AddU1(t);
766
767#if DUMP_PRIM_DATA
768 // Dump the raw, packed element values.
769 if (size == 1) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800770 rec->AddU1List((const uint8_t *)aobj->GetRawData(sizeof(uint8_t)), length);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500771 } else if (size == 2) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800772 rec->AddU2List((const uint16_t *)(void *)aobj->GetRawData(sizeof(uint16_t)), length);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500773 } else if (size == 4) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800774 rec->AddU4List((const uint32_t *)(void *)aobj->GetRawData(sizeof(uint32_t)), length);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500775 } else if (size == 8) {
Ian Rogersa15e67d2012-02-28 13:51:55 -0800776 rec->AddU8List((const uint64_t *)aobj->GetRawData(sizeof(uint64_t)), length);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500777 }
778#endif
779 }
780 } else {
781
782 // obj is an instance object.
783 rec->AddU1(HPROF_INSTANCE_DUMP);
784 rec->AddId((HprofObjectId)obj);
785 rec->AddU4(StackTraceSerialNumber(obj));
Elliott Hughese84278b2012-03-22 10:06:53 -0700786 rec->AddId(LookupClassId(c));
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500787
788 // Reserve some space for the length of the instance data, which we won't
789 // know until we're done writing it.
790 size_t sizePatchOffset = rec->length_;
791 rec->AddU4(0x77777777);
792
793 // Write the instance data; fields for this class, followed by super class fields,
794 // and so on. Don't write the klass or monitor fields of Object.class.
Elliott Hughese84278b2012-03-22 10:06:53 -0700795 const Class* sclass = c;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800796 FieldHelper fh;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500797 while (!sclass->IsObjectClass()) {
798 int ifieldCount = sclass->NumInstanceFields();
799 for (int i = 0; i < ifieldCount; i++) {
800 Field* f = sclass->GetInstanceField(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800801 fh.ChangeField(f);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500802 size_t size;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800803 SignatureToBasicTypeAndSize(fh.GetTypeDescriptor(), &size);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500804 if (size == 1) {
805 rec->AddU1(f->Get32(obj));
806 } else if (size == 2) {
807 rec->AddU2(f->Get32(obj));
808 } else if (size == 4) {
809 rec->AddU4(f->Get32(obj));
810 } else if (size == 8) {
811 rec->AddU8(f->Get64(obj));
812 } else {
813 CHECK(false);
814 }
815 }
816
817 sclass = sclass->GetSuperClass();
818 }
819
820 // Patch the instance field length.
821 size_t savedLen = rec->length_;
822 rec->length_ = sizePatchOffset;
823 rec->AddU4(savedLen - (sizePatchOffset + 4));
824 rec->length_ = savedLen;
825 }
826 }
827
828 objects_in_segment_++;
829 return 0;
830}
831
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400832#define kHeadSuffix "-hptemp"
833
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400834// TODO: use File::WriteFully
Jesse Wilson0b075f12011-11-09 10:57:41 -0500835int sysWriteFully(int fd, const void* buf, size_t count, const char* logMsg) {
836 while (count != 0) {
837 ssize_t actual = TEMP_FAILURE_RETRY(write(fd, buf, count));
838 if (actual < 0) {
839 int err = errno;
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700840 PLOG(ERROR) << StringPrintf("%s: write failed", logMsg);
Jesse Wilson0b075f12011-11-09 10:57:41 -0500841 return err;
842 } else if (actual != (ssize_t) count) {
843 LOG(DEBUG) << StringPrintf("%s: partial write (will retry): (%d of %zd)",
844 logMsg, (int) actual, count);
845 buf = (const void*) (((const uint8_t*) buf) + actual);
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400846 }
Jesse Wilson0b075f12011-11-09 10:57:41 -0500847 count -= actual;
848 }
849 return 0;
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400850}
851
Elliott Hughes622a6982012-06-08 17:58:54 -0700852void Hprof::Finish() {
Jesse Wilson0b075f12011-11-09 10:57:41 -0500853 // flush the "tail" portion of the output
854 StartNewRecord(HPROF_TAG_HEAP_DUMP_END, HPROF_TIME);
855 FlushCurrentRecord();
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400856
Jesse Wilson0b075f12011-11-09 10:57:41 -0500857 // create a new Hprof for the start of the file (as opposed to this, which is the tail)
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800858 Hprof headCtx(file_name_.c_str(), fd_, true, direct_to_ddms_);
Jesse Wilson0b075f12011-11-09 10:57:41 -0500859 headCtx.classes_ = classes_;
860 headCtx.strings_ = strings_;
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400861
Jesse Wilson0b075f12011-11-09 10:57:41 -0500862 headCtx.DumpStrings();
863 headCtx.DumpClasses();
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400864
Jesse Wilson0b075f12011-11-09 10:57:41 -0500865 // write a dummy stack trace record so the analysis tools don't freak out
866 headCtx.StartNewRecord(HPROF_TAG_STACK_TRACE, HPROF_TIME);
867 headCtx.current_record_.AddU4(HPROF_NULL_STACK_TRACE);
868 headCtx.current_record_.AddU4(HPROF_NULL_THREAD);
869 headCtx.current_record_.AddU4(0); // no frames
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400870
Jesse Wilson0b075f12011-11-09 10:57:41 -0500871 headCtx.FlushCurrentRecord();
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400872
Jesse Wilson0b075f12011-11-09 10:57:41 -0500873 // flush to ensure memstream pointer and size are updated
874 fflush(headCtx.mem_fp_);
875 fflush(mem_fp_);
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400876
Jesse Wilson0b075f12011-11-09 10:57:41 -0500877 if (direct_to_ddms_) {
878 // send the data off to DDMS
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700879 iovec iov[2];
Jesse Wilson0b075f12011-11-09 10:57:41 -0500880 iov[0].iov_base = headCtx.file_data_ptr_;
881 iov[0].iov_len = headCtx.file_data_size_;
882 iov[1].iov_base = file_data_ptr_;
883 iov[1].iov_len = file_data_size_;
884 Dbg::DdmSendChunkV(CHUNK_TYPE("HPDS"), iov, 2);
885 } else {
886 // open the output file, and copy the head and tail to it.
887 CHECK_EQ(headCtx.fd_, fd_);
888
889 int outFd;
890 if (headCtx.fd_ >= 0) {
891 outFd = dup(headCtx.fd_);
892 if (outFd < 0) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700893 Thread::Current()->ThrowNewExceptionF("Ljava/lang/RuntimeException;", "Couldn't dump heap; dup(%d) failed: %s", headCtx.fd_, strerror(errno));
894 return;
Jesse Wilson0b075f12011-11-09 10:57:41 -0500895 }
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400896 } else {
Elliott Hughes7b3cdfc2011-12-08 21:28:17 -0800897 outFd = open(file_name_.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0644);
Jesse Wilson0b075f12011-11-09 10:57:41 -0500898 if (outFd < 0) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700899 Thread::Current()->ThrowNewExceptionF("Ljava/lang/RuntimeException;", "Couldn't dump heap; open(\"%s\") failed: %s", headCtx.file_name_.c_str(), strerror(errno));
900 return;
Jesse Wilson0b075f12011-11-09 10:57:41 -0500901 }
902 }
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400903
Elliott Hughes622a6982012-06-08 17:58:54 -0700904 // TODO: just use writev(2)?
905 int result = sysWriteFully(outFd, headCtx.file_data_ptr_, headCtx.file_data_size_, "hprof-head");
Jesse Wilson0b075f12011-11-09 10:57:41 -0500906 result |= sysWriteFully(outFd, file_data_ptr_, file_data_size_, "hprof-tail");
907 close(outFd);
908 if (result != 0) {
Elliott Hughes622a6982012-06-08 17:58:54 -0700909 // TODO: better detail message.
910 Thread::Current()->ThrowNewExceptionF("Ljava/lang/RuntimeException;", "Couldn't dump heap; check log output for details");
911 return;
Jesse Wilson0b075f12011-11-09 10:57:41 -0500912 }
913 }
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400914
Jesse Wilson0b075f12011-11-09 10:57:41 -0500915 // throw out a log message for the benefit of "runhat"
Elliott Hughes409d2732012-04-03 13:34:44 -0700916 LOG(INFO) << "hprof: heap dump completed (" << PrettySize(headCtx.file_data_size_ + file_data_size_ + 1023) << ")";
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400917}
918
Jesse Wilson3aa66fd2011-11-08 20:53:40 -0500919Hprof::~Hprof() {
Jesse Wilson0b075f12011-11-09 10:57:41 -0500920 // we don't own ctx->fd_, do not close
921 if (mem_fp_ != NULL) {
922 fclose(mem_fp_);
923 }
924 free(current_record_.body_);
Jesse Wilson0b075f12011-11-09 10:57:41 -0500925 free(file_data_ptr_);
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400926}
927
Jesse Wilson3aa66fd2011-11-08 20:53:40 -0500928void Hprof::VisitRoot(const Object* obj) {
Jesse Wilson0b075f12011-11-09 10:57:41 -0500929 uint32_t threadId = 0; // TODO
930 /*RootType */ size_t type = 0; // TODO
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400931
Jesse Wilson0b075f12011-11-09 10:57:41 -0500932 static const HprofHeapTag xlate[] = {
933 HPROF_ROOT_UNKNOWN,
934 HPROF_ROOT_JNI_GLOBAL,
935 HPROF_ROOT_JNI_LOCAL,
936 HPROF_ROOT_JAVA_FRAME,
937 HPROF_ROOT_NATIVE_STACK,
938 HPROF_ROOT_STICKY_CLASS,
939 HPROF_ROOT_THREAD_BLOCK,
940 HPROF_ROOT_MONITOR_USED,
941 HPROF_ROOT_THREAD_OBJECT,
942 HPROF_ROOT_INTERNED_STRING,
943 HPROF_ROOT_FINALIZING,
944 HPROF_ROOT_DEBUGGER,
945 HPROF_ROOT_REFERENCE_CLEANUP,
946 HPROF_ROOT_VM_INTERNAL,
947 HPROF_ROOT_JNI_MONITOR,
948 };
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400949
Jesse Wilson0b075f12011-11-09 10:57:41 -0500950 CHECK_LT(type, sizeof(xlate) / sizeof(HprofHeapTag));
951 if (obj == NULL) {
952 return;
953 }
954 gc_scan_state_ = xlate[type];
955 gc_thread_serial_number_ = threadId;
956 MarkRootObject(obj, 0);
957 gc_scan_state_ = 0;
958 gc_thread_serial_number_ = 0;
Jesse Wilsonc4824e62011-11-01 14:39:04 -0400959}
960
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500961HprofStringId Hprof::LookupStringId(String* string) {
962 return LookupStringId(string->ToModifiedUtf8());
963}
964
965HprofStringId Hprof::LookupStringId(const char* string) {
966 return LookupStringId(std::string(string));
967}
968
Elliott Hughesae80b492012-04-24 10:43:17 -0700969HprofStringId Hprof::LookupStringId(const std::string& string) {
Elliott Hughesa0e18062012-04-13 15:59:59 -0700970 StringMapIterator it = strings_.find(string);
971 if (it != strings_.end()) {
972 return it->second;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500973 }
Elliott Hughesa0e18062012-04-13 15:59:59 -0700974 HprofStringId id = next_string_id_++;
975 strings_.Put(string, id);
976 return id;
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500977}
978
979int Hprof::DumpStrings() {
980 HprofRecord *rec = &current_record_;
981
982 for (StringMapIterator it = strings_.begin(); it != strings_.end(); ++it) {
Elliott Hughes95572412011-12-13 18:14:20 -0800983 std::string string((*it).first);
Jesse Wilson0c54ac12011-11-09 15:14:05 -0500984 size_t id = (*it).second;
985
986 int err = StartNewRecord(HPROF_TAG_STRING, HPROF_TIME);
987 if (err != 0) {
988 return err;
989 }
990
991 // STRING format:
992 // ID: ID for this string
993 // U1*: UTF8 characters for string (NOT NULL terminated)
994 // (the record format encodes the length)
995 err = rec->AddU4(id);
996 if (err != 0) {
997 return err;
998 }
999 err = rec->AddUtf8String(string.c_str());
1000 if (err != 0) {
1001 return err;
1002 }
1003 }
1004
1005 return 0;
1006}
1007
Elliott Hughese84278b2012-03-22 10:06:53 -07001008HprofStringId Hprof::LookupClassNameId(Class* c) {
1009 return LookupStringId(PrettyDescriptor(c));
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001010}
1011
Elliott Hughese84278b2012-03-22 10:06:53 -07001012HprofClassObjectId Hprof::LookupClassId(Class* c) {
1013 if (c == NULL) {
1014 // c is the superclass of java.lang.Object or a primitive
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001015 return (HprofClassObjectId)0;
1016 }
1017
Elliott Hughese84278b2012-03-22 10:06:53 -07001018 std::pair<ClassSetIterator, bool> result = classes_.insert(c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001019 Class* present = *result.first;
1020
1021 // Make sure that we've assigned a string ID for this class' name
Elliott Hughese84278b2012-03-22 10:06:53 -07001022 LookupClassNameId(c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001023
Elliott Hughese84278b2012-03-22 10:06:53 -07001024 CHECK_EQ(present, c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001025 return (HprofStringId) present;
1026}
1027
1028int Hprof::DumpClasses() {
1029 HprofRecord *rec = &current_record_;
1030 uint32_t nextSerialNumber = 1;
1031
1032 for (ClassSetIterator it = classes_.begin(); it != classes_.end(); ++it) {
Elliott Hughese84278b2012-03-22 10:06:53 -07001033 Class* c = *it;
1034 CHECK(c != NULL);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001035
1036 int err = StartNewRecord(HPROF_TAG_LOAD_CLASS, HPROF_TIME);
1037 if (err != 0) {
1038 return err;
1039 }
1040
1041 // LOAD CLASS format:
1042 // U4: class serial number (always > 0)
1043 // ID: class object ID. We use the address of the class object structure as its ID.
1044 // U4: stack trace serial number
1045 // ID: class name string ID
1046 rec->AddU4(nextSerialNumber++);
Elliott Hughese84278b2012-03-22 10:06:53 -07001047 rec->AddId((HprofClassObjectId) c);
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001048 rec->AddU4(HPROF_NULL_STACK_TRACE);
Elliott Hughese84278b2012-03-22 10:06:53 -07001049 rec->AddId(LookupClassNameId(c));
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001050 }
1051
1052 return 0;
1053}
1054
Elliott Hughes622a6982012-06-08 17:58:54 -07001055static void HprofRootVisitor(const Object* obj, void* arg) {
Jesse Wilson0c54ac12011-11-09 15:14:05 -05001056 CHECK(arg != NULL);
1057 Hprof* hprof = (Hprof*)arg;
1058 hprof->VisitRoot(obj);
1059}
1060
Elliott Hughes622a6982012-06-08 17:58:54 -07001061static void HprofBitmapCallback(Object *obj, void *arg) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001062 CHECK(obj != NULL);
1063 CHECK(arg != NULL);
1064 Hprof *hprof = (Hprof*)arg;
1065 hprof->DumpHeapObject(obj);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001066}
1067
1068/*
1069 * Walk the roots and heap writing heap information to the specified
1070 * file.
1071 *
1072 * If "fd" is >= 0, the output will be written to that file descriptor.
Jesse Wilson3aa66fd2011-11-08 20:53:40 -05001073 * Otherwise, "file_name_" is used to create an output file.
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001074 *
Jesse Wilson3aa66fd2011-11-08 20:53:40 -05001075 * If "direct_to_ddms_" is set, the other arguments are ignored, and data is
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001076 * sent directly to DDMS.
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001077 */
Elliott Hughes622a6982012-06-08 17:58:54 -07001078void DumpHeap(const char* fileName, int fd, bool direct_to_ddms) {
Jesse Wilson0b075f12011-11-09 10:57:41 -05001079 CHECK(fileName != NULL);
Elliott Hughesffb465f2012-03-01 18:46:05 -08001080 ScopedHeapLock heap_lock;
Elliott Hughes34e06962012-04-09 13:55:55 -07001081 ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001082
Jesse Wilson0b075f12011-11-09 10:57:41 -05001083 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1084 thread_list->SuspendAll();
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001085
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001086 Runtime* runtime = Runtime::Current();
Elliott Hughes622a6982012-06-08 17:58:54 -07001087 Hprof hprof(fileName, fd, false, direct_to_ddms);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001088 runtime->VisitRoots(HprofRootVisitor, &hprof);
1089 runtime->GetHeap()->GetLiveBits()->Walk(HprofBitmapCallback, &hprof);
Jesse Wilson0b075f12011-11-09 10:57:41 -05001090 // TODO: write a HEAP_SUMMARY record
Elliott Hughes622a6982012-06-08 17:58:54 -07001091 hprof.Finish();
Jesse Wilson0b075f12011-11-09 10:57:41 -05001092 thread_list->ResumeAll();
Jesse Wilsonc4824e62011-11-01 14:39:04 -04001093}
1094
1095} // namespace hprof
1096
1097} // namespace art