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