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