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