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 "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
  47 
  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  */
 312 
 313 
 314 // HPROF tags
 315 
 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,
 330 
 331   // 1.0.2 record types
 332   HPROF_HEAP_DUMP_SEGMENT       = 0x1C,
 333   HPROF_HEAP_DUMP_END           = 0x2C,
 334 
 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,
 346 
 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;
 362 
 363 // Default stack trace ID (used for dummy HPROF_TRACE record)
 364 enum {
 365   STACK_TRACE_ID = 1,
 366   INITIAL_CLASS_COUNT = 200
 367 };
 368 
 369 // Supports I/O operations on a dump file
 370 
 371 class DumpWriter : public StackObj {
 372  private:
 373   enum {
 374     io_buffer_size  = 8*M
 375   };
 376 
 377   int _fd;              // file descriptor (-1 if dump file not open)
 378   julong _bytes_written; // number of byte written to dump file
 379 
 380   char* _buffer;    // internal buffer
 381   size_t _size;
 382   size_t _pos;
 383 
 384   jlong _dump_start;
 385 
 386   char* _error;   // error message when I/O fails
 387 
 388   void set_file_descriptor(int fd)              { _fd = fd; }
 389   int file_descriptor() const                   { return _fd; }
 390 
 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; }
 395 
 396   void set_error(const char* error)             { _error = (char*)os::strdup(error); }
 397 
 398   // all I/O go through this function
 399   void write_internal(void* s, size_t len);
 400 
 401  public:
 402   DumpWriter(const char* path);
 403   ~DumpWriter();
 404 
 405   void close();
 406   bool is_open() const                  { return file_descriptor() >= 0; }
 407   void flush();
 408 
 409   jlong dump_start() const                      { return _dump_start; }
 410   void set_dump_start(jlong pos);
 411   julong current_record_length();
 412 
 413   // total number of bytes written to the disk
 414   julong bytes_written() const          { return _bytes_written; }
 415 
 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; }
 419 
 420   // number of (buffered) bytes as yet unwritten to the dump file
 421   size_t bytes_unwritten() const        { return position(); }
 422 
 423   char* error() const                   { return _error; }
 424 
 425   jlong current_offset();
 426   void seek_to_offset(jlong pos);
 427 
 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 };
 439 
 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
 456 
 457   // if the open failed we record the error
 458   if (_fd < 0) {
 459     _error = (char*)os::strdup(strerror(errno));
 460   }
 461 }
 462 
 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 }
 471 
 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 }
 481 
 482 // sets the dump starting position
 483 void DumpWriter::set_dump_start(jlong pos) {
 484   _dump_start = pos;
 485 }
 486 
 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 }
 497 
 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);
 506 
 507       if (n < 0) {
 508         set_error(strerror(errno));
 509         ::close(file_descriptor());
 510         set_file_descriptor(-1);
 511         return;
 512       }
 513 
 514       _bytes_written += n;
 515       pos += n;
 516       len -= n;
 517     }
 518   }
 519 }
 520 
 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     }
 528 
 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 }
 539 
 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 }
 547 
 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 }
 558 
 559 void DumpWriter::seek_to_offset(jlong off) {
 560   assert(off >= 0, "bad offset");
 561 
 562   // need to flush before seeking
 563   flush();
 564 
 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 }
 571 
 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 }
 577 
 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 }
 583 
 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 }
 589 
 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 }
 598 
 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 }
 607 
 608 void DumpWriter::write_id(u4 x) {
 609 #ifdef _LP64
 610   write_u8((u8) x);
 611 #else
 612   write_u4(x);
 613 #endif
 614 }
 615 
 616 // We use java mirror as the class ID
 617 void DumpWriter::write_classID(Klass* k) {
 618   write_objectID(k->java_mirror());
 619 }
 620 
 621 
 622 
 623 // Support class with a collection of functions used when dumping the heap
 624 
 625 class DumperSupport : AllStatic {
 626  public:
 627 
 628   // write a header of the given type
 629   static void write_header(DumpWriter* writer, hprofTag tag, u4 len);
 630 
 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);
 635 
 636   // returns the size of the instance of the given class
 637   static u4 instance_size(Klass* k);
 638 
 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);
 659 
 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);
 666 
 667   // check if we need to truncate an array
 668   static int calculate_array_max_length(DumpWriter* writer, arrayOop array, short header_size);
 669 
 670   // writes a HPROF_HEAP_DUMP_SEGMENT record
 671   static void write_dump_header(DumpWriter* writer);
 672 
 673   // fixes up the length of the current dump record
 674   static void write_current_dump_record_length(DumpWriter* writer);
 675 
 676   // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record
 677   static void end_of_dump(DumpWriter* writer);
 678 };
 679 
 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 }
 686 
 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 }
 703 
 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 }
 717 
 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 }
 731 
 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 }
 746 
 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       }
 758 
 759 #if INCLUDE_ALL_GCS
 760       if (UseShenandoahGC) {
 761         o = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(o);
 762       }
 763 #endif
 764 
 765       // reflection and sun.misc.Unsafe classes may have a reference to a
 766       // Klass* so filter it out.
 767       assert(o->is_oop_or_null(), "should always be an oop");
 768       writer->write_objectID(o);
 769       break;
 770     }
 771     case JVM_SIGNATURE_BYTE     : {
 772       jbyte* b = (jbyte*)addr;
 773       writer->write_u1((u1)*b);
 774       break;
 775     }
 776     case JVM_SIGNATURE_CHAR     : {
 777       jchar* c = (jchar*)addr;
 778       writer->write_u2((u2)*c);
 779       break;
 780     }
 781     case JVM_SIGNATURE_SHORT : {
 782       jshort* s = (jshort*)addr;
 783       writer->write_u2((u2)*s);
 784       break;
 785     }
 786     case JVM_SIGNATURE_FLOAT : {
 787       jfloat* f = (jfloat*)addr;
 788       dump_float(writer, *f);
 789       break;
 790     }
 791     case JVM_SIGNATURE_DOUBLE : {
 792       jdouble* f = (jdouble*)addr;
 793       dump_double(writer, *f);
 794       break;
 795     }
 796     case JVM_SIGNATURE_INT : {
 797       jint* i = (jint*)addr;
 798       writer->write_u4((u4)*i);
 799       break;
 800     }
 801     case JVM_SIGNATURE_LONG     : {
 802       jlong* l = (jlong*)addr;
 803       writer->write_u8((u8)*l);
 804       break;
 805     }
 806     case JVM_SIGNATURE_BOOLEAN : {
 807       jboolean* b = (jboolean*)addr;
 808       writer->write_u1((u1)*b);
 809       break;
 810     }
 811     default : ShouldNotReachHere();
 812   }
 813 }
 814 
 815 // returns the size of the instance of the given class
 816 u4 DumperSupport::instance_size(Klass* k) {
 817   HandleMark hm;
 818   instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), k);
 819 
 820   u4 size = 0;
 821 
 822   for (FieldStream fld(ikh, false, false); !fld.eos(); fld.next()) {
 823     if (!fld.access_flags().is_static()) {
 824       Symbol* sig = fld.signature();
 825       switch (sig->byte_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
 849 void DumperSupport::dump_static_fields(DumpWriter* writer, Klass* k) {
 850   HandleMark hm;
 851   instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), k);
 852 
 853   // pass 1 - count the static fields
 854   u2 field_count = 0;
 855   for (FieldStream fldc(ikh, true, true); !fldc.eos(); fldc.next()) {
 856     if (fldc.access_flags().is_static()) field_count++;
 857   }
 858   // Add in resolved_references which is referenced by the cpCache
 859   // The resolved_references is an array per InstanceKlass holding the
 860   // strings and other oops resolved from the constant pool.
 861   oop resolved_references = ikh->constants()->resolved_references_or_null();
 862   if (resolved_references != NULL) {
 863     field_count++;
 864 
 865     // Add in the resolved_references of the used previous versions of the class
 866     // in the case of RedefineClasses
 867     InstanceKlass* prev = ikh->previous_versions();
 868     while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {
 869       field_count++;
 870       prev = prev->previous_versions();
 871     }
 872   }
 873 
 874   // Also provide a pointer to the init_lock if present, so there aren't unreferenced int[0]
 875   // arrays.
 876   oop init_lock = ikh->init_lock();
 877   if (init_lock != NULL) {
 878     field_count++;
 879   }
 880 
 881   writer->write_u2(field_count);
 882 
 883   // pass 2 - dump the field descriptors and raw values
 884   for (FieldStream fld(ikh, true, true); !fld.eos(); fld.next()) {
 885     if (fld.access_flags().is_static()) {
 886       Symbol* sig = fld.signature();
 887 
 888       writer->write_symbolID(fld.name());   // name
 889       writer->write_u1(sig2tag(sig));       // type
 890 
 891       // value
 892       int offset = fld.offset();
 893       address addr = (address)ikh->java_mirror() + offset;
 894 
 895       dump_field_value(writer, sig->byte_at(0), addr);
 896     }
 897   }
 898 
 899   // Add resolved_references for each class that has them
 900   if (resolved_references != NULL) {
 901     writer->write_symbolID(vmSymbols::resolved_references_name());  // name
 902     writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
 903     writer->write_objectID(resolved_references);
 904 
 905     // Also write any previous versions
 906     InstanceKlass* prev = ikh->previous_versions();
 907     while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {
 908       writer->write_symbolID(vmSymbols::resolved_references_name());  // name
 909       writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
 910       writer->write_objectID(prev->constants()->resolved_references());
 911       prev = prev->previous_versions();
 912     }
 913   }
 914 
 915   // Add init lock to the end if the class is not yet initialized
 916   if (init_lock != NULL) {
 917     writer->write_symbolID(vmSymbols::init_lock_name());         // name
 918     writer->write_u1(sig2tag(vmSymbols::int_array_signature())); // type
 919     writer->write_objectID(init_lock);
 920   }
 921 }
 922 
 923 // dump the raw values of the instance fields of the given object
 924 void DumperSupport::dump_instance_fields(DumpWriter* writer, oop o) {
 925   HandleMark hm;
 926   instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), o->klass());
 927 
 928   for (FieldStream fld(ikh, false, false); !fld.eos(); fld.next()) {
 929     if (!fld.access_flags().is_static()) {
 930       Symbol* sig = fld.signature();
 931       address addr = (address)o + fld.offset();
 932 
 933       dump_field_value(writer, sig->byte_at(0), addr);
 934     }
 935   }
 936 }
 937 
 938 // dumps the definition of the instance fields for a given class
 939 void DumperSupport::dump_instance_field_descriptors(DumpWriter* writer, Klass* k) {
 940   HandleMark hm;
 941   instanceKlassHandle ikh = instanceKlassHandle(Thread::current(), k);
 942 
 943   // pass 1 - count the instance fields
 944   u2 field_count = 0;
 945   for (FieldStream fldc(ikh, true, true); !fldc.eos(); fldc.next()) {
 946     if (!fldc.access_flags().is_static()) field_count++;
 947   }
 948 
 949   writer->write_u2(field_count);
 950 
 951   // pass 2 - dump the field descriptors
 952   for (FieldStream fld(ikh, true, true); !fld.eos(); fld.next()) {
 953     if (!fld.access_flags().is_static()) {
 954       Symbol* sig = fld.signature();
 955 
 956       writer->write_symbolID(fld.name());   // name
 957       writer->write_u1(sig2tag(sig));       // type
 958     }
 959   }
 960 }
 961 
 962 // creates HPROF_GC_INSTANCE_DUMP record for the given object
 963 void DumperSupport::dump_instance(DumpWriter* writer, oop o) {
 964   Klass* k = o->klass();
 965 
 966   writer->write_u1(HPROF_GC_INSTANCE_DUMP);
 967   writer->write_objectID(o);
 968   writer->write_u4(STACK_TRACE_ID);
 969 
 970   // class ID
 971   writer->write_classID(k);
 972 
 973   // number of bytes that follow
 974   writer->write_u4(instance_size(k) );
 975 
 976   // field values
 977   dump_instance_fields(writer, o);
 978 }
 979 
 980 // creates HPROF_GC_CLASS_DUMP record for the given class and each of
 981 // its array classes
 982 void DumperSupport::dump_class_and_array_classes(DumpWriter* writer, Klass* k) {
 983   Klass* 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   Klass* 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 = klass->array_klass_or_null();
1029   while (k != NULL) {
1030     Klass* klass = k;
1031     assert(klass->oop_is_objArray(), "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)
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     Klass* 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.
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
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 
1146   // array class ID
1147   writer->write_classID(array->klass());
1148 
1149   // [id]* elements
1150   for (int index = 0; index < length; index++) {
1151     oop o = array->obj_at(index);
1152     writer->write_objectID(o);
1153   }
1154 }
1155 
1156 #define WRITE_ARRAY(Array, Type, Size, Length) \
1157   for (int i = 0; i < Length; i++) { writer->write_##Size((Size)array->Type##_at(i)); }
1158 
1159 // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
1160 void DumperSupport::dump_prim_array(DumpWriter* writer, typeArrayOop array) {
1161   BasicType type = TypeArrayKlass::cast(array->klass())->element_type();
1162 
1163   // 2 * sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID)
1164   short header_size = 2 * 1 + 2 * 4 + sizeof(address);
1165 
1166   int length = calculate_array_max_length(writer, array, header_size);
1167   int type_size = type2aelembytes(type);
1168   u4 length_in_bytes = (u4)length * type_size;
1169 
1170   writer->write_u1(HPROF_GC_PRIM_ARRAY_DUMP);
1171   writer->write_objectID(array);
1172   writer->write_u4(STACK_TRACE_ID);
1173   writer->write_u4(length);
1174   writer->write_u1(type2tag(type));
1175 
1176   // nothing to copy
1177   if (length == 0) {
1178     return;
1179   }
1180 
1181   // If the byte ordering is big endian then we can copy most types directly
1182 
1183   switch (type) {
1184     case T_INT : {
1185       if (Bytes::is_Java_byte_ordering_different()) {
1186         WRITE_ARRAY(array, int, u4, length);
1187       } else {
1188         writer->write_raw((void*)(array->int_at_addr(0)), length_in_bytes);
1189       }
1190       break;
1191     }
1192     case T_BYTE : {
1193       writer->write_raw((void*)(array->byte_at_addr(0)), length_in_bytes);
1194       break;
1195     }
1196     case T_CHAR : {
1197       if (Bytes::is_Java_byte_ordering_different()) {
1198         WRITE_ARRAY(array, char, u2, length);
1199       } else {
1200         writer->write_raw((void*)(array->char_at_addr(0)), length_in_bytes);
1201       }
1202       break;
1203     }
1204     case T_SHORT : {
1205       if (Bytes::is_Java_byte_ordering_different()) {
1206         WRITE_ARRAY(array, short, u2, length);
1207       } else {
1208         writer->write_raw((void*)(array->short_at_addr(0)), length_in_bytes);
1209       }
1210       break;
1211     }
1212     case T_BOOLEAN : {
1213       if (Bytes::is_Java_byte_ordering_different()) {
1214         WRITE_ARRAY(array, bool, u1, length);
1215       } else {
1216         writer->write_raw((void*)(array->bool_at_addr(0)), length_in_bytes);
1217       }
1218       break;
1219     }
1220     case T_LONG : {
1221       if (Bytes::is_Java_byte_ordering_different()) {
1222         WRITE_ARRAY(array, long, u8, length);
1223       } else {
1224         writer->write_raw((void*)(array->long_at_addr(0)), length_in_bytes);
1225       }
1226       break;
1227     }
1228 
1229     // handle float/doubles in a special value to ensure than NaNs are
1230     // written correctly. TO DO: Check if we can avoid this on processors that
1231     // use IEEE 754.
1232 
1233     case T_FLOAT : {
1234       for (int i = 0; i < length; i++) {
1235         dump_float(writer, array->float_at(i));
1236       }
1237       break;
1238     }
1239     case T_DOUBLE : {
1240       for (int i = 0; i < length; i++) {
1241         dump_double(writer, array->double_at(i));
1242       }
1243       break;
1244     }
1245     default : ShouldNotReachHere();
1246   }
1247 }
1248 
1249 // create a HPROF_FRAME record of the given Method* and bci
1250 void DumperSupport::dump_stack_frame(DumpWriter* writer,
1251                                      int frame_serial_num,
1252                                      int class_serial_num,
1253                                      Method* m,
1254                                      int bci) {
1255   int line_number;
1256   if (m->is_native()) {
1257     line_number = -3;  // native frame
1258   } else {
1259     line_number = m->line_number_from_bci(bci);
1260   }
1261 
1262   write_header(writer, HPROF_FRAME, 4*oopSize + 2*sizeof(u4));
1263   writer->write_id(frame_serial_num);               // frame serial number
1264   writer->write_symbolID(m->name());                // method's name
1265   writer->write_symbolID(m->signature());           // method's signature
1266 
1267   assert(m->method_holder()->oop_is_instance(), "not InstanceKlass");
1268   writer->write_symbolID(m->method_holder()->source_file_name());  // source file name
1269   writer->write_u4(class_serial_num);               // class serial number
1270   writer->write_u4((u4) line_number);               // line number
1271 }
1272 
1273 
1274 // Support class used to generate HPROF_UTF8 records from the entries in the
1275 // SymbolTable.
1276 
1277 class SymbolTableDumper : public SymbolClosure {
1278  private:
1279   DumpWriter* _writer;
1280   DumpWriter* writer() const                { return _writer; }
1281  public:
1282   SymbolTableDumper(DumpWriter* writer)     { _writer = writer; }
1283   void do_symbol(Symbol** p);
1284 };
1285 
1286 void SymbolTableDumper::do_symbol(Symbol** p) {
1287   ResourceMark rm;
1288   Symbol* sym = load_symbol(p);
1289   int len = sym->utf8_length();
1290   if (len > 0) {
1291     char* s = sym->as_utf8();
1292     DumperSupport::write_header(writer(), HPROF_UTF8, oopSize + len);
1293     writer()->write_symbolID(sym);
1294     writer()->write_raw(s, len);
1295   }
1296 }
1297 
1298 // Support class used to generate HPROF_GC_ROOT_JNI_LOCAL records
1299 
1300 class JNILocalsDumper : public OopClosure {
1301  private:
1302   DumpWriter* _writer;
1303   u4 _thread_serial_num;
1304   int _frame_num;
1305   DumpWriter* writer() const                { return _writer; }
1306  public:
1307   JNILocalsDumper(DumpWriter* writer, u4 thread_serial_num) {
1308     _writer = writer;
1309     _thread_serial_num = thread_serial_num;
1310     _frame_num = -1;  // default - empty stack
1311   }
1312   void set_frame_number(int n) { _frame_num = n; }
1313   void do_oop(oop* obj_p);
1314   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1315 };
1316 
1317 
1318 void JNILocalsDumper::do_oop(oop* obj_p) {
1319   // ignore null or deleted handles
1320   oop o = *obj_p;
1321   if (o != NULL && o != JNIHandles::deleted_handle()) {
1322     writer()->write_u1(HPROF_GC_ROOT_JNI_LOCAL);
1323     writer()->write_objectID(o);
1324     writer()->write_u4(_thread_serial_num);
1325     writer()->write_u4((u4)_frame_num);
1326   }
1327 }
1328 
1329 
1330 // Support class used to generate HPROF_GC_ROOT_JNI_GLOBAL records
1331 
1332 class JNIGlobalsDumper : public OopClosure {
1333  private:
1334   DumpWriter* _writer;
1335   DumpWriter* writer() const                { return _writer; }
1336 
1337  public:
1338   JNIGlobalsDumper(DumpWriter* writer) {
1339     _writer = writer;
1340   }
1341   void do_oop(oop* obj_p);
1342   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1343 };
1344 
1345 void JNIGlobalsDumper::do_oop(oop* obj_p) {
1346   oop o = *obj_p;
1347 
1348   // ignore these
1349   if (o == NULL || o == JNIHandles::deleted_handle()) return;
1350 
1351   // we ignore global ref to symbols and other internal objects
1352   if (o->is_instance() || o->is_objArray() || o->is_typeArray()) {
1353     writer()->write_u1(HPROF_GC_ROOT_JNI_GLOBAL);
1354     writer()->write_objectID(o);
1355     writer()->write_objectID((oopDesc*)obj_p);      // global ref ID
1356   }
1357 };
1358 
1359 
1360 // Support class used to generate HPROF_GC_ROOT_MONITOR_USED records
1361 
1362 class MonitorUsedDumper : public OopClosure {
1363  private:
1364   DumpWriter* _writer;
1365   DumpWriter* writer() const                { return _writer; }
1366  public:
1367   MonitorUsedDumper(DumpWriter* writer) {
1368     _writer = writer;
1369   }
1370   void do_oop(oop* obj_p) {
1371     writer()->write_u1(HPROF_GC_ROOT_MONITOR_USED);
1372     writer()->write_objectID(*obj_p);
1373   }
1374   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1375 };
1376 
1377 
1378 // Support class used to generate HPROF_GC_ROOT_STICKY_CLASS records
1379 
1380 class StickyClassDumper : public KlassClosure {
1381  private:
1382   DumpWriter* _writer;
1383   DumpWriter* writer() const                { return _writer; }
1384  public:
1385   StickyClassDumper(DumpWriter* writer) {
1386     _writer = writer;
1387   }
1388   void do_klass(Klass* k) {
1389     if (k->oop_is_instance()) {
1390       InstanceKlass* ik = InstanceKlass::cast(k);
1391         writer()->write_u1(HPROF_GC_ROOT_STICKY_CLASS);
1392         writer()->write_classID(ik);
1393       }
1394     }
1395 };
1396 
1397 
1398 class VM_HeapDumper;
1399 
1400 // Support class using when iterating over the heap.
1401 
1402 class HeapObjectDumper : public ObjectClosure {
1403  private:
1404   VM_HeapDumper* _dumper;
1405   DumpWriter* _writer;
1406 
1407   VM_HeapDumper* dumper()               { return _dumper; }
1408   DumpWriter* writer()                  { return _writer; }
1409 
1410   // used to indicate that a record has been writen
1411   void mark_end_of_record();
1412 
1413  public:
1414   HeapObjectDumper(VM_HeapDumper* dumper, DumpWriter* writer) {
1415     _dumper = dumper;
1416     _writer = writer;
1417   }
1418 
1419   // called for each object in the heap
1420   void do_object(oop o);
1421 };
1422 
1423 void HeapObjectDumper::do_object(oop o) {
1424   // hide the sentinel for deleted handles
1425   if (o == JNIHandles::deleted_handle()) return;
1426 
1427   // skip classes as these emitted as HPROF_GC_CLASS_DUMP records
1428   if (o->klass() == SystemDictionary::Class_klass()) {
1429     if (!java_lang_Class::is_primitive(o)) {
1430       return;
1431     }
1432   }
1433 
1434   if (o->is_instance()) {
1435     // create a HPROF_GC_INSTANCE record for each object
1436     DumperSupport::dump_instance(writer(), o);
1437     mark_end_of_record();
1438   } else if (o->is_objArray()) {
1439     // create a HPROF_GC_OBJ_ARRAY_DUMP record for each object array
1440     DumperSupport::dump_object_array(writer(), objArrayOop(o));
1441     mark_end_of_record();
1442   } else if (o->is_typeArray()) {
1443     // create a HPROF_GC_PRIM_ARRAY_DUMP record for each type array
1444     DumperSupport::dump_prim_array(writer(), typeArrayOop(o));
1445     mark_end_of_record();
1446   }
1447 }
1448 
1449 // The VM operation that performs the heap dump
1450 class VM_HeapDumper : public VM_GC_Operation {
1451  private:
1452   static VM_HeapDumper* _global_dumper;
1453   static DumpWriter*    _global_writer;
1454   DumpWriter*           _local_writer;
1455   JavaThread*           _oome_thread;
1456   Method*               _oome_constructor;
1457   bool _gc_before_heap_dump;
1458   GrowableArray<Klass*>* _klass_map;
1459   ThreadStackTrace** _stack_traces;
1460   int _num_threads;
1461 
1462   // accessors and setters
1463   static VM_HeapDumper* dumper()         {  assert(_global_dumper != NULL, "Error"); return _global_dumper; }
1464   static DumpWriter* writer()            {  assert(_global_writer != NULL, "Error"); return _global_writer; }
1465   void set_global_dumper() {
1466     assert(_global_dumper == NULL, "Error");
1467     _global_dumper = this;
1468   }
1469   void set_global_writer() {
1470     assert(_global_writer == NULL, "Error");
1471     _global_writer = _local_writer;
1472   }
1473   void clear_global_dumper() { _global_dumper = NULL; }
1474   void clear_global_writer() { _global_writer = NULL; }
1475 
1476   bool skip_operation() const;
1477 
1478   // writes a HPROF_LOAD_CLASS record
1479   static void do_load_class(Klass* k);
1480 
1481   // writes a HPROF_GC_CLASS_DUMP record for the given class
1482   // (and each array class too)
1483   static void do_class_dump(Klass* k);
1484 
1485   // writes a HPROF_GC_CLASS_DUMP records for a given basic type
1486   // array (and each multi-dimensional array too)
1487   static void do_basic_type_array_class_dump(Klass* k);
1488 
1489   // HPROF_GC_ROOT_THREAD_OBJ records
1490   int do_thread(JavaThread* thread, u4 thread_serial_num);
1491   void do_threads();
1492 
1493   void add_class_serial_number(Klass* k, int serial_num) {
1494     _klass_map->at_put_grow(serial_num, k);
1495   }
1496 
1497   // HPROF_TRACE and HPROF_FRAME records
1498   void dump_stack_traces();
1499 
1500  public:
1501   VM_HeapDumper(DumpWriter* writer, bool gc_before_heap_dump, bool oome) :
1502     VM_GC_Operation(0 /* total collections,      dummy, ignored */,
1503                     GCCause::_heap_dump /* GC Cause */,
1504                     0 /* total full collections, dummy, ignored */,
1505                     gc_before_heap_dump) {
1506     _local_writer = writer;
1507     _gc_before_heap_dump = gc_before_heap_dump;
1508     _klass_map = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<Klass*>(INITIAL_CLASS_COUNT, true);
1509     _stack_traces = NULL;
1510     _num_threads = 0;
1511     if (oome) {
1512       assert(!Thread::current()->is_VM_thread(), "Dump from OutOfMemoryError cannot be called by the VMThread");
1513       // get OutOfMemoryError zero-parameter constructor
1514       InstanceKlass* oome_ik = InstanceKlass::cast(SystemDictionary::OutOfMemoryError_klass());
1515       _oome_constructor = oome_ik->find_method(vmSymbols::object_initializer_name(),
1516                                                           vmSymbols::void_method_signature());
1517       // get thread throwing OOME when generating the heap dump at OOME
1518       _oome_thread = JavaThread::current();
1519     } else {
1520       _oome_thread = NULL;
1521       _oome_constructor = NULL;
1522     }
1523   }
1524   ~VM_HeapDumper() {
1525     if (_stack_traces != NULL) {
1526       for (int i=0; i < _num_threads; i++) {
1527         delete _stack_traces[i];
1528       }
1529       FREE_C_HEAP_ARRAY(ThreadStackTrace*, _stack_traces, mtInternal);
1530     }
1531     delete _klass_map;
1532   }
1533 
1534   VMOp_Type type() const { return VMOp_HeapDumper; }
1535   // used to mark sub-record boundary
1536   void check_segment_length();
1537   void doit();
1538 };
1539 
1540 VM_HeapDumper* VM_HeapDumper::_global_dumper = NULL;
1541 DumpWriter*    VM_HeapDumper::_global_writer = NULL;
1542 
1543 bool VM_HeapDumper::skip_operation() const {
1544   return false;
1545 }
1546 
1547  // writes a HPROF_HEAP_DUMP_SEGMENT record
1548 void DumperSupport::write_dump_header(DumpWriter* writer) {
1549   if (writer->is_open()) {
1550     writer->write_u1(HPROF_HEAP_DUMP_SEGMENT);
1551     writer->write_u4(0); // current ticks
1552 
1553     // record the starting position for the dump (its length will be fixed up later)
1554     writer->set_dump_start(writer->current_offset());
1555     writer->write_u4(0);
1556   }
1557 }
1558 
1559 // fixes up the length of the current dump record
1560 void DumperSupport::write_current_dump_record_length(DumpWriter* writer) {
1561   if (writer->is_open()) {
1562     julong dump_end = writer->bytes_written() + writer->bytes_unwritten();
1563     julong dump_len = writer->current_record_length();
1564 
1565     // record length must fit in a u4
1566     if (dump_len > max_juint) {
1567       warning("record is too large");
1568     }
1569 
1570     // seek to the dump start and fix-up the length
1571     assert(writer->dump_start() >= 0, "no dump start recorded");
1572     writer->seek_to_offset(writer->dump_start());
1573     writer->write_u4((u4)dump_len);
1574 
1575     // adjust the total size written to keep the bytes written correct.
1576     writer->adjust_bytes_written(-((jlong) sizeof(u4)));
1577 
1578     // seek to dump end so we can continue
1579     writer->seek_to_offset(dump_end);
1580 
1581     // no current dump record
1582     writer->set_dump_start((jlong)-1);
1583   }
1584 }
1585 
1586 // used on a sub-record boundary to check if we need to start a
1587 // new segment.
1588 void VM_HeapDumper::check_segment_length() {
1589   if (writer()->is_open()) {
1590     julong dump_len = writer()->current_record_length();
1591 
1592     if (dump_len > 2UL*G) {
1593       DumperSupport::write_current_dump_record_length(writer());
1594       DumperSupport::write_dump_header(writer());
1595     }
1596   }
1597 }
1598 
1599 // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record
1600 void DumperSupport::end_of_dump(DumpWriter* writer) {
1601   if (writer->is_open()) {
1602     write_current_dump_record_length(writer);
1603 
1604     writer->write_u1(HPROF_HEAP_DUMP_END);
1605     writer->write_u4(0);
1606     writer->write_u4(0);
1607   }
1608 }
1609 
1610 // marks sub-record boundary
1611 void HeapObjectDumper::mark_end_of_record() {
1612   dumper()->check_segment_length();
1613 }
1614 
1615 // writes a HPROF_LOAD_CLASS record for the class (and each of its
1616 // array classes)
1617 void VM_HeapDumper::do_load_class(Klass* k) {
1618   static u4 class_serial_num = 0;
1619 
1620   // len of HPROF_LOAD_CLASS record
1621   u4 remaining = 2*oopSize + 2*sizeof(u4);
1622 
1623   // write a HPROF_LOAD_CLASS for the class and each array class
1624   do {
1625     DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining);
1626 
1627     // class serial number is just a number
1628     writer()->write_u4(++class_serial_num);
1629 
1630     // class ID
1631     Klass* klass = k;
1632     writer()->write_classID(klass);
1633 
1634     // add the Klass* and class serial number pair
1635     dumper()->add_class_serial_number(klass, class_serial_num);
1636 
1637     writer()->write_u4(STACK_TRACE_ID);
1638 
1639     // class name ID
1640     Symbol* name = klass->name();
1641     writer()->write_symbolID(name);
1642 
1643     // write a LOAD_CLASS record for the array type (if it exists)
1644     k = klass->array_klass_or_null();
1645   } while (k != NULL);
1646 }
1647 
1648 // writes a HPROF_GC_CLASS_DUMP record for the given class
1649 void VM_HeapDumper::do_class_dump(Klass* k) {
1650   if (k->oop_is_instance()) {
1651     DumperSupport::dump_class_and_array_classes(writer(), k);
1652   }
1653 }
1654 
1655 // writes a HPROF_GC_CLASS_DUMP records for a given basic type
1656 // array (and each multi-dimensional array too)
1657 void VM_HeapDumper::do_basic_type_array_class_dump(Klass* k) {
1658   DumperSupport::dump_basic_type_array_class(writer(), k);
1659 }
1660 
1661 // Walk the stack of the given thread.
1662 // Dumps a HPROF_GC_ROOT_JAVA_FRAME record for each local
1663 // Dumps a HPROF_GC_ROOT_JNI_LOCAL record for each JNI local
1664 //
1665 // It returns the number of Java frames in this thread stack
1666 int VM_HeapDumper::do_thread(JavaThread* java_thread, u4 thread_serial_num) {
1667   JNILocalsDumper blk(writer(), thread_serial_num);
1668 
1669   oop threadObj = java_thread->threadObj();
1670   assert(threadObj != NULL, "sanity check");
1671 
1672   int stack_depth = 0;
1673   if (java_thread->has_last_Java_frame()) {
1674 
1675     // vframes are resource allocated
1676     Thread* current_thread = Thread::current();
1677     ResourceMark rm(current_thread);
1678     HandleMark hm(current_thread);
1679 
1680     RegisterMap reg_map(java_thread);
1681     frame f = java_thread->last_frame();
1682     vframe* vf = vframe::new_vframe(&f, &reg_map, java_thread);
1683     frame* last_entry_frame = NULL;
1684     int extra_frames = 0;
1685 
1686     if (java_thread == _oome_thread && _oome_constructor != NULL) {
1687       extra_frames++;
1688     }
1689     while (vf != NULL) {
1690       blk.set_frame_number(stack_depth);
1691       if (vf->is_java_frame()) {
1692 
1693         // java frame (interpreted, compiled, ...)
1694         javaVFrame *jvf = javaVFrame::cast(vf);
1695         if (!(jvf->method()->is_native())) {
1696           StackValueCollection* locals = jvf->locals();
1697           for (int slot=0; slot<locals->size(); slot++) {
1698             if (locals->at(slot)->type() == T_OBJECT) {
1699               oop o = locals->obj_at(slot)();
1700 
1701               if (o != NULL) {
1702                 writer()->write_u1(HPROF_GC_ROOT_JAVA_FRAME);
1703                 writer()->write_objectID(o);
1704                 writer()->write_u4(thread_serial_num);
1705                 writer()->write_u4((u4) (stack_depth + extra_frames));
1706               }
1707             }
1708           }
1709         } else {
1710           // native frame
1711           if (stack_depth == 0) {
1712             // JNI locals for the top frame.
1713             java_thread->active_handles()->oops_do(&blk);
1714           } else {
1715             if (last_entry_frame != NULL) {
1716               // JNI locals for the entry frame
1717               assert(last_entry_frame->is_entry_frame(), "checking");
1718               last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(&blk);
1719             }
1720           }
1721         }
1722         // increment only for Java frames
1723         stack_depth++;
1724         last_entry_frame = NULL;
1725 
1726       } else {
1727         // externalVFrame - if it's an entry frame then report any JNI locals
1728         // as roots when we find the corresponding native javaVFrame
1729         frame* fr = vf->frame_pointer();
1730         assert(fr != NULL, "sanity check");
1731         if (fr->is_entry_frame()) {
1732           last_entry_frame = fr;
1733         }
1734       }
1735       vf = vf->sender();
1736     }
1737   } else {
1738     // no last java frame but there may be JNI locals
1739     java_thread->active_handles()->oops_do(&blk);
1740   }
1741   return stack_depth;
1742 }
1743 
1744 
1745 // write a HPROF_GC_ROOT_THREAD_OBJ record for each java thread. Then walk
1746 // the stack so that locals and JNI locals are dumped.
1747 void VM_HeapDumper::do_threads() {
1748   for (int i=0; i < _num_threads; i++) {
1749     JavaThread* thread = _stack_traces[i]->thread();
1750     oop threadObj = thread->threadObj();
1751     u4 thread_serial_num = i+1;
1752     u4 stack_serial_num = thread_serial_num + STACK_TRACE_ID;
1753     writer()->write_u1(HPROF_GC_ROOT_THREAD_OBJ);
1754     writer()->write_objectID(threadObj);
1755     writer()->write_u4(thread_serial_num);  // thread number
1756     writer()->write_u4(stack_serial_num);   // stack trace serial number
1757     int num_frames = do_thread(thread, thread_serial_num);
1758     assert(num_frames == _stack_traces[i]->get_stack_depth(),
1759            "total number of Java frames not matched");
1760   }
1761 }
1762 
1763 
1764 // The VM operation that dumps the heap. The dump consists of the following
1765 // records:
1766 //
1767 //  HPROF_HEADER
1768 //  [HPROF_UTF8]*
1769 //  [HPROF_LOAD_CLASS]*
1770 //  [[HPROF_FRAME]*|HPROF_TRACE]*
1771 //  [HPROF_GC_CLASS_DUMP]*
1772 //  [HPROF_HEAP_DUMP_SEGMENT]*
1773 //  HPROF_HEAP_DUMP_END
1774 //
1775 // The HPROF_TRACE records represent the stack traces where the heap dump
1776 // is generated and a "dummy trace" record which does not include
1777 // any frames. The dummy trace record is used to be referenced as the
1778 // unknown object alloc site.
1779 //
1780 // Each HPROF_HEAP_DUMP_SEGMENT record has a length followed by sub-records.
1781 // To allow the heap dump be generated in a single pass we remember the position
1782 // of the dump length and fix it up after all sub-records have been written.
1783 // To generate the sub-records we iterate over the heap, writing
1784 // HPROF_GC_INSTANCE_DUMP, HPROF_GC_OBJ_ARRAY_DUMP, and HPROF_GC_PRIM_ARRAY_DUMP
1785 // records as we go. Once that is done we write records for some of the GC
1786 // roots.
1787 
1788 void VM_HeapDumper::doit() {
1789 
1790   HandleMark hm;
1791   CollectedHeap* ch = Universe::heap();
1792 
1793   ch->ensure_parsability(false); // must happen, even if collection does
1794                                  // not happen (e.g. due to GC_locker)
1795 
1796   if (_gc_before_heap_dump) {
1797     if (GC_locker::is_active()) {
1798       warning("GC locker is held; pre-heapdump GC was skipped");
1799     } else {
1800       ch->collect_as_vm_thread(GCCause::_heap_dump);
1801     }
1802   }
1803 
1804   // At this point we should be the only dumper active, so
1805   // the following should be safe.
1806   set_global_dumper();
1807   set_global_writer();
1808 
1809   // Write the file header - we always use 1.0.2
1810   size_t used = ch->used();
1811   const char* header = "JAVA PROFILE 1.0.2";
1812 
1813   // header is few bytes long - no chance to overflow int
1814   writer()->write_raw((void*)header, (int)strlen(header));
1815   writer()->write_u1(0); // terminator
1816   writer()->write_u4(oopSize);
1817   writer()->write_u8(os::javaTimeMillis());
1818 
1819   // HPROF_UTF8 records
1820   SymbolTableDumper sym_dumper(writer());
1821   SymbolTable::symbols_do(&sym_dumper);
1822 
1823   // write HPROF_LOAD_CLASS records
1824   ClassLoaderDataGraph::classes_do(&do_load_class);
1825   Universe::basic_type_classes_do(&do_load_class);
1826 
1827   // write HPROF_FRAME and HPROF_TRACE records
1828   // this must be called after _klass_map is built when iterating the classes above.
1829   dump_stack_traces();
1830 
1831   // write HPROF_HEAP_DUMP_SEGMENT
1832   DumperSupport::write_dump_header(writer());
1833 
1834   // Writes HPROF_GC_CLASS_DUMP records
1835   ClassLoaderDataGraph::classes_do(&do_class_dump);
1836   Universe::basic_type_classes_do(&do_basic_type_array_class_dump);
1837   check_segment_length();
1838 
1839   // writes HPROF_GC_INSTANCE_DUMP records.
1840   // After each sub-record is written check_segment_length will be invoked
1841   // to check if the current segment exceeds a threshold. If so, a new
1842   // segment is started.
1843   // The HPROF_GC_CLASS_DUMP and HPROF_GC_INSTANCE_DUMP are the vast bulk
1844   // of the heap dump.
1845   HeapObjectDumper obj_dumper(this, writer());
1846   Universe::heap()->safe_object_iterate(&obj_dumper);
1847 
1848   // HPROF_GC_ROOT_THREAD_OBJ + frames + jni locals
1849   do_threads();
1850   check_segment_length();
1851 
1852   // HPROF_GC_ROOT_MONITOR_USED
1853   MonitorUsedDumper mon_dumper(writer());
1854   ObjectSynchronizer::oops_do(&mon_dumper);
1855   check_segment_length();
1856 
1857   // HPROF_GC_ROOT_JNI_GLOBAL
1858   JNIGlobalsDumper jni_dumper(writer());
1859   JNIHandles::oops_do(&jni_dumper);
1860   Universe::oops_do(&jni_dumper);  // technically not jni roots, but global roots
1861                                    // for things like preallocated throwable backtraces
1862   check_segment_length();
1863 
1864   // HPROF_GC_ROOT_STICKY_CLASS
1865   StickyClassDumper class_dumper(writer());
1866   SystemDictionary::always_strong_classes_do(&class_dumper);
1867 
1868   // fixes up the length of the dump record and writes the HPROF_HEAP_DUMP_END record.
1869   DumperSupport::end_of_dump(writer());
1870 
1871   // Now we clear the global variables, so that a future dumper might run.
1872   clear_global_dumper();
1873   clear_global_writer();
1874 }
1875 
1876 void VM_HeapDumper::dump_stack_traces() {
1877   // write a HPROF_TRACE record without any frames to be referenced as object alloc sites
1878   DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4));
1879   writer()->write_u4((u4) STACK_TRACE_ID);
1880   writer()->write_u4(0);                    // thread number
1881   writer()->write_u4(0);                    // frame count
1882 
1883   _stack_traces = NEW_C_HEAP_ARRAY(ThreadStackTrace*, Threads::number_of_threads(), mtInternal);
1884   int frame_serial_num = 0;
1885   for (JavaThread* thread = Threads::first(); thread != NULL ; thread = thread->next()) {
1886     oop threadObj = thread->threadObj();
1887     if (threadObj != NULL && !thread->is_exiting() && !thread->is_hidden_from_external_view()) {
1888       // dump thread stack trace
1889       ThreadStackTrace* stack_trace = new ThreadStackTrace(thread, false);
1890       stack_trace->dump_stack_at_safepoint(-1);
1891       _stack_traces[_num_threads++] = stack_trace;
1892 
1893       // write HPROF_FRAME records for this thread's stack trace
1894       int depth = stack_trace->get_stack_depth();
1895       int thread_frame_start = frame_serial_num;
1896       int extra_frames = 0;
1897       // write fake frame that makes it look like the thread, which caused OOME,
1898       // is in the OutOfMemoryError zero-parameter constructor
1899       if (thread == _oome_thread && _oome_constructor != NULL) {
1900         int oome_serial_num = _klass_map->find(_oome_constructor->method_holder());
1901         // the class serial number starts from 1
1902         assert(oome_serial_num > 0, "OutOfMemoryError class not found");
1903         DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, oome_serial_num,
1904                                         _oome_constructor, 0);
1905         extra_frames++;
1906       }
1907       for (int j=0; j < depth; j++) {
1908         StackFrameInfo* frame = stack_trace->stack_frame_at(j);
1909         Method* m = frame->method();
1910         int class_serial_num = _klass_map->find(m->method_holder());
1911         // the class serial number starts from 1
1912         assert(class_serial_num > 0, "class not found");
1913         DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, class_serial_num, m, frame->bci());
1914       }
1915       depth += extra_frames;
1916 
1917       // write HPROF_TRACE record for one thread
1918       DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4) + depth*oopSize);
1919       int stack_serial_num = _num_threads + STACK_TRACE_ID;
1920       writer()->write_u4(stack_serial_num);      // stack trace serial number
1921       writer()->write_u4((u4) _num_threads);     // thread serial number
1922       writer()->write_u4(depth);                 // frame count
1923       for (int j=1; j <= depth; j++) {
1924         writer()->write_id(thread_frame_start + j);
1925       }
1926     }
1927   }
1928 }
1929 
1930 // dump the heap to given path.
1931 PRAGMA_FORMAT_NONLITERAL_IGNORED_EXTERNAL
1932 int HeapDumper::dump(const char* path) {
1933   assert(path != NULL && strlen(path) > 0, "path missing");
1934 
1935   // print message in interactive case
1936   if (print_to_tty()) {
1937     tty->print_cr("Dumping heap to %s ...", path);
1938     timer()->start();
1939   }
1940 
1941   // create the dump writer. If the file can be opened then bail
1942   DumpWriter writer(path);
1943   if (!writer.is_open()) {
1944     set_error(writer.error());
1945     if (print_to_tty()) {
1946       tty->print_cr("Unable to create %s: %s", path,
1947         (error() != NULL) ? error() : "reason unknown");
1948     }
1949     return -1;
1950   }
1951 
1952   // generate the dump
1953   VM_HeapDumper dumper(&writer, _gc_before_heap_dump, _oome);
1954   if (Thread::current()->is_VM_thread()) {
1955     assert(SafepointSynchronize::is_at_safepoint(), "Expected to be called at a safepoint");
1956     dumper.doit();
1957   } else {
1958     VMThread::execute(&dumper);
1959   }
1960 
1961   // close dump file and record any error that the writer may have encountered
1962   writer.close();
1963   set_error(writer.error());
1964 
1965   // print message in interactive case
1966   if (print_to_tty()) {
1967     timer()->stop();
1968     if (error() == NULL) {
1969       tty->print_cr("Heap dump file created [" JULONG_FORMAT " bytes in %3.3f secs]",
1970                     writer.bytes_written(), timer()->seconds());
1971     } else {
1972       tty->print_cr("Dump file is incomplete: %s", writer.error());
1973     }
1974   }
1975 
1976   return (writer.error() == NULL) ? 0 : -1;
1977 }
1978 
1979 // stop timer (if still active), and free any error string we might be holding
1980 HeapDumper::~HeapDumper() {
1981   if (timer()->is_active()) {
1982     timer()->stop();
1983   }
1984   set_error(NULL);
1985 }
1986 
1987 
1988 // returns the error string (resource allocated), or NULL
1989 char* HeapDumper::error_as_C_string() const {
1990   if (error() != NULL) {
1991     char* str = NEW_RESOURCE_ARRAY(char, strlen(error())+1);
1992     strcpy(str, error());
1993     return str;
1994   } else {
1995     return NULL;
1996   }
1997 }
1998 
1999 // set the error string
2000 void HeapDumper::set_error(char* error) {
2001   if (_error != NULL) {
2002     os::free(_error);
2003   }
2004   if (error == NULL) {
2005     _error = NULL;
2006   } else {
2007     _error = os::strdup(error);
2008     assert(_error != NULL, "allocation failure");
2009   }
2010 }
2011 
2012 // Called by out-of-memory error reporting by a single Java thread
2013 // outside of a JVM safepoint
2014 void HeapDumper::dump_heap_from_oome() {
2015   HeapDumper::dump_heap(true);
2016 }
2017 
2018 // Called by error reporting by a single Java thread outside of a JVM safepoint,
2019 // or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various
2020 // callers are strictly serialized and guaranteed not to interfere below. For more
2021 // general use, however, this method will need modification to prevent
2022 // inteference when updating the static variables base_path and dump_file_seq below.
2023 void HeapDumper::dump_heap() {
2024   HeapDumper::dump_heap(false);
2025 }
2026 
2027 void HeapDumper::dump_heap(bool oome) {
2028   static char base_path[JVM_MAXPATHLEN] = {'\0'};
2029   static uint dump_file_seq = 0;
2030   char* my_path;
2031   const int max_digit_chars = 20;
2032 
2033   const char* dump_file_name = "java_pid";
2034   const char* dump_file_ext  = ".hprof";
2035 
2036   // The dump file defaults to java_pid<pid>.hprof in the current working
2037   // directory. HeapDumpPath=<file> can be used to specify an alternative
2038   // dump file name or a directory where dump file is created.
2039   if (dump_file_seq == 0) { // first time in, we initialize base_path
2040     // Calculate potentially longest base path and check if we have enough
2041     // allocated statically.
2042     const size_t total_length =
2043                       (HeapDumpPath == NULL ? 0 : strlen(HeapDumpPath)) +
2044                       strlen(os::file_separator()) + max_digit_chars +
2045                       strlen(dump_file_name) + strlen(dump_file_ext) + 1;
2046     if (total_length > sizeof(base_path)) {
2047       warning("Cannot create heap dump file.  HeapDumpPath is too long.");
2048       return;
2049     }
2050 
2051     bool use_default_filename = true;
2052     if (HeapDumpPath == NULL || HeapDumpPath[0] == '\0') {
2053       // HeapDumpPath=<file> not specified
2054     } else {
2055       strncpy(base_path, HeapDumpPath, sizeof(base_path));
2056       // check if the path is a directory (must exist)
2057       DIR* dir = os::opendir(base_path);
2058       if (dir == NULL) {
2059         use_default_filename = false;
2060       } else {
2061         // HeapDumpPath specified a directory. We append a file separator
2062         // (if needed).
2063         os::closedir(dir);
2064         size_t fs_len = strlen(os::file_separator());
2065         if (strlen(base_path) >= fs_len) {
2066           char* end = base_path;
2067           end += (strlen(base_path) - fs_len);
2068           if (strcmp(end, os::file_separator()) != 0) {
2069             strcat(base_path, os::file_separator());
2070           }
2071         }
2072       }
2073     }
2074     // If HeapDumpPath wasn't a file name then we append the default name
2075     if (use_default_filename) {
2076       const size_t dlen = strlen(base_path);  // if heap dump dir specified
2077       jio_snprintf(&base_path[dlen], sizeof(base_path)-dlen, "%s%d%s",
2078                    dump_file_name, os::current_process_id(), dump_file_ext);
2079     }
2080     const size_t len = strlen(base_path) + 1;
2081     my_path = (char*)os::malloc(len, mtInternal);
2082     if (my_path == NULL) {
2083       warning("Cannot create heap dump file.  Out of system memory.");
2084       return;
2085     }
2086     strncpy(my_path, base_path, len);
2087   } else {
2088     // Append a sequence number id for dumps following the first
2089     const size_t len = strlen(base_path) + max_digit_chars + 2; // for '.' and \0
2090     my_path = (char*)os::malloc(len, mtInternal);
2091     if (my_path == NULL) {
2092       warning("Cannot create heap dump file.  Out of system memory.");
2093       return;
2094     }
2095     jio_snprintf(my_path, len, "%s.%d", base_path, dump_file_seq);
2096   }
2097   dump_file_seq++;   // increment seq number for next time we dump
2098 
2099   HeapDumper dumper(false /* no GC before heap dump */,
2100                     true  /* send to tty */,
2101                     oome  /* pass along out-of-memory-error flag */);
2102   dumper.dump(my_path);
2103   os::free(my_path);
2104 }