src/share/vm/services/heapDumper.cpp

Fri, 24 Jan 2020 09:41:30 +0800

author
aeriksso
date
Fri, 24 Jan 2020 09:41:30 +0800
changeset 9820
a67e9c6edcdd
parent 9668
acb9351e3a29
child 9852
70aa912cebe5
permissions
-rw-r--r--

8144732: VM_HeapDumper hits assert with bad dump_len
Reviewed-by: dsamersoff

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

mercurial