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