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