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