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