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