1 /*
2 * Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "jvm.h"
27 #include "classfile/symbolTable.hpp"
28 #include "classfile/systemDictionary.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "gc/shared/gcLocker.hpp"
31 #include "gc/shared/vmGCOperations.hpp"
32 #include "memory/allocation.inline.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "memory/universe.hpp"
35 #include "oops/objArrayKlass.hpp"
36 #include "oops/objArrayOop.inline.hpp"
37 #include "oops/oop.inline.hpp"
38 #include "oops/typeArrayOop.inline.hpp"
39 #include "runtime/frame.inline.hpp"
40 #include "runtime/handles.inline.hpp"
41 #include "runtime/javaCalls.hpp"
42 #include "runtime/jniHandles.hpp"
43 #include "runtime/os.inline.hpp"
44 #include "runtime/reflectionUtils.hpp"
45 #include "runtime/thread.inline.hpp"
46 #include "runtime/threadSMR.hpp"
47 #include "runtime/vframe.hpp"
48 #include "runtime/vmThread.hpp"
49 #include "runtime/vmOperations.hpp"
50 #include "services/heapDumper.hpp"
51 #include "services/threadService.hpp"
52 #include "utilities/macros.hpp"
53 #include "utilities/ostream.hpp"
54
55 /*
56 * HPROF binary format - description copied from:
57 * src/share/demo/jvmti/hprof/hprof_io.c
58 *
59 *
60 * header "JAVA PROFILE 1.0.2" (0-terminated)
61 *
62 * u4 size of identifiers. Identifiers are used to represent
63 * UTF8 strings, objects, stack traces, etc. They usually
64 * have the same size as host pointers. For example, on
65 * Solaris and Win32, the size is 4.
66 * u4 high word
67 * u4 low word number of milliseconds since 0:00 GMT, 1/1/70
68 * [record]* a sequence of records.
69 *
70 *
71 * Record format:
72 *
73 * u1 a TAG denoting the type of the record
74 * u4 number of *microseconds* since the time stamp in the
75 * header. (wraps around in a little more than an hour)
76 * u4 number of bytes *remaining* in the record. Note that
77 * this number excludes the tag and the length field itself.
78 * [u1]* BODY of the record (a sequence of bytes)
79 *
80 *
81 * The following TAGs are supported:
82 *
83 * TAG BODY notes
84 *----------------------------------------------------------
85 * HPROF_UTF8 a UTF8-encoded name
86 *
87 * id name ID
88 * [u1]* UTF8 characters (no trailing zero)
89 *
90 * HPROF_LOAD_CLASS a newly loaded class
91 *
92 * u4 class serial number (> 0)
93 * id class object ID
94 * u4 stack trace serial number
95 * id class name ID
96 *
97 * HPROF_UNLOAD_CLASS an unloading class
98 *
99 * u4 class serial_number
100 *
101 * HPROF_FRAME a Java stack frame
102 *
103 * id stack frame ID
104 * id method name ID
105 * id method signature ID
106 * id source file name ID
107 * u4 class serial number
108 * i4 line number. >0: normal
109 * -1: unknown
110 * -2: compiled method
111 * -3: native method
112 *
113 * HPROF_TRACE a Java stack trace
114 *
115 * u4 stack trace serial number
116 * u4 thread serial number
117 * u4 number of frames
118 * [id]* stack frame IDs
119 *
120 *
121 * HPROF_ALLOC_SITES a set of heap allocation sites, obtained after GC
122 *
123 * u2 flags 0x0001: incremental vs. complete
124 * 0x0002: sorted by allocation vs. live
125 * 0x0004: whether to force a GC
126 * u4 cutoff ratio
127 * u4 total live bytes
128 * u4 total live instances
129 * u8 total bytes allocated
130 * u8 total instances allocated
131 * u4 number of sites that follow
132 * [u1 is_array: 0: normal object
133 * 2: object array
134 * 4: boolean array
135 * 5: char array
136 * 6: float array
137 * 7: double array
138 * 8: byte array
139 * 9: short array
140 * 10: int array
141 * 11: long array
142 * u4 class serial number (may be zero during startup)
143 * u4 stack trace serial number
144 * u4 number of bytes alive
145 * u4 number of instances alive
146 * u4 number of bytes allocated
147 * u4]* number of instance allocated
148 *
149 * HPROF_START_THREAD a newly started thread.
150 *
151 * u4 thread serial number (> 0)
152 * id thread object ID
153 * u4 stack trace serial number
154 * id thread name ID
155 * id thread group name ID
156 * id thread group parent name ID
157 *
158 * HPROF_END_THREAD a terminating thread.
159 *
160 * u4 thread serial number
161 *
162 * HPROF_HEAP_SUMMARY heap summary
163 *
164 * u4 total live bytes
165 * u4 total live instances
166 * u8 total bytes allocated
167 * u8 total instances allocated
168 *
169 * HPROF_HEAP_DUMP denote a heap dump
170 *
171 * [heap dump sub-records]*
172 *
173 * There are four kinds of heap dump sub-records:
174 *
175 * u1 sub-record type
176 *
177 * HPROF_GC_ROOT_UNKNOWN unknown root
178 *
179 * id object ID
180 *
181 * HPROF_GC_ROOT_THREAD_OBJ thread object
182 *
183 * id thread object ID (may be 0 for a
184 * thread newly attached through JNI)
185 * u4 thread sequence number
186 * u4 stack trace sequence number
187 *
188 * HPROF_GC_ROOT_JNI_GLOBAL JNI global ref root
189 *
190 * id object ID
191 * id JNI global ref ID
192 *
193 * HPROF_GC_ROOT_JNI_LOCAL JNI local ref
194 *
195 * id object ID
196 * u4 thread serial number
197 * u4 frame # in stack trace (-1 for empty)
198 *
199 * HPROF_GC_ROOT_JAVA_FRAME Java stack frame
200 *
201 * id object ID
202 * u4 thread serial number
203 * u4 frame # in stack trace (-1 for empty)
204 *
205 * HPROF_GC_ROOT_NATIVE_STACK Native stack
206 *
207 * id object ID
208 * u4 thread serial number
209 *
210 * HPROF_GC_ROOT_STICKY_CLASS System class
211 *
212 * id object ID
213 *
214 * HPROF_GC_ROOT_THREAD_BLOCK Reference from thread block
215 *
216 * id object ID
217 * u4 thread serial number
218 *
219 * HPROF_GC_ROOT_MONITOR_USED Busy monitor
220 *
221 * id object ID
222 *
223 * HPROF_GC_CLASS_DUMP dump of a class object
224 *
225 * id class object ID
226 * u4 stack trace serial number
227 * id super class object ID
228 * id class loader object ID
229 * id signers object ID
230 * id protection domain object ID
231 * id reserved
232 * id reserved
233 *
234 * u4 instance size (in bytes)
235 *
236 * u2 size of constant pool
237 * [u2, constant pool index,
238 * ty, type
239 * 2: object
240 * 4: boolean
241 * 5: char
242 * 6: float
243 * 7: double
244 * 8: byte
245 * 9: short
246 * 10: int
247 * 11: long
248 * vl]* and value
249 *
250 * u2 number of static fields
251 * [id, static field name,
252 * ty, type,
253 * vl]* and value
254 *
255 * u2 number of inst. fields (not inc. super)
256 * [id, instance field name,
257 * ty]* type
258 *
259 * HPROF_GC_INSTANCE_DUMP dump of a normal object
260 *
261 * id object ID
262 * u4 stack trace serial number
263 * id class object ID
264 * u4 number of bytes that follow
265 * [vl]* instance field values (class, followed
266 * by super, super's super ...)
267 *
268 * HPROF_GC_OBJ_ARRAY_DUMP dump of an object array
269 *
270 * id array object ID
271 * u4 stack trace serial number
272 * u4 number of elements
273 * id array class ID
274 * [id]* elements
275 *
276 * HPROF_GC_PRIM_ARRAY_DUMP dump of a primitive array
277 *
278 * id array object ID
279 * u4 stack trace serial number
280 * u4 number of elements
281 * u1 element type
282 * 4: boolean array
283 * 5: char array
284 * 6: float array
285 * 7: double array
286 * 8: byte array
287 * 9: short array
288 * 10: int array
289 * 11: long array
290 * [u1]* elements
291 *
292 * HPROF_CPU_SAMPLES a set of sample traces of running threads
293 *
294 * u4 total number of samples
295 * u4 # of traces
296 * [u4 # of samples
297 * u4]* stack trace serial number
298 *
299 * HPROF_CONTROL_SETTINGS the settings of on/off switches
300 *
301 * u4 0x00000001: alloc traces on/off
302 * 0x00000002: cpu sampling on/off
303 * u2 stack trace depth
304 *
305 *
306 * When the header is "JAVA PROFILE 1.0.2" a heap dump can optionally
307 * be generated as a sequence of heap dump segments. This sequence is
308 * terminated by an end record. The additional tags allowed by format
309 * "JAVA PROFILE 1.0.2" are:
310 *
311 * HPROF_HEAP_DUMP_SEGMENT denote a heap dump segment
312 *
313 * [heap dump sub-records]*
314 * The same sub-record types allowed by HPROF_HEAP_DUMP
315 *
316 * HPROF_HEAP_DUMP_END denotes the end of a heap dump
317 *
318 */
319
320
321 // HPROF tags
322
323 typedef enum {
324 // top-level records
325 HPROF_UTF8 = 0x01,
326 HPROF_LOAD_CLASS = 0x02,
327 HPROF_UNLOAD_CLASS = 0x03,
328 HPROF_FRAME = 0x04,
329 HPROF_TRACE = 0x05,
330 HPROF_ALLOC_SITES = 0x06,
331 HPROF_HEAP_SUMMARY = 0x07,
332 HPROF_START_THREAD = 0x0A,
333 HPROF_END_THREAD = 0x0B,
334 HPROF_HEAP_DUMP = 0x0C,
335 HPROF_CPU_SAMPLES = 0x0D,
336 HPROF_CONTROL_SETTINGS = 0x0E,
337
338 // 1.0.2 record types
339 HPROF_HEAP_DUMP_SEGMENT = 0x1C,
340 HPROF_HEAP_DUMP_END = 0x2C,
341
342 // field types
343 HPROF_ARRAY_OBJECT = 0x01,
344 HPROF_NORMAL_OBJECT = 0x02,
345 HPROF_BOOLEAN = 0x04,
346 HPROF_CHAR = 0x05,
347 HPROF_FLOAT = 0x06,
348 HPROF_DOUBLE = 0x07,
349 HPROF_BYTE = 0x08,
350 HPROF_SHORT = 0x09,
351 HPROF_INT = 0x0A,
352 HPROF_LONG = 0x0B,
353
354 // data-dump sub-records
355 HPROF_GC_ROOT_UNKNOWN = 0xFF,
356 HPROF_GC_ROOT_JNI_GLOBAL = 0x01,
357 HPROF_GC_ROOT_JNI_LOCAL = 0x02,
358 HPROF_GC_ROOT_JAVA_FRAME = 0x03,
359 HPROF_GC_ROOT_NATIVE_STACK = 0x04,
360 HPROF_GC_ROOT_STICKY_CLASS = 0x05,
361 HPROF_GC_ROOT_THREAD_BLOCK = 0x06,
362 HPROF_GC_ROOT_MONITOR_USED = 0x07,
363 HPROF_GC_ROOT_THREAD_OBJ = 0x08,
364 HPROF_GC_CLASS_DUMP = 0x20,
365 HPROF_GC_INSTANCE_DUMP = 0x21,
366 HPROF_GC_OBJ_ARRAY_DUMP = 0x22,
367 HPROF_GC_PRIM_ARRAY_DUMP = 0x23
368 } hprofTag;
369
370 // Default stack trace ID (used for dummy HPROF_TRACE record)
371 enum {
372 STACK_TRACE_ID = 1,
373 INITIAL_CLASS_COUNT = 200
374 };
375
376 // Supports I/O operations on a dump file
377
378 class DumpWriter : public StackObj {
379 private:
380 enum {
381 io_buffer_max_size = 8*M,
382 io_buffer_min_size = 64*K,
383 dump_segment_header_size = 9
384 };
385
386 int _fd; // file descriptor (-1 if dump file not open)
387 julong _bytes_written; // number of byte written to dump file
388
389 char* _buffer; // internal buffer
390 size_t _size;
391 size_t _pos;
392
393 bool _in_dump_segment; // Are we currently in a dump segment?
394 bool _is_huge_sub_record; // Are we writing a sub-record larger than the buffer size?
395 DEBUG_ONLY(size_t _sub_record_left;) // The bytes not written for the current sub-record.
396 DEBUG_ONLY(bool _sub_record_ended;) // True if we have called the end_sub_record().
397
398 char* _error; // error message when I/O fails
399
set_file_descriptor(int fd)400 void set_file_descriptor(int fd) { _fd = fd; }
file_descriptor() const401 int file_descriptor() const { return _fd; }
402
is_open() const403 bool is_open() const { return file_descriptor() >= 0; }
404 void flush();
405
buffer() const406 char* buffer() const { return _buffer; }
buffer_size() const407 size_t buffer_size() const { return _size; }
position() const408 size_t position() const { return _pos; }
set_position(size_t pos)409 void set_position(size_t pos) { _pos = pos; }
410
set_error(const char * error)411 void set_error(const char* error) { _error = (char*)os::strdup(error); }
412
413 // all I/O go through this function
414 void write_internal(void* s, size_t len);
415
416 public:
417 DumpWriter(const char* path, bool overwrite);
418 ~DumpWriter();
419
420 void close();
421
422 // total number of bytes written to the disk
bytes_written() const423 julong bytes_written() const { return _bytes_written; }
424
error() const425 char* error() const { return _error; }
426
427 // writer functions
428 void write_raw(void* s, size_t len);
write_u1(u1 x)429 void write_u1(u1 x) { write_raw((void*)&x, 1); }
430 void write_u2(u2 x);
431 void write_u4(u4 x);
432 void write_u8(u8 x);
433 void write_objectID(oop o);
434 void write_symbolID(Symbol* o);
435 void write_classID(Klass* k);
436 void write_id(u4 x);
437
438 // Start a new sub-record. Starts a new heap dump segment if needed.
439 void start_sub_record(u1 tag, u4 len);
440 // Ends the current sub-record.
441 void end_sub_record();
442 // Finishes the current dump segment if not already finished.
443 void finish_dump_segment();
444 };
445
DumpWriter(const char * path,bool overwrite)446 DumpWriter::DumpWriter(const char* path, bool overwrite) : _fd(-1), _bytes_written(0), _pos(0),
447 _in_dump_segment(false), _error(NULL) {
448 // try to allocate an I/O buffer of io_buffer_size. If there isn't
449 // sufficient memory then reduce size until we can allocate something.
450 _size = io_buffer_max_size;
451 do {
452 _buffer = (char*)os::malloc(_size, mtInternal);
453 if (_buffer == NULL) {
454 _size = _size >> 1;
455 }
456 } while (_buffer == NULL && _size >= io_buffer_min_size);
457
458 if (_buffer == NULL) {
459 set_error("Could not allocate buffer memory for heap dump");
460 } else {
461 _fd = os::create_binary_file(path, overwrite); // don't replace existing file
462
463 // if the open failed we record the error
464 if (_fd < 0) {
465 set_error(os::strerror(errno));
466 }
467 }
468 }
469
~DumpWriter()470 DumpWriter::~DumpWriter() {
471 close();
472 os::free(_buffer);
473 os::free(_error);
474 }
475
476 // closes dump file (if open)
close()477 void DumpWriter::close() {
478 // flush and close dump file
479 if (is_open()) {
480 flush();
481 os::close(file_descriptor());
482 set_file_descriptor(-1);
483 }
484 }
485
486 // write directly to the file
write_internal(void * s,size_t len)487 void DumpWriter::write_internal(void* s, size_t len) {
488 if (is_open()) {
489 const char* pos = (char*)s;
490 ssize_t n = 0;
491 while (len > 0) {
492 uint tmp = (uint)MIN2(len, (size_t)INT_MAX);
493 n = os::write(file_descriptor(), pos, tmp);
494
495 if (n < 0) {
496 // EINTR cannot happen here, os::write will take care of that
497 set_error(os::strerror(errno));
498 os::close(file_descriptor());
499 set_file_descriptor(-1);
500 return;
501 }
502
503 _bytes_written += n;
504 pos += n;
505 len -= n;
506 }
507 }
508 }
509
510 // write raw bytes
write_raw(void * s,size_t len)511 void DumpWriter::write_raw(void* s, size_t len) {
512 assert(!_in_dump_segment || (_sub_record_left >= len), "sub-record too large");
513 debug_only(_sub_record_left -= len);
514
515 // flush buffer to make room
516 if (len > buffer_size() - position()) {
517 assert(!_in_dump_segment || _is_huge_sub_record, "Cannot overflow in non-huge sub-record.");
518 flush();
519
520 // If larger than the buffer, just write it directly.
521 if (len > buffer_size()) {
522 write_internal(s, len);
523
524 return;
525 }
526 }
527
528 memcpy(buffer() + position(), s, len);
529 set_position(position() + len);
530 }
531
532 // flush any buffered bytes to the file
flush()533 void DumpWriter::flush() {
534 write_internal(buffer(), position());
535 set_position(0);
536 }
537
write_u2(u2 x)538 void DumpWriter::write_u2(u2 x) {
539 u2 v;
540 Bytes::put_Java_u2((address)&v, x);
541 write_raw((void*)&v, 2);
542 }
543
write_u4(u4 x)544 void DumpWriter::write_u4(u4 x) {
545 u4 v;
546 Bytes::put_Java_u4((address)&v, x);
547 write_raw((void*)&v, 4);
548 }
549
write_u8(u8 x)550 void DumpWriter::write_u8(u8 x) {
551 u8 v;
552 Bytes::put_Java_u8((address)&v, x);
553 write_raw((void*)&v, 8);
554 }
555
write_objectID(oop o)556 void DumpWriter::write_objectID(oop o) {
557 address a = (address)o;
558 #ifdef _LP64
559 write_u8((u8)a);
560 #else
561 write_u4((u4)a);
562 #endif
563 }
564
write_symbolID(Symbol * s)565 void DumpWriter::write_symbolID(Symbol* s) {
566 address a = (address)((uintptr_t)s);
567 #ifdef _LP64
568 write_u8((u8)a);
569 #else
570 write_u4((u4)a);
571 #endif
572 }
573
write_id(u4 x)574 void DumpWriter::write_id(u4 x) {
575 #ifdef _LP64
576 write_u8((u8) x);
577 #else
578 write_u4(x);
579 #endif
580 }
581
582 // We use java mirror as the class ID
write_classID(Klass * k)583 void DumpWriter::write_classID(Klass* k) {
584 write_objectID(k->java_mirror());
585 }
586
finish_dump_segment()587 void DumpWriter::finish_dump_segment() {
588 if (_in_dump_segment) {
589 assert(_sub_record_left == 0, "Last sub-record not written completely");
590 assert(_sub_record_ended, "sub-record must have ended");
591
592 // Fix up the dump segment length if we haven't written a huge sub-record last
593 // (in which case the segment length was already set to the correct value initially).
594 if (!_is_huge_sub_record) {
595 assert(position() > dump_segment_header_size, "Dump segment should have some content");
596 Bytes::put_Java_u4((address) (buffer() + 5), (u4) (position() - dump_segment_header_size));
597 }
598
599 flush();
600 _in_dump_segment = false;
601 }
602 }
603
start_sub_record(u1 tag,u4 len)604 void DumpWriter::start_sub_record(u1 tag, u4 len) {
605 if (!_in_dump_segment) {
606 if (position() > 0) {
607 flush();
608 assert(position() == 0, "Must be at the start");
609 }
610
611 write_u1(HPROF_HEAP_DUMP_SEGMENT);
612 write_u4(0); // timestamp
613 // Will be fixed up later if we add more sub-records. If this is a huge sub-record,
614 // this is already the correct length, since we don't add more sub-records.
615 write_u4(len);
616 _in_dump_segment = true;
617 _is_huge_sub_record = len > buffer_size() - dump_segment_header_size;
618 } else if (_is_huge_sub_record || (len > buffer_size() - position())) {
619 // This object will not fit in completely or the last sub-record was huge.
620 // Finish the current segement and try again.
621 finish_dump_segment();
622 start_sub_record(tag, len);
623
624 return;
625 }
626
627 debug_only(_sub_record_left = len);
628 debug_only(_sub_record_ended = false);
629
630 write_u1(tag);
631 }
632
end_sub_record()633 void DumpWriter::end_sub_record() {
634 assert(_in_dump_segment, "must be in dump segment");
635 assert(_sub_record_left == 0, "sub-record not written completely");
636 assert(!_sub_record_ended, "Must not have ended yet");
637 debug_only(_sub_record_ended = true);
638 }
639
640 // Support class with a collection of functions used when dumping the heap
641
642 class DumperSupport : AllStatic {
643 public:
644
645 // write a header of the given type
646 static void write_header(DumpWriter* writer, hprofTag tag, u4 len);
647
648 // returns hprof tag for the given type signature
649 static hprofTag sig2tag(Symbol* sig);
650 // returns hprof tag for the given basic type
651 static hprofTag type2tag(BasicType type);
652 // Returns the size of the data to write.
653 static u4 sig2size(Symbol* sig);
654
655 // returns the size of the instance of the given class
656 static u4 instance_size(Klass* k);
657
658 // dump a jfloat
659 static void dump_float(DumpWriter* writer, jfloat f);
660 // dump a jdouble
661 static void dump_double(DumpWriter* writer, jdouble d);
662 // dumps the raw value of the given field
663 static void dump_field_value(DumpWriter* writer, char type, oop obj, int offset);
664 // returns the size of the static fields; also counts the static fields
665 static u4 get_static_fields_size(InstanceKlass* ik, u2& field_count);
666 // dumps static fields of the given class
667 static void dump_static_fields(DumpWriter* writer, Klass* k);
668 // dump the raw values of the instance fields of the given object
669 static void dump_instance_fields(DumpWriter* writer, oop o);
670 // get the count of the instance fields for a given class
671 static u2 get_instance_fields_count(InstanceKlass* ik);
672 // dumps the definition of the instance fields for a given class
673 static void dump_instance_field_descriptors(DumpWriter* writer, Klass* k);
674 // creates HPROF_GC_INSTANCE_DUMP record for the given object
675 static void dump_instance(DumpWriter* writer, oop o);
676 // creates HPROF_GC_CLASS_DUMP record for the given class and each of its
677 // array classes
678 static void dump_class_and_array_classes(DumpWriter* writer, Klass* k);
679 // creates HPROF_GC_CLASS_DUMP record for a given primitive array
680 // class (and each multi-dimensional array class too)
681 static void dump_basic_type_array_class(DumpWriter* writer, Klass* k);
682
683 // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
684 static void dump_object_array(DumpWriter* writer, objArrayOop array);
685 // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
686 static void dump_prim_array(DumpWriter* writer, typeArrayOop array);
687 // create HPROF_FRAME record for the given method and bci
688 static void dump_stack_frame(DumpWriter* writer, int frame_serial_num, int class_serial_num, Method* m, int bci);
689
690 // check if we need to truncate an array
691 static int calculate_array_max_length(DumpWriter* writer, arrayOop array, short header_size);
692
693 // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record
694 static void end_of_dump(DumpWriter* writer);
695
mask_dormant_archived_object(oop o)696 static oop mask_dormant_archived_object(oop o) {
697 if (o != NULL && o->klass()->java_mirror() == NULL) {
698 // Ignore this object since the corresponding java mirror is not loaded.
699 // Might be a dormant archive object.
700 return NULL;
701 } else {
702 return o;
703 }
704 }
705 };
706
707 // write a header of the given type
write_header(DumpWriter * writer,hprofTag tag,u4 len)708 void DumperSupport:: write_header(DumpWriter* writer, hprofTag tag, u4 len) {
709 writer->write_u1((u1)tag);
710 writer->write_u4(0); // current ticks
711 writer->write_u4(len);
712 }
713
714 // returns hprof tag for the given type signature
sig2tag(Symbol * sig)715 hprofTag DumperSupport::sig2tag(Symbol* sig) {
716 switch (sig->byte_at(0)) {
717 case JVM_SIGNATURE_CLASS : return HPROF_NORMAL_OBJECT;
718 case JVM_SIGNATURE_ARRAY : return HPROF_NORMAL_OBJECT;
719 case JVM_SIGNATURE_BYTE : return HPROF_BYTE;
720 case JVM_SIGNATURE_CHAR : return HPROF_CHAR;
721 case JVM_SIGNATURE_FLOAT : return HPROF_FLOAT;
722 case JVM_SIGNATURE_DOUBLE : return HPROF_DOUBLE;
723 case JVM_SIGNATURE_INT : return HPROF_INT;
724 case JVM_SIGNATURE_LONG : return HPROF_LONG;
725 case JVM_SIGNATURE_SHORT : return HPROF_SHORT;
726 case JVM_SIGNATURE_BOOLEAN : return HPROF_BOOLEAN;
727 default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
728 }
729 }
730
type2tag(BasicType type)731 hprofTag DumperSupport::type2tag(BasicType type) {
732 switch (type) {
733 case T_BYTE : return HPROF_BYTE;
734 case T_CHAR : return HPROF_CHAR;
735 case T_FLOAT : return HPROF_FLOAT;
736 case T_DOUBLE : return HPROF_DOUBLE;
737 case T_INT : return HPROF_INT;
738 case T_LONG : return HPROF_LONG;
739 case T_SHORT : return HPROF_SHORT;
740 case T_BOOLEAN : return HPROF_BOOLEAN;
741 default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
742 }
743 }
744
sig2size(Symbol * sig)745 u4 DumperSupport::sig2size(Symbol* sig) {
746 switch (sig->byte_at(0)) {
747 case JVM_SIGNATURE_CLASS:
748 case JVM_SIGNATURE_ARRAY: return sizeof(address);
749 case JVM_SIGNATURE_BOOLEAN:
750 case JVM_SIGNATURE_BYTE: return 1;
751 case JVM_SIGNATURE_SHORT:
752 case JVM_SIGNATURE_CHAR: return 2;
753 case JVM_SIGNATURE_INT:
754 case JVM_SIGNATURE_FLOAT: return 4;
755 case JVM_SIGNATURE_LONG:
756 case JVM_SIGNATURE_DOUBLE: return 8;
757 default: ShouldNotReachHere(); /* to shut up compiler */ return 0;
758 }
759 }
760
761 // dump a jfloat
dump_float(DumpWriter * writer,jfloat f)762 void DumperSupport::dump_float(DumpWriter* writer, jfloat f) {
763 if (g_isnan(f)) {
764 writer->write_u4(0x7fc00000); // collapsing NaNs
765 } else {
766 union {
767 int i;
768 float f;
769 } u;
770 u.f = (float)f;
771 writer->write_u4((u4)u.i);
772 }
773 }
774
775 // dump a jdouble
dump_double(DumpWriter * writer,jdouble d)776 void DumperSupport::dump_double(DumpWriter* writer, jdouble d) {
777 union {
778 jlong l;
779 double d;
780 } u;
781 if (g_isnan(d)) { // collapsing NaNs
782 u.l = (jlong)(0x7ff80000);
783 u.l = (u.l << 32);
784 } else {
785 u.d = (double)d;
786 }
787 writer->write_u8((u8)u.l);
788 }
789
790 // dumps the raw value of the given field
dump_field_value(DumpWriter * writer,char type,oop obj,int offset)791 void DumperSupport::dump_field_value(DumpWriter* writer, char type, oop obj, int offset) {
792 switch (type) {
793 case JVM_SIGNATURE_CLASS :
794 case JVM_SIGNATURE_ARRAY : {
795 oop o = obj->obj_field_access<ON_UNKNOWN_OOP_REF | AS_NO_KEEPALIVE>(offset);
796 if (o != NULL && log_is_enabled(Debug, cds, heap) && mask_dormant_archived_object(o) == NULL) {
797 ResourceMark rm;
798 log_debug(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s) referenced by " INTPTR_FORMAT " (%s)",
799 p2i(o), o->klass()->external_name(),
800 p2i(obj), obj->klass()->external_name());
801 }
802 o = mask_dormant_archived_object(o);
803 assert(oopDesc::is_oop_or_null(o), "Expected an oop or NULL at " PTR_FORMAT, p2i(o));
804 writer->write_objectID(o);
805 break;
806 }
807 case JVM_SIGNATURE_BYTE : {
808 jbyte b = obj->byte_field(offset);
809 writer->write_u1((u1)b);
810 break;
811 }
812 case JVM_SIGNATURE_CHAR : {
813 jchar c = obj->char_field(offset);
814 writer->write_u2((u2)c);
815 break;
816 }
817 case JVM_SIGNATURE_SHORT : {
818 jshort s = obj->short_field(offset);
819 writer->write_u2((u2)s);
820 break;
821 }
822 case JVM_SIGNATURE_FLOAT : {
823 jfloat f = obj->float_field(offset);
824 dump_float(writer, f);
825 break;
826 }
827 case JVM_SIGNATURE_DOUBLE : {
828 jdouble d = obj->double_field(offset);
829 dump_double(writer, d);
830 break;
831 }
832 case JVM_SIGNATURE_INT : {
833 jint i = obj->int_field(offset);
834 writer->write_u4((u4)i);
835 break;
836 }
837 case JVM_SIGNATURE_LONG : {
838 jlong l = obj->long_field(offset);
839 writer->write_u8((u8)l);
840 break;
841 }
842 case JVM_SIGNATURE_BOOLEAN : {
843 jboolean b = obj->bool_field(offset);
844 writer->write_u1((u1)b);
845 break;
846 }
847 default : {
848 ShouldNotReachHere();
849 break;
850 }
851 }
852 }
853
854 // returns the size of the instance of the given class
instance_size(Klass * k)855 u4 DumperSupport::instance_size(Klass* k) {
856 HandleMark hm;
857 InstanceKlass* ik = InstanceKlass::cast(k);
858
859 u4 size = 0;
860
861 for (FieldStream fld(ik, false, false); !fld.eos(); fld.next()) {
862 if (!fld.access_flags().is_static()) {
863 size += sig2size(fld.signature());
864 }
865 }
866 return size;
867 }
868
get_static_fields_size(InstanceKlass * ik,u2 & field_count)869 u4 DumperSupport::get_static_fields_size(InstanceKlass* ik, u2& field_count) {
870 HandleMark hm;
871 field_count = 0;
872 u4 size = 0;
873
874 for (FieldStream fldc(ik, true, true); !fldc.eos(); fldc.next()) {
875 if (fldc.access_flags().is_static()) {
876 field_count++;
877 size += sig2size(fldc.signature());
878 }
879 }
880
881 // Add in resolved_references which is referenced by the cpCache
882 // The resolved_references is an array per InstanceKlass holding the
883 // strings and other oops resolved from the constant pool.
884 oop resolved_references = ik->constants()->resolved_references_or_null();
885 if (resolved_references != NULL) {
886 field_count++;
887 size += sizeof(address);
888
889 // Add in the resolved_references of the used previous versions of the class
890 // in the case of RedefineClasses
891 InstanceKlass* prev = ik->previous_versions();
892 while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {
893 field_count++;
894 size += sizeof(address);
895 prev = prev->previous_versions();
896 }
897 }
898
899 // Also provide a pointer to the init_lock if present, so there aren't unreferenced int[0]
900 // arrays.
901 oop init_lock = ik->init_lock();
902 if (init_lock != NULL) {
903 field_count++;
904 size += sizeof(address);
905 }
906
907 // We write the value itself plus a name and a one byte type tag per field.
908 return size + field_count * (sizeof(address) + 1);
909 }
910
911 // dumps static fields of the given class
dump_static_fields(DumpWriter * writer,Klass * k)912 void DumperSupport::dump_static_fields(DumpWriter* writer, Klass* k) {
913 HandleMark hm;
914 InstanceKlass* ik = InstanceKlass::cast(k);
915
916 // dump the field descriptors and raw values
917 for (FieldStream fld(ik, true, true); !fld.eos(); fld.next()) {
918 if (fld.access_flags().is_static()) {
919 Symbol* sig = fld.signature();
920
921 writer->write_symbolID(fld.name()); // name
922 writer->write_u1(sig2tag(sig)); // type
923
924 // value
925 dump_field_value(writer, sig->byte_at(0), ik->java_mirror(), fld.offset());
926 }
927 }
928
929 // Add resolved_references for each class that has them
930 oop resolved_references = ik->constants()->resolved_references_or_null();
931 if (resolved_references != NULL) {
932 writer->write_symbolID(vmSymbols::resolved_references_name()); // name
933 writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
934 writer->write_objectID(resolved_references);
935
936 // Also write any previous versions
937 InstanceKlass* prev = ik->previous_versions();
938 while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {
939 writer->write_symbolID(vmSymbols::resolved_references_name()); // name
940 writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
941 writer->write_objectID(prev->constants()->resolved_references());
942 prev = prev->previous_versions();
943 }
944 }
945
946 // Add init lock to the end if the class is not yet initialized
947 oop init_lock = ik->init_lock();
948 if (init_lock != NULL) {
949 writer->write_symbolID(vmSymbols::init_lock_name()); // name
950 writer->write_u1(sig2tag(vmSymbols::int_array_signature())); // type
951 writer->write_objectID(init_lock);
952 }
953 }
954
955 // dump the raw values of the instance fields of the given object
dump_instance_fields(DumpWriter * writer,oop o)956 void DumperSupport::dump_instance_fields(DumpWriter* writer, oop o) {
957 HandleMark hm;
958 InstanceKlass* ik = InstanceKlass::cast(o->klass());
959
960 for (FieldStream fld(ik, false, false); !fld.eos(); fld.next()) {
961 if (!fld.access_flags().is_static()) {
962 Symbol* sig = fld.signature();
963 dump_field_value(writer, sig->byte_at(0), o, fld.offset());
964 }
965 }
966 }
967
968 // dumps the definition of the instance fields for a given class
get_instance_fields_count(InstanceKlass * ik)969 u2 DumperSupport::get_instance_fields_count(InstanceKlass* ik) {
970 HandleMark hm;
971 u2 field_count = 0;
972
973 for (FieldStream fldc(ik, true, true); !fldc.eos(); fldc.next()) {
974 if (!fldc.access_flags().is_static()) field_count++;
975 }
976
977 return field_count;
978 }
979
980 // dumps the definition of the instance fields for a given class
dump_instance_field_descriptors(DumpWriter * writer,Klass * k)981 void DumperSupport::dump_instance_field_descriptors(DumpWriter* writer, Klass* k) {
982 HandleMark hm;
983 InstanceKlass* ik = InstanceKlass::cast(k);
984
985 // dump the field descriptors
986 for (FieldStream fld(ik, true, true); !fld.eos(); fld.next()) {
987 if (!fld.access_flags().is_static()) {
988 Symbol* sig = fld.signature();
989
990 writer->write_symbolID(fld.name()); // name
991 writer->write_u1(sig2tag(sig)); // type
992 }
993 }
994 }
995
996 // creates HPROF_GC_INSTANCE_DUMP record for the given object
dump_instance(DumpWriter * writer,oop o)997 void DumperSupport::dump_instance(DumpWriter* writer, oop o) {
998 Klass* k = o->klass();
999
1000 InstanceKlass* ik = InstanceKlass::cast(k);
1001 u4 is = instance_size(ik);
1002 u4 size = 1 + sizeof(address) + 4 + sizeof(address) + 4 + is;
1003
1004 writer->start_sub_record(HPROF_GC_INSTANCE_DUMP, size);
1005 writer->write_objectID(o);
1006 writer->write_u4(STACK_TRACE_ID);
1007
1008 // class ID
1009 writer->write_classID(ik);
1010
1011 // number of bytes that follow
1012 writer->write_u4(is);
1013
1014 // field values
1015 dump_instance_fields(writer, o);
1016
1017 writer->end_sub_record();
1018 }
1019
1020 // creates HPROF_GC_CLASS_DUMP record for the given class and each of
1021 // its array classes
dump_class_and_array_classes(DumpWriter * writer,Klass * k)1022 void DumperSupport::dump_class_and_array_classes(DumpWriter* writer, Klass* k) {
1023 InstanceKlass* ik = InstanceKlass::cast(k);
1024
1025 // We can safepoint and do a heap dump at a point where we have a Klass,
1026 // but no java mirror class has been setup for it. So we need to check
1027 // that the class is at least loaded, to avoid crash from a null mirror.
1028 if (!ik->is_loaded()) {
1029 return;
1030 }
1031
1032 u2 static_fields_count = 0;
1033 u4 static_size = get_static_fields_size(ik, static_fields_count);
1034 u2 instance_fields_count = get_instance_fields_count(ik);
1035 u4 instance_fields_size = instance_fields_count * (sizeof(address) + 1);
1036 u4 size = 1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + static_size + 2 + instance_fields_size;
1037
1038 writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);
1039
1040 // class ID
1041 writer->write_classID(ik);
1042 writer->write_u4(STACK_TRACE_ID);
1043
1044 // super class ID
1045 Klass* java_super = ik->java_super();
1046 if (java_super == NULL) {
1047 writer->write_objectID(oop(NULL));
1048 } else {
1049 writer->write_classID(java_super);
1050 }
1051
1052 writer->write_objectID(ik->class_loader());
1053 writer->write_objectID(ik->signers());
1054 writer->write_objectID(ik->protection_domain());
1055
1056 // reserved
1057 writer->write_objectID(oop(NULL));
1058 writer->write_objectID(oop(NULL));
1059
1060 // instance size
1061 writer->write_u4(DumperSupport::instance_size(ik));
1062
1063 // size of constant pool - ignored by HAT 1.1
1064 writer->write_u2(0);
1065
1066 // static fields
1067 writer->write_u2(static_fields_count);
1068 dump_static_fields(writer, ik);
1069
1070 // description of instance fields
1071 writer->write_u2(instance_fields_count);
1072 dump_instance_field_descriptors(writer, ik);
1073
1074 writer->end_sub_record();
1075
1076 // array classes
1077 k = ik->array_klass_or_null();
1078 while (k != NULL) {
1079 assert(k->is_objArray_klass(), "not an ObjArrayKlass");
1080
1081 u4 size = 1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + 2;
1082 writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);
1083 writer->write_classID(k);
1084 writer->write_u4(STACK_TRACE_ID);
1085
1086 // super class of array classes is java.lang.Object
1087 java_super = k->java_super();
1088 assert(java_super != NULL, "checking");
1089 writer->write_classID(java_super);
1090
1091 writer->write_objectID(ik->class_loader());
1092 writer->write_objectID(ik->signers());
1093 writer->write_objectID(ik->protection_domain());
1094
1095 writer->write_objectID(oop(NULL)); // reserved
1096 writer->write_objectID(oop(NULL));
1097 writer->write_u4(0); // instance size
1098 writer->write_u2(0); // constant pool
1099 writer->write_u2(0); // static fields
1100 writer->write_u2(0); // instance fields
1101
1102 writer->end_sub_record();
1103
1104 // get the array class for the next rank
1105 k = k->array_klass_or_null();
1106 }
1107 }
1108
1109 // creates HPROF_GC_CLASS_DUMP record for a given primitive array
1110 // class (and each multi-dimensional array class too)
dump_basic_type_array_class(DumpWriter * writer,Klass * k)1111 void DumperSupport::dump_basic_type_array_class(DumpWriter* writer, Klass* k) {
1112 // array classes
1113 while (k != NULL) {
1114 Klass* klass = k;
1115
1116 u4 size = 1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + 2;
1117 writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);
1118 writer->write_classID(klass);
1119 writer->write_u4(STACK_TRACE_ID);
1120
1121 // super class of array classes is java.lang.Object
1122 Klass* java_super = klass->java_super();
1123 assert(java_super != NULL, "checking");
1124 writer->write_classID(java_super);
1125
1126 writer->write_objectID(oop(NULL)); // loader
1127 writer->write_objectID(oop(NULL)); // signers
1128 writer->write_objectID(oop(NULL)); // protection domain
1129
1130 writer->write_objectID(oop(NULL)); // reserved
1131 writer->write_objectID(oop(NULL));
1132 writer->write_u4(0); // instance size
1133 writer->write_u2(0); // constant pool
1134 writer->write_u2(0); // static fields
1135 writer->write_u2(0); // instance fields
1136
1137 writer->end_sub_record();
1138
1139 // get the array class for the next rank
1140 k = klass->array_klass_or_null();
1141 }
1142 }
1143
1144 // Hprof uses an u4 as record length field,
1145 // which means we need to truncate arrays that are too long.
calculate_array_max_length(DumpWriter * writer,arrayOop array,short header_size)1146 int DumperSupport::calculate_array_max_length(DumpWriter* writer, arrayOop array, short header_size) {
1147 BasicType type = ArrayKlass::cast(array->klass())->element_type();
1148 assert(type >= T_BOOLEAN && type <= T_OBJECT, "invalid array element type");
1149
1150 int length = array->length();
1151
1152 int type_size;
1153 if (type == T_OBJECT) {
1154 type_size = sizeof(address);
1155 } else {
1156 type_size = type2aelembytes(type);
1157 }
1158
1159 size_t length_in_bytes = (size_t)length * type_size;
1160 uint max_bytes = max_juint - header_size;
1161
1162 if (length_in_bytes > max_bytes) {
1163 length = max_bytes / type_size;
1164 length_in_bytes = (size_t)length * type_size;
1165
1166 warning("cannot dump array of type %s[] with length %d; truncating to length %d",
1167 type2name_tab[type], array->length(), length);
1168 }
1169 return length;
1170 }
1171
1172 // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
dump_object_array(DumpWriter * writer,objArrayOop array)1173 void DumperSupport::dump_object_array(DumpWriter* writer, objArrayOop array) {
1174 // sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID) + sizeof(classID)
1175 short header_size = 1 + 2 * 4 + 2 * sizeof(address);
1176 int length = calculate_array_max_length(writer, array, header_size);
1177 u4 size = header_size + length * sizeof(address);
1178
1179 writer->start_sub_record(HPROF_GC_OBJ_ARRAY_DUMP, size);
1180 writer->write_objectID(array);
1181 writer->write_u4(STACK_TRACE_ID);
1182 writer->write_u4(length);
1183
1184 // array class ID
1185 writer->write_classID(array->klass());
1186
1187 // [id]* elements
1188 for (int index = 0; index < length; index++) {
1189 oop o = array->obj_at(index);
1190 if (o != NULL && log_is_enabled(Debug, cds, heap) && mask_dormant_archived_object(o) == NULL) {
1191 ResourceMark rm;
1192 log_debug(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s) referenced by " INTPTR_FORMAT " (%s)",
1193 p2i(o), o->klass()->external_name(),
1194 p2i(array), array->klass()->external_name());
1195 }
1196 o = mask_dormant_archived_object(o);
1197 writer->write_objectID(o);
1198 }
1199
1200 writer->end_sub_record();
1201 }
1202
1203 #define WRITE_ARRAY(Array, Type, Size, Length) \
1204 for (int i = 0; i < Length; i++) { writer->write_##Size((Size)Array->Type##_at(i)); }
1205
1206 // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
dump_prim_array(DumpWriter * writer,typeArrayOop array)1207 void DumperSupport::dump_prim_array(DumpWriter* writer, typeArrayOop array) {
1208 BasicType type = TypeArrayKlass::cast(array->klass())->element_type();
1209
1210 // 2 * sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID)
1211 short header_size = 2 * 1 + 2 * 4 + sizeof(address);
1212
1213 int length = calculate_array_max_length(writer, array, header_size);
1214 int type_size = type2aelembytes(type);
1215 u4 length_in_bytes = (u4)length * type_size;
1216 u4 size = header_size + length_in_bytes;
1217
1218 writer->start_sub_record(HPROF_GC_PRIM_ARRAY_DUMP, size);
1219 writer->write_objectID(array);
1220 writer->write_u4(STACK_TRACE_ID);
1221 writer->write_u4(length);
1222 writer->write_u1(type2tag(type));
1223
1224 // nothing to copy
1225 if (length == 0) {
1226 writer->end_sub_record();
1227 return;
1228 }
1229
1230 // If the byte ordering is big endian then we can copy most types directly
1231
1232 switch (type) {
1233 case T_INT : {
1234 if (Endian::is_Java_byte_ordering_different()) {
1235 WRITE_ARRAY(array, int, u4, length);
1236 } else {
1237 writer->write_raw((void*)(array->int_at_addr(0)), length_in_bytes);
1238 }
1239 break;
1240 }
1241 case T_BYTE : {
1242 writer->write_raw((void*)(array->byte_at_addr(0)), length_in_bytes);
1243 break;
1244 }
1245 case T_CHAR : {
1246 if (Endian::is_Java_byte_ordering_different()) {
1247 WRITE_ARRAY(array, char, u2, length);
1248 } else {
1249 writer->write_raw((void*)(array->char_at_addr(0)), length_in_bytes);
1250 }
1251 break;
1252 }
1253 case T_SHORT : {
1254 if (Endian::is_Java_byte_ordering_different()) {
1255 WRITE_ARRAY(array, short, u2, length);
1256 } else {
1257 writer->write_raw((void*)(array->short_at_addr(0)), length_in_bytes);
1258 }
1259 break;
1260 }
1261 case T_BOOLEAN : {
1262 if (Endian::is_Java_byte_ordering_different()) {
1263 WRITE_ARRAY(array, bool, u1, length);
1264 } else {
1265 writer->write_raw((void*)(array->bool_at_addr(0)), length_in_bytes);
1266 }
1267 break;
1268 }
1269 case T_LONG : {
1270 if (Endian::is_Java_byte_ordering_different()) {
1271 WRITE_ARRAY(array, long, u8, length);
1272 } else {
1273 writer->write_raw((void*)(array->long_at_addr(0)), length_in_bytes);
1274 }
1275 break;
1276 }
1277
1278 // handle float/doubles in a special value to ensure than NaNs are
1279 // written correctly. TO DO: Check if we can avoid this on processors that
1280 // use IEEE 754.
1281
1282 case T_FLOAT : {
1283 for (int i = 0; i < length; i++) {
1284 dump_float(writer, array->float_at(i));
1285 }
1286 break;
1287 }
1288 case T_DOUBLE : {
1289 for (int i = 0; i < length; i++) {
1290 dump_double(writer, array->double_at(i));
1291 }
1292 break;
1293 }
1294 default : ShouldNotReachHere();
1295 }
1296
1297 writer->end_sub_record();
1298 }
1299
1300 // create a HPROF_FRAME record of the given Method* and bci
dump_stack_frame(DumpWriter * writer,int frame_serial_num,int class_serial_num,Method * m,int bci)1301 void DumperSupport::dump_stack_frame(DumpWriter* writer,
1302 int frame_serial_num,
1303 int class_serial_num,
1304 Method* m,
1305 int bci) {
1306 int line_number;
1307 if (m->is_native()) {
1308 line_number = -3; // native frame
1309 } else {
1310 line_number = m->line_number_from_bci(bci);
1311 }
1312
1313 write_header(writer, HPROF_FRAME, 4*oopSize + 2*sizeof(u4));
1314 writer->write_id(frame_serial_num); // frame serial number
1315 writer->write_symbolID(m->name()); // method's name
1316 writer->write_symbolID(m->signature()); // method's signature
1317
1318 assert(m->method_holder()->is_instance_klass(), "not InstanceKlass");
1319 writer->write_symbolID(m->method_holder()->source_file_name()); // source file name
1320 writer->write_u4(class_serial_num); // class serial number
1321 writer->write_u4((u4) line_number); // line number
1322 }
1323
1324
1325 // Support class used to generate HPROF_UTF8 records from the entries in the
1326 // SymbolTable.
1327
1328 class SymbolTableDumper : public SymbolClosure {
1329 private:
1330 DumpWriter* _writer;
writer() const1331 DumpWriter* writer() const { return _writer; }
1332 public:
SymbolTableDumper(DumpWriter * writer)1333 SymbolTableDumper(DumpWriter* writer) { _writer = writer; }
1334 void do_symbol(Symbol** p);
1335 };
1336
do_symbol(Symbol ** p)1337 void SymbolTableDumper::do_symbol(Symbol** p) {
1338 ResourceMark rm;
1339 Symbol* sym = load_symbol(p);
1340 int len = sym->utf8_length();
1341 if (len > 0) {
1342 char* s = sym->as_utf8();
1343 DumperSupport::write_header(writer(), HPROF_UTF8, oopSize + len);
1344 writer()->write_symbolID(sym);
1345 writer()->write_raw(s, len);
1346 }
1347 }
1348
1349 // Support class used to generate HPROF_GC_ROOT_JNI_LOCAL records
1350
1351 class JNILocalsDumper : public OopClosure {
1352 private:
1353 DumpWriter* _writer;
1354 u4 _thread_serial_num;
1355 int _frame_num;
writer() const1356 DumpWriter* writer() const { return _writer; }
1357 public:
JNILocalsDumper(DumpWriter * writer,u4 thread_serial_num)1358 JNILocalsDumper(DumpWriter* writer, u4 thread_serial_num) {
1359 _writer = writer;
1360 _thread_serial_num = thread_serial_num;
1361 _frame_num = -1; // default - empty stack
1362 }
set_frame_number(int n)1363 void set_frame_number(int n) { _frame_num = n; }
1364 void do_oop(oop* obj_p);
do_oop(narrowOop * obj_p)1365 void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1366 };
1367
1368
do_oop(oop * obj_p)1369 void JNILocalsDumper::do_oop(oop* obj_p) {
1370 // ignore null handles
1371 oop o = *obj_p;
1372 if (o != NULL) {
1373 u4 size = 1 + sizeof(address) + 4 + 4;
1374 writer()->start_sub_record(HPROF_GC_ROOT_JNI_LOCAL, size);
1375 writer()->write_objectID(o);
1376 writer()->write_u4(_thread_serial_num);
1377 writer()->write_u4((u4)_frame_num);
1378 writer()->end_sub_record();
1379 }
1380 }
1381
1382
1383 // Support class used to generate HPROF_GC_ROOT_JNI_GLOBAL records
1384
1385 class JNIGlobalsDumper : public OopClosure {
1386 private:
1387 DumpWriter* _writer;
writer() const1388 DumpWriter* writer() const { return _writer; }
1389
1390 public:
JNIGlobalsDumper(DumpWriter * writer)1391 JNIGlobalsDumper(DumpWriter* writer) {
1392 _writer = writer;
1393 }
1394 void do_oop(oop* obj_p);
do_oop(narrowOop * obj_p)1395 void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1396 };
1397
do_oop(oop * obj_p)1398 void JNIGlobalsDumper::do_oop(oop* obj_p) {
1399 oop o = *obj_p;
1400
1401 // ignore these
1402 if (o == NULL) return;
1403
1404 // we ignore global ref to symbols and other internal objects
1405 if (o->is_instance() || o->is_objArray() || o->is_typeArray()) {
1406 u4 size = 1 + 2 * sizeof(address);
1407 writer()->start_sub_record(HPROF_GC_ROOT_JNI_GLOBAL, size);
1408 writer()->write_objectID(o);
1409 writer()->write_objectID((oopDesc*)obj_p); // global ref ID
1410 writer()->end_sub_record();
1411 }
1412 };
1413
1414
1415 // Support class used to generate HPROF_GC_ROOT_MONITOR_USED records
1416
1417 class MonitorUsedDumper : public OopClosure {
1418 private:
1419 DumpWriter* _writer;
writer() const1420 DumpWriter* writer() const { return _writer; }
1421 public:
MonitorUsedDumper(DumpWriter * writer)1422 MonitorUsedDumper(DumpWriter* writer) {
1423 _writer = writer;
1424 }
do_oop(oop * obj_p)1425 void do_oop(oop* obj_p) {
1426 u4 size = 1 + sizeof(address);
1427 writer()->start_sub_record(HPROF_GC_ROOT_MONITOR_USED, size);
1428 writer()->write_objectID(*obj_p);
1429 writer()->end_sub_record();
1430 }
do_oop(narrowOop * obj_p)1431 void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1432 };
1433
1434
1435 // Support class used to generate HPROF_GC_ROOT_STICKY_CLASS records
1436
1437 class StickyClassDumper : public KlassClosure {
1438 private:
1439 DumpWriter* _writer;
writer() const1440 DumpWriter* writer() const { return _writer; }
1441 public:
StickyClassDumper(DumpWriter * writer)1442 StickyClassDumper(DumpWriter* writer) {
1443 _writer = writer;
1444 }
do_klass(Klass * k)1445 void do_klass(Klass* k) {
1446 if (k->is_instance_klass()) {
1447 InstanceKlass* ik = InstanceKlass::cast(k);
1448 u4 size = 1 + sizeof(address);
1449 writer()->start_sub_record(HPROF_GC_ROOT_STICKY_CLASS, size);
1450 writer()->write_classID(ik);
1451 writer()->end_sub_record();
1452 }
1453 }
1454 };
1455
1456
1457 class VM_HeapDumper;
1458
1459 // Support class using when iterating over the heap.
1460
1461 class HeapObjectDumper : public ObjectClosure {
1462 private:
1463 VM_HeapDumper* _dumper;
1464 DumpWriter* _writer;
1465
dumper()1466 VM_HeapDumper* dumper() { return _dumper; }
writer()1467 DumpWriter* writer() { return _writer; }
1468
1469 public:
HeapObjectDumper(VM_HeapDumper * dumper,DumpWriter * writer)1470 HeapObjectDumper(VM_HeapDumper* dumper, DumpWriter* writer) {
1471 _dumper = dumper;
1472 _writer = writer;
1473 }
1474
1475 // called for each object in the heap
1476 void do_object(oop o);
1477 };
1478
do_object(oop o)1479 void HeapObjectDumper::do_object(oop o) {
1480 // skip classes as these emitted as HPROF_GC_CLASS_DUMP records
1481 if (o->klass() == SystemDictionary::Class_klass()) {
1482 if (!java_lang_Class::is_primitive(o)) {
1483 return;
1484 }
1485 }
1486
1487 if (DumperSupport::mask_dormant_archived_object(o) == NULL) {
1488 log_debug(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)", p2i(o), o->klass()->external_name());
1489 return;
1490 }
1491
1492 if (o->is_instance()) {
1493 // create a HPROF_GC_INSTANCE record for each object
1494 DumperSupport::dump_instance(writer(), o);
1495 } else if (o->is_objArray()) {
1496 // create a HPROF_GC_OBJ_ARRAY_DUMP record for each object array
1497 DumperSupport::dump_object_array(writer(), objArrayOop(o));
1498 } else if (o->is_typeArray()) {
1499 // create a HPROF_GC_PRIM_ARRAY_DUMP record for each type array
1500 DumperSupport::dump_prim_array(writer(), typeArrayOop(o));
1501 }
1502 }
1503
1504 // The VM operation that performs the heap dump
1505 class VM_HeapDumper : public VM_GC_Operation {
1506 private:
1507 static VM_HeapDumper* _global_dumper;
1508 static DumpWriter* _global_writer;
1509 DumpWriter* _local_writer;
1510 JavaThread* _oome_thread;
1511 Method* _oome_constructor;
1512 bool _gc_before_heap_dump;
1513 GrowableArray<Klass*>* _klass_map;
1514 ThreadStackTrace** _stack_traces;
1515 int _num_threads;
1516
1517 // accessors and setters
dumper()1518 static VM_HeapDumper* dumper() { assert(_global_dumper != NULL, "Error"); return _global_dumper; }
writer()1519 static DumpWriter* writer() { assert(_global_writer != NULL, "Error"); return _global_writer; }
set_global_dumper()1520 void set_global_dumper() {
1521 assert(_global_dumper == NULL, "Error");
1522 _global_dumper = this;
1523 }
set_global_writer()1524 void set_global_writer() {
1525 assert(_global_writer == NULL, "Error");
1526 _global_writer = _local_writer;
1527 }
clear_global_dumper()1528 void clear_global_dumper() { _global_dumper = NULL; }
clear_global_writer()1529 void clear_global_writer() { _global_writer = NULL; }
1530
1531 bool skip_operation() const;
1532
1533 // writes a HPROF_LOAD_CLASS record
1534 static void do_load_class(Klass* k);
1535
1536 // writes a HPROF_GC_CLASS_DUMP record for the given class
1537 // (and each array class too)
1538 static void do_class_dump(Klass* k);
1539
1540 // writes a HPROF_GC_CLASS_DUMP records for a given basic type
1541 // array (and each multi-dimensional array too)
1542 static void do_basic_type_array_class_dump(Klass* k);
1543
1544 // HPROF_GC_ROOT_THREAD_OBJ records
1545 int do_thread(JavaThread* thread, u4 thread_serial_num);
1546 void do_threads();
1547
add_class_serial_number(Klass * k,int serial_num)1548 void add_class_serial_number(Klass* k, int serial_num) {
1549 _klass_map->at_put_grow(serial_num, k);
1550 }
1551
1552 // HPROF_TRACE and HPROF_FRAME records
1553 void dump_stack_traces();
1554
1555 public:
VM_HeapDumper(DumpWriter * writer,bool gc_before_heap_dump,bool oome)1556 VM_HeapDumper(DumpWriter* writer, bool gc_before_heap_dump, bool oome) :
1557 VM_GC_Operation(0 /* total collections, dummy, ignored */,
1558 GCCause::_heap_dump /* GC Cause */,
1559 0 /* total full collections, dummy, ignored */,
1560 gc_before_heap_dump) {
1561 _local_writer = writer;
1562 _gc_before_heap_dump = gc_before_heap_dump;
1563 _klass_map = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<Klass*>(INITIAL_CLASS_COUNT, true);
1564 _stack_traces = NULL;
1565 _num_threads = 0;
1566 if (oome) {
1567 assert(!Thread::current()->is_VM_thread(), "Dump from OutOfMemoryError cannot be called by the VMThread");
1568 // get OutOfMemoryError zero-parameter constructor
1569 InstanceKlass* oome_ik = SystemDictionary::OutOfMemoryError_klass();
1570 _oome_constructor = oome_ik->find_method(vmSymbols::object_initializer_name(),
1571 vmSymbols::void_method_signature());
1572 // get thread throwing OOME when generating the heap dump at OOME
1573 _oome_thread = JavaThread::current();
1574 } else {
1575 _oome_thread = NULL;
1576 _oome_constructor = NULL;
1577 }
1578 }
~VM_HeapDumper()1579 ~VM_HeapDumper() {
1580 if (_stack_traces != NULL) {
1581 for (int i=0; i < _num_threads; i++) {
1582 delete _stack_traces[i];
1583 }
1584 FREE_C_HEAP_ARRAY(ThreadStackTrace*, _stack_traces);
1585 }
1586 delete _klass_map;
1587 }
1588
type() const1589 VMOp_Type type() const { return VMOp_HeapDumper; }
1590 void doit();
1591 };
1592
1593 VM_HeapDumper* VM_HeapDumper::_global_dumper = NULL;
1594 DumpWriter* VM_HeapDumper::_global_writer = NULL;
1595
skip_operation() const1596 bool VM_HeapDumper::skip_operation() const {
1597 return false;
1598 }
1599
1600 // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record
end_of_dump(DumpWriter * writer)1601 void DumperSupport::end_of_dump(DumpWriter* writer) {
1602 writer->finish_dump_segment();
1603
1604 writer->write_u1(HPROF_HEAP_DUMP_END);
1605 writer->write_u4(0);
1606 writer->write_u4(0);
1607 }
1608
1609 // writes a HPROF_LOAD_CLASS record for the class (and each of its
1610 // array classes)
do_load_class(Klass * k)1611 void VM_HeapDumper::do_load_class(Klass* k) {
1612 static u4 class_serial_num = 0;
1613
1614 // len of HPROF_LOAD_CLASS record
1615 u4 remaining = 2*oopSize + 2*sizeof(u4);
1616
1617 // write a HPROF_LOAD_CLASS for the class and each array class
1618 do {
1619 DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining);
1620
1621 // class serial number is just a number
1622 writer()->write_u4(++class_serial_num);
1623
1624 // class ID
1625 Klass* klass = k;
1626 writer()->write_classID(klass);
1627
1628 // add the Klass* and class serial number pair
1629 dumper()->add_class_serial_number(klass, class_serial_num);
1630
1631 writer()->write_u4(STACK_TRACE_ID);
1632
1633 // class name ID
1634 Symbol* name = klass->name();
1635 writer()->write_symbolID(name);
1636
1637 // write a LOAD_CLASS record for the array type (if it exists)
1638 k = klass->array_klass_or_null();
1639 } while (k != NULL);
1640 }
1641
1642 // writes a HPROF_GC_CLASS_DUMP record for the given class
do_class_dump(Klass * k)1643 void VM_HeapDumper::do_class_dump(Klass* k) {
1644 if (k->is_instance_klass()) {
1645 DumperSupport::dump_class_and_array_classes(writer(), k);
1646 }
1647 }
1648
1649 // writes a HPROF_GC_CLASS_DUMP records for a given basic type
1650 // array (and each multi-dimensional array too)
do_basic_type_array_class_dump(Klass * k)1651 void VM_HeapDumper::do_basic_type_array_class_dump(Klass* k) {
1652 DumperSupport::dump_basic_type_array_class(writer(), k);
1653 }
1654
1655 // Walk the stack of the given thread.
1656 // Dumps a HPROF_GC_ROOT_JAVA_FRAME record for each local
1657 // Dumps a HPROF_GC_ROOT_JNI_LOCAL record for each JNI local
1658 //
1659 // It returns the number of Java frames in this thread stack
do_thread(JavaThread * java_thread,u4 thread_serial_num)1660 int VM_HeapDumper::do_thread(JavaThread* java_thread, u4 thread_serial_num) {
1661 JNILocalsDumper blk(writer(), thread_serial_num);
1662
1663 oop threadObj = java_thread->threadObj();
1664 assert(threadObj != NULL, "sanity check");
1665
1666 int stack_depth = 0;
1667 if (java_thread->has_last_Java_frame()) {
1668
1669 // vframes are resource allocated
1670 Thread* current_thread = Thread::current();
1671 ResourceMark rm(current_thread);
1672 HandleMark hm(current_thread);
1673
1674 RegisterMap reg_map(java_thread);
1675 frame f = java_thread->last_frame();
1676 vframe* vf = vframe::new_vframe(&f, ®_map, java_thread);
1677 frame* last_entry_frame = NULL;
1678 int extra_frames = 0;
1679
1680 if (java_thread == _oome_thread && _oome_constructor != NULL) {
1681 extra_frames++;
1682 }
1683 while (vf != NULL) {
1684 blk.set_frame_number(stack_depth);
1685 if (vf->is_java_frame()) {
1686
1687 // java frame (interpreted, compiled, ...)
1688 javaVFrame *jvf = javaVFrame::cast(vf);
1689 if (!(jvf->method()->is_native())) {
1690 StackValueCollection* locals = jvf->locals();
1691 for (int slot=0; slot<locals->size(); slot++) {
1692 if (locals->at(slot)->type() == T_OBJECT) {
1693 oop o = locals->obj_at(slot)();
1694
1695 if (o != NULL) {
1696 u4 size = 1 + sizeof(address) + 4 + 4;
1697 writer()->start_sub_record(HPROF_GC_ROOT_JAVA_FRAME, size);
1698 writer()->write_objectID(o);
1699 writer()->write_u4(thread_serial_num);
1700 writer()->write_u4((u4) (stack_depth + extra_frames));
1701 writer()->end_sub_record();
1702 }
1703 }
1704 }
1705 StackValueCollection *exprs = jvf->expressions();
1706 for(int index = 0; index < exprs->size(); index++) {
1707 if (exprs->at(index)->type() == T_OBJECT) {
1708 oop o = exprs->obj_at(index)();
1709 if (o != NULL) {
1710 u4 size = 1 + sizeof(address) + 4 + 4;
1711 writer()->start_sub_record(HPROF_GC_ROOT_JAVA_FRAME, size);
1712 writer()->write_objectID(o);
1713 writer()->write_u4(thread_serial_num);
1714 writer()->write_u4((u4) (stack_depth + extra_frames));
1715 writer()->end_sub_record();
1716 }
1717 }
1718 }
1719 } else {
1720 // native frame
1721 if (stack_depth == 0) {
1722 // JNI locals for the top frame.
1723 java_thread->active_handles()->oops_do(&blk);
1724 } else {
1725 if (last_entry_frame != NULL) {
1726 // JNI locals for the entry frame
1727 assert(last_entry_frame->is_entry_frame(), "checking");
1728 last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(&blk);
1729 }
1730 }
1731 }
1732 // increment only for Java frames
1733 stack_depth++;
1734 last_entry_frame = NULL;
1735
1736 } else {
1737 // externalVFrame - if it's an entry frame then report any JNI locals
1738 // as roots when we find the corresponding native javaVFrame
1739 frame* fr = vf->frame_pointer();
1740 assert(fr != NULL, "sanity check");
1741 if (fr->is_entry_frame()) {
1742 last_entry_frame = fr;
1743 }
1744 }
1745 vf = vf->sender();
1746 }
1747 } else {
1748 // no last java frame but there may be JNI locals
1749 java_thread->active_handles()->oops_do(&blk);
1750 }
1751 return stack_depth;
1752 }
1753
1754
1755 // write a HPROF_GC_ROOT_THREAD_OBJ record for each java thread. Then walk
1756 // the stack so that locals and JNI locals are dumped.
do_threads()1757 void VM_HeapDumper::do_threads() {
1758 for (int i=0; i < _num_threads; i++) {
1759 JavaThread* thread = _stack_traces[i]->thread();
1760 oop threadObj = thread->threadObj();
1761 u4 thread_serial_num = i+1;
1762 u4 stack_serial_num = thread_serial_num + STACK_TRACE_ID;
1763 u4 size = 1 + sizeof(address) + 4 + 4;
1764 writer()->start_sub_record(HPROF_GC_ROOT_THREAD_OBJ, size);
1765 writer()->write_objectID(threadObj);
1766 writer()->write_u4(thread_serial_num); // thread number
1767 writer()->write_u4(stack_serial_num); // stack trace serial number
1768 writer()->end_sub_record();
1769 int num_frames = do_thread(thread, thread_serial_num);
1770 assert(num_frames == _stack_traces[i]->get_stack_depth(),
1771 "total number of Java frames not matched");
1772 }
1773 }
1774
1775
1776 // The VM operation that dumps the heap. The dump consists of the following
1777 // records:
1778 //
1779 // HPROF_HEADER
1780 // [HPROF_UTF8]*
1781 // [HPROF_LOAD_CLASS]*
1782 // [[HPROF_FRAME]*|HPROF_TRACE]*
1783 // [HPROF_GC_CLASS_DUMP]*
1784 // [HPROF_HEAP_DUMP_SEGMENT]*
1785 // HPROF_HEAP_DUMP_END
1786 //
1787 // The HPROF_TRACE records represent the stack traces where the heap dump
1788 // is generated and a "dummy trace" record which does not include
1789 // any frames. The dummy trace record is used to be referenced as the
1790 // unknown object alloc site.
1791 //
1792 // Each HPROF_HEAP_DUMP_SEGMENT record has a length followed by sub-records.
1793 // To allow the heap dump be generated in a single pass we remember the position
1794 // of the dump length and fix it up after all sub-records have been written.
1795 // To generate the sub-records we iterate over the heap, writing
1796 // HPROF_GC_INSTANCE_DUMP, HPROF_GC_OBJ_ARRAY_DUMP, and HPROF_GC_PRIM_ARRAY_DUMP
1797 // records as we go. Once that is done we write records for some of the GC
1798 // roots.
1799
doit()1800 void VM_HeapDumper::doit() {
1801
1802 HandleMark hm;
1803 CollectedHeap* ch = Universe::heap();
1804
1805 ch->ensure_parsability(false); // must happen, even if collection does
1806 // not happen (e.g. due to GCLocker)
1807
1808 if (_gc_before_heap_dump) {
1809 if (GCLocker::is_active()) {
1810 warning("GC locker is held; pre-heapdump GC was skipped");
1811 } else {
1812 ch->collect_as_vm_thread(GCCause::_heap_dump);
1813 }
1814 }
1815
1816 // At this point we should be the only dumper active, so
1817 // the following should be safe.
1818 set_global_dumper();
1819 set_global_writer();
1820
1821 // Write the file header - we always use 1.0.2
1822 size_t used = ch->used();
1823 const char* header = "JAVA PROFILE 1.0.2";
1824
1825 // header is few bytes long - no chance to overflow int
1826 writer()->write_raw((void*)header, (int)strlen(header));
1827 writer()->write_u1(0); // terminator
1828 writer()->write_u4(oopSize);
1829 writer()->write_u8(os::javaTimeMillis());
1830
1831 // HPROF_UTF8 records
1832 SymbolTableDumper sym_dumper(writer());
1833 SymbolTable::symbols_do(&sym_dumper);
1834
1835 // write HPROF_LOAD_CLASS records
1836 ClassLoaderDataGraph::classes_do(&do_load_class);
1837 Universe::basic_type_classes_do(&do_load_class);
1838
1839 // write HPROF_FRAME and HPROF_TRACE records
1840 // this must be called after _klass_map is built when iterating the classes above.
1841 dump_stack_traces();
1842
1843 // Writes HPROF_GC_CLASS_DUMP records
1844 ClassLoaderDataGraph::classes_do(&do_class_dump);
1845 Universe::basic_type_classes_do(&do_basic_type_array_class_dump);
1846
1847 // writes HPROF_GC_INSTANCE_DUMP records.
1848 // After each sub-record is written check_segment_length will be invoked
1849 // to check if the current segment exceeds a threshold. If so, a new
1850 // segment is started.
1851 // The HPROF_GC_CLASS_DUMP and HPROF_GC_INSTANCE_DUMP are the vast bulk
1852 // of the heap dump.
1853 HeapObjectDumper obj_dumper(this, writer());
1854 Universe::heap()->safe_object_iterate(&obj_dumper);
1855
1856 // HPROF_GC_ROOT_THREAD_OBJ + frames + jni locals
1857 do_threads();
1858
1859 // HPROF_GC_ROOT_MONITOR_USED
1860 MonitorUsedDumper mon_dumper(writer());
1861 ObjectSynchronizer::oops_do(&mon_dumper);
1862
1863 // HPROF_GC_ROOT_JNI_GLOBAL
1864 JNIGlobalsDumper jni_dumper(writer());
1865 JNIHandles::oops_do(&jni_dumper);
1866 Universe::oops_do(&jni_dumper); // technically not jni roots, but global roots
1867 // for things like preallocated throwable backtraces
1868
1869 // HPROF_GC_ROOT_STICKY_CLASS
1870 // These should be classes in the NULL class loader data, and not all classes
1871 // if !ClassUnloading
1872 StickyClassDumper class_dumper(writer());
1873 ClassLoaderData::the_null_class_loader_data()->classes_do(&class_dumper);
1874
1875 // Writes the HPROF_HEAP_DUMP_END record.
1876 DumperSupport::end_of_dump(writer());
1877
1878 // Now we clear the global variables, so that a future dumper might run.
1879 clear_global_dumper();
1880 clear_global_writer();
1881 }
1882
dump_stack_traces()1883 void VM_HeapDumper::dump_stack_traces() {
1884 // write a HPROF_TRACE record without any frames to be referenced as object alloc sites
1885 DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4));
1886 writer()->write_u4((u4) STACK_TRACE_ID);
1887 writer()->write_u4(0); // thread number
1888 writer()->write_u4(0); // frame count
1889
1890 _stack_traces = NEW_C_HEAP_ARRAY(ThreadStackTrace*, Threads::number_of_threads(), mtInternal);
1891 int frame_serial_num = 0;
1892 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *thread = jtiwh.next(); ) {
1893 oop threadObj = thread->threadObj();
1894 if (threadObj != NULL && !thread->is_exiting() && !thread->is_hidden_from_external_view()) {
1895 // dump thread stack trace
1896 ThreadStackTrace* stack_trace = new ThreadStackTrace(thread, false);
1897 stack_trace->dump_stack_at_safepoint(-1);
1898 _stack_traces[_num_threads++] = stack_trace;
1899
1900 // write HPROF_FRAME records for this thread's stack trace
1901 int depth = stack_trace->get_stack_depth();
1902 int thread_frame_start = frame_serial_num;
1903 int extra_frames = 0;
1904 // write fake frame that makes it look like the thread, which caused OOME,
1905 // is in the OutOfMemoryError zero-parameter constructor
1906 if (thread == _oome_thread && _oome_constructor != NULL) {
1907 int oome_serial_num = _klass_map->find(_oome_constructor->method_holder());
1908 // the class serial number starts from 1
1909 assert(oome_serial_num > 0, "OutOfMemoryError class not found");
1910 DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, oome_serial_num,
1911 _oome_constructor, 0);
1912 extra_frames++;
1913 }
1914 for (int j=0; j < depth; j++) {
1915 StackFrameInfo* frame = stack_trace->stack_frame_at(j);
1916 Method* m = frame->method();
1917 int class_serial_num = _klass_map->find(m->method_holder());
1918 // the class serial number starts from 1
1919 assert(class_serial_num > 0, "class not found");
1920 DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, class_serial_num, m, frame->bci());
1921 }
1922 depth += extra_frames;
1923
1924 // write HPROF_TRACE record for one thread
1925 DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4) + depth*oopSize);
1926 int stack_serial_num = _num_threads + STACK_TRACE_ID;
1927 writer()->write_u4(stack_serial_num); // stack trace serial number
1928 writer()->write_u4((u4) _num_threads); // thread serial number
1929 writer()->write_u4(depth); // frame count
1930 for (int j=1; j <= depth; j++) {
1931 writer()->write_id(thread_frame_start + j);
1932 }
1933 }
1934 }
1935 }
1936
1937 // dump the heap to given path.
dump(const char * path,outputStream * out,bool overwrite)1938 int HeapDumper::dump(const char* path, outputStream* out, bool overwrite) {
1939 assert(path != NULL && strlen(path) > 0, "path missing");
1940
1941 // print message in interactive case
1942 if (out != NULL) {
1943 out->print_cr("Dumping heap to %s ...", path);
1944 timer()->start();
1945 }
1946
1947 // create the dump writer. If the file can be opened then bail
1948 DumpWriter writer(path, overwrite);
1949 if (writer.error() != NULL) {
1950 set_error(writer.error());
1951 if (out != NULL) {
1952 out->print_cr("Unable to create %s: %s", path,
1953 (error() != NULL) ? error() : "reason unknown");
1954 }
1955 return -1;
1956 }
1957
1958 // generate the dump
1959 VM_HeapDumper dumper(&writer, _gc_before_heap_dump, _oome);
1960 if (Thread::current()->is_VM_thread()) {
1961 assert(SafepointSynchronize::is_at_safepoint(), "Expected to be called at a safepoint");
1962 dumper.doit();
1963 } else {
1964 VMThread::execute(&dumper);
1965 }
1966
1967 // close dump file and record any error that the writer may have encountered
1968 writer.close();
1969 set_error(writer.error());
1970
1971 // print message in interactive case
1972 if (out != NULL) {
1973 timer()->stop();
1974 if (error() == NULL) {
1975 out->print_cr("Heap dump file created [" JULONG_FORMAT " bytes in %3.3f secs]",
1976 writer.bytes_written(), timer()->seconds());
1977 } else {
1978 out->print_cr("Dump file is incomplete: %s", writer.error());
1979 }
1980 }
1981
1982 return (writer.error() == NULL) ? 0 : -1;
1983 }
1984
1985 // stop timer (if still active), and free any error string we might be holding
~HeapDumper()1986 HeapDumper::~HeapDumper() {
1987 if (timer()->is_active()) {
1988 timer()->stop();
1989 }
1990 set_error(NULL);
1991 }
1992
1993
1994 // returns the error string (resource allocated), or NULL
error_as_C_string() const1995 char* HeapDumper::error_as_C_string() const {
1996 if (error() != NULL) {
1997 char* str = NEW_RESOURCE_ARRAY(char, strlen(error())+1);
1998 strcpy(str, error());
1999 return str;
2000 } else {
2001 return NULL;
2002 }
2003 }
2004
2005 // set the error string
set_error(char * error)2006 void HeapDumper::set_error(char* error) {
2007 if (_error != NULL) {
2008 os::free(_error);
2009 }
2010 if (error == NULL) {
2011 _error = NULL;
2012 } else {
2013 _error = os::strdup(error);
2014 assert(_error != NULL, "allocation failure");
2015 }
2016 }
2017
2018 // Called by out-of-memory error reporting by a single Java thread
2019 // outside of a JVM safepoint
dump_heap_from_oome()2020 void HeapDumper::dump_heap_from_oome() {
2021 HeapDumper::dump_heap(true);
2022 }
2023
2024 // Called by error reporting by a single Java thread outside of a JVM safepoint,
2025 // or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various
2026 // callers are strictly serialized and guaranteed not to interfere below. For more
2027 // general use, however, this method will need modification to prevent
2028 // inteference when updating the static variables base_path and dump_file_seq below.
dump_heap()2029 void HeapDumper::dump_heap() {
2030 HeapDumper::dump_heap(false);
2031 }
2032
dump_heap(bool oome)2033 void HeapDumper::dump_heap(bool oome) {
2034 static char base_path[JVM_MAXPATHLEN] = {'\0'};
2035 static uint dump_file_seq = 0;
2036 char* my_path;
2037 const int max_digit_chars = 20;
2038
2039 const char* dump_file_name = "java_pid";
2040 const char* dump_file_ext = ".hprof";
2041
2042 // The dump file defaults to java_pid<pid>.hprof in the current working
2043 // directory. HeapDumpPath=<file> can be used to specify an alternative
2044 // dump file name or a directory where dump file is created.
2045 if (dump_file_seq == 0) { // first time in, we initialize base_path
2046 // Calculate potentially longest base path and check if we have enough
2047 // allocated statically.
2048 const size_t total_length =
2049 (HeapDumpPath == NULL ? 0 : strlen(HeapDumpPath)) +
2050 strlen(os::file_separator()) + max_digit_chars +
2051 strlen(dump_file_name) + strlen(dump_file_ext) + 1;
2052 if (total_length > sizeof(base_path)) {
2053 warning("Cannot create heap dump file. HeapDumpPath is too long.");
2054 return;
2055 }
2056
2057 bool use_default_filename = true;
2058 if (HeapDumpPath == NULL || HeapDumpPath[0] == '\0') {
2059 // HeapDumpPath=<file> not specified
2060 } else {
2061 strcpy(base_path, HeapDumpPath);
2062 // check if the path is a directory (must exist)
2063 DIR* dir = os::opendir(base_path);
2064 if (dir == NULL) {
2065 use_default_filename = false;
2066 } else {
2067 // HeapDumpPath specified a directory. We append a file separator
2068 // (if needed).
2069 os::closedir(dir);
2070 size_t fs_len = strlen(os::file_separator());
2071 if (strlen(base_path) >= fs_len) {
2072 char* end = base_path;
2073 end += (strlen(base_path) - fs_len);
2074 if (strcmp(end, os::file_separator()) != 0) {
2075 strcat(base_path, os::file_separator());
2076 }
2077 }
2078 }
2079 }
2080 // If HeapDumpPath wasn't a file name then we append the default name
2081 if (use_default_filename) {
2082 const size_t dlen = strlen(base_path); // if heap dump dir specified
2083 jio_snprintf(&base_path[dlen], sizeof(base_path)-dlen, "%s%d%s",
2084 dump_file_name, os::current_process_id(), dump_file_ext);
2085 }
2086 const size_t len = strlen(base_path) + 1;
2087 my_path = (char*)os::malloc(len, mtInternal);
2088 if (my_path == NULL) {
2089 warning("Cannot create heap dump file. Out of system memory.");
2090 return;
2091 }
2092 strncpy(my_path, base_path, len);
2093 } else {
2094 // Append a sequence number id for dumps following the first
2095 const size_t len = strlen(base_path) + max_digit_chars + 2; // for '.' and \0
2096 my_path = (char*)os::malloc(len, mtInternal);
2097 if (my_path == NULL) {
2098 warning("Cannot create heap dump file. Out of system memory.");
2099 return;
2100 }
2101 jio_snprintf(my_path, len, "%s.%d", base_path, dump_file_seq);
2102 }
2103 dump_file_seq++; // increment seq number for next time we dump
2104
2105 HeapDumper dumper(false /* no GC before heap dump */,
2106 oome /* pass along out-of-memory-error flag */);
2107 dumper.dump(my_path, tty);
2108 os::free(my_path);
2109 }
2110