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