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 "jvm.h"
  27 #include "classfile/symbolTable.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "gc/shared/gcLocker.inline.hpp"
  31 #include "gc/shared/genCollectedHeap.hpp"
  32 #include "gc/shared/vmGCOperations.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "memory/universe.hpp"
  35 #include "oops/objArrayKlass.hpp"
  36 #include "oops/objArrayOop.inline.hpp"
  37 #include "oops/oop.inline.hpp"
  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(oopDesc::is_oop_or_null(o), "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   // Add in resolved_references which is referenced by the cpCache
 860   // The resolved_references is an array per InstanceKlass holding the
 861   // strings and other oops resolved from the constant pool.
 862   oop resolved_references = ik->constants()->resolved_references_or_null();
 863   if (resolved_references != NULL) {
 864     field_count++;
 865 
 866     // Add in the resolved_references of the used previous versions of the class
 867     // in the case of RedefineClasses
 868     InstanceKlass* prev = ik->previous_versions();
 869     while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {
 870       field_count++;
 871       prev = prev->previous_versions();
 872     }
 873   }
 874 
 875   // Also provide a pointer to the init_lock if present, so there aren't unreferenced int[0]
 876   // arrays.
 877   oop init_lock = ik->init_lock();
 878   if (init_lock != NULL) {
 879     field_count++;
 880   }
 881 
 882   writer->write_u2(field_count);
 883 
 884   // pass 2 - dump the field descriptors and raw values
 885   for (FieldStream fld(ik, true, true); !fld.eos(); fld.next()) {
 886     if (fld.access_flags().is_static()) {
 887       Symbol* sig = fld.signature();
 888 
 889       writer->write_symbolID(fld.name());   // name
 890       writer->write_u1(sig2tag(sig));       // type
 891 
 892       // value
 893       int offset = fld.offset();
 894       address addr = (address)ik->java_mirror() + offset;
 895 
 896       dump_field_value(writer, sig->byte_at(0), addr);
 897     }
 898   }
 899 
 900   // Add resolved_references for each class that has them
 901   if (resolved_references != NULL) {
 902     writer->write_symbolID(vmSymbols::resolved_references_name());  // name
 903     writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
 904     writer->write_objectID(resolved_references);
 905 
 906     // Also write any previous versions
 907     InstanceKlass* prev = ik->previous_versions();
 908     while (prev != NULL && prev->constants()->resolved_references_or_null() != NULL) {
 909       writer->write_symbolID(vmSymbols::resolved_references_name());  // name
 910       writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
 911       writer->write_objectID(prev->constants()->resolved_references());
 912       prev = prev->previous_versions();
 913     }
 914   }
 915 
 916   // Add init lock to the end if the class is not yet initialized
 917   if (init_lock != NULL) {
 918     writer->write_symbolID(vmSymbols::init_lock_name());         // name
 919     writer->write_u1(sig2tag(vmSymbols::int_array_signature())); // type
 920     writer->write_objectID(init_lock);
 921   }
 922 }
 923 
 924 // dump the raw values of the instance fields of the given object
 925 void DumperSupport::dump_instance_fields(DumpWriter* writer, oop o) {
 926   HandleMark hm;
 927   InstanceKlass* ik = InstanceKlass::cast(o->klass());
 928 
 929   for (FieldStream fld(ik, false, false); !fld.eos(); fld.next()) {
 930     if (!fld.access_flags().is_static()) {
 931       Symbol* sig = fld.signature();
 932       address addr = (address)o + fld.offset();
 933 
 934       dump_field_value(writer, sig->byte_at(0), addr);
 935     }
 936   }
 937 }
 938 
 939 // dumps the definition of the instance fields for a given class
 940 void DumperSupport::dump_instance_field_descriptors(DumpWriter* writer, Klass* k) {
 941   HandleMark hm;
 942   InstanceKlass* ik = InstanceKlass::cast(k);
 943 
 944   // pass 1 - count the instance fields
 945   u2 field_count = 0;
 946   for (FieldStream fldc(ik, true, true); !fldc.eos(); fldc.next()) {
 947     if (!fldc.access_flags().is_static()) field_count++;
 948   }
 949 
 950   writer->write_u2(field_count);
 951 
 952   // pass 2 - dump the field descriptors
 953   for (FieldStream fld(ik, true, true); !fld.eos(); fld.next()) {
 954     if (!fld.access_flags().is_static()) {
 955       Symbol* sig = fld.signature();
 956 
 957       writer->write_symbolID(fld.name());   // name
 958       writer->write_u1(sig2tag(sig));       // type
 959     }
 960   }
 961 }
 962 
 963 // creates HPROF_GC_INSTANCE_DUMP record for the given object
 964 void DumperSupport::dump_instance(DumpWriter* writer, oop o) {
 965   Klass* k = o->klass();
 966 
 967   writer->write_u1(HPROF_GC_INSTANCE_DUMP);
 968   writer->write_objectID(o);
 969   writer->write_u4(STACK_TRACE_ID);
 970 
 971   // class ID
 972   writer->write_classID(k);
 973 
 974   // number of bytes that follow
 975   writer->write_u4(instance_size(k) );
 976 
 977   // field values
 978   dump_instance_fields(writer, o);
 979 }
 980 
 981 // creates HPROF_GC_CLASS_DUMP record for the given class and each of
 982 // its array classes
 983 void DumperSupport::dump_class_and_array_classes(DumpWriter* writer, Klass* k) {
 984   InstanceKlass* ik = InstanceKlass::cast(k);
 985 
 986   // We can safepoint and do a heap dump at a point where we have a Klass,
 987   // but no java mirror class has been setup for it. So we need to check
 988   // that the class is at least loaded, to avoid crash from a null mirror.
 989   if (!ik->is_loaded()) {
 990     return;
 991   }
 992 
 993   writer->write_u1(HPROF_GC_CLASS_DUMP);
 994 
 995   // class ID
 996   writer->write_classID(ik);
 997   writer->write_u4(STACK_TRACE_ID);
 998 
 999   // super class ID
1000   Klass* java_super = ik->java_super();
1001   if (java_super == NULL) {
1002     writer->write_objectID(oop(NULL));
1003   } else {
1004     writer->write_classID(java_super);
1005   }
1006 
1007   writer->write_objectID(ik->class_loader());
1008   writer->write_objectID(ik->signers());
1009   writer->write_objectID(ik->protection_domain());
1010 
1011   // reserved
1012   writer->write_objectID(oop(NULL));
1013   writer->write_objectID(oop(NULL));
1014 
1015   // instance size
1016   writer->write_u4(DumperSupport::instance_size(k));
1017 
1018   // size of constant pool - ignored by HAT 1.1
1019   writer->write_u2(0);
1020 
1021   // number of static fields
1022   dump_static_fields(writer, k);
1023 
1024   // description of instance fields
1025   dump_instance_field_descriptors(writer, k);
1026 
1027   // array classes
1028   k = k->array_klass_or_null();
1029   while (k != NULL) {
1030     Klass* klass = k;
1031     assert(klass->is_objArray_klass(), "not an ObjArrayKlass");
1032 
1033     writer->write_u1(HPROF_GC_CLASS_DUMP);
1034     writer->write_classID(klass);
1035     writer->write_u4(STACK_TRACE_ID);
1036 
1037     // super class of array classes is java.lang.Object
1038     java_super = klass->java_super();
1039     assert(java_super != NULL, "checking");
1040     writer->write_classID(java_super);
1041 
1042     writer->write_objectID(ik->class_loader());
1043     writer->write_objectID(ik->signers());
1044     writer->write_objectID(ik->protection_domain());
1045 
1046     writer->write_objectID(oop(NULL));    // reserved
1047     writer->write_objectID(oop(NULL));
1048     writer->write_u4(0);             // instance size
1049     writer->write_u2(0);             // constant pool
1050     writer->write_u2(0);             // static fields
1051     writer->write_u2(0);             // instance fields
1052 
1053     // get the array class for the next rank
1054     k = klass->array_klass_or_null();
1055   }
1056 }
1057 
1058 // creates HPROF_GC_CLASS_DUMP record for a given primitive array
1059 // class (and each multi-dimensional array class too)
1060 void DumperSupport::dump_basic_type_array_class(DumpWriter* writer, Klass* k) {
1061  // array classes
1062  while (k != NULL) {
1063     Klass* klass = k;
1064 
1065     writer->write_u1(HPROF_GC_CLASS_DUMP);
1066     writer->write_classID(klass);
1067     writer->write_u4(STACK_TRACE_ID);
1068 
1069     // super class of array classes is java.lang.Object
1070     Klass* java_super = klass->java_super();
1071     assert(java_super != NULL, "checking");
1072     writer->write_classID(java_super);
1073 
1074     writer->write_objectID(oop(NULL));    // loader
1075     writer->write_objectID(oop(NULL));    // signers
1076     writer->write_objectID(oop(NULL));    // protection domain
1077 
1078     writer->write_objectID(oop(NULL));    // reserved
1079     writer->write_objectID(oop(NULL));
1080     writer->write_u4(0);             // instance size
1081     writer->write_u2(0);             // constant pool
1082     writer->write_u2(0);             // static fields
1083     writer->write_u2(0);             // instance fields
1084 
1085     // get the array class for the next rank
1086     k = klass->array_klass_or_null();
1087   }
1088 }
1089 
1090 // Hprof uses an u4 as record length field,
1091 // which means we need to truncate arrays that are too long.
1092 int DumperSupport::calculate_array_max_length(DumpWriter* writer, arrayOop array, short header_size) {
1093   BasicType type = ArrayKlass::cast(array->klass())->element_type();
1094   assert(type >= T_BOOLEAN && type <= T_OBJECT, "invalid array element type");
1095 
1096   int length = array->length();
1097 
1098   int type_size;
1099   if (type == T_OBJECT) {
1100     type_size = sizeof(address);
1101   } else {
1102     type_size = type2aelembytes(type);
1103   }
1104 
1105   size_t length_in_bytes = (size_t)length * type_size;
1106 
1107   // Create a new record if the current record is non-empty and the array can't fit.
1108   julong current_record_length = writer->current_record_length();
1109   if (current_record_length > 0 &&
1110       (current_record_length + header_size + length_in_bytes) > max_juint) {
1111     write_current_dump_record_length(writer);
1112     write_dump_header(writer);
1113 
1114     // We now have an empty record.
1115     current_record_length = 0;
1116   }
1117 
1118   // Calculate max bytes we can use.
1119   uint max_bytes = max_juint - (header_size + current_record_length);
1120 
1121   // Array too long for the record?
1122   // Calculate max length and return it.
1123   if (length_in_bytes > max_bytes) {
1124     length = max_bytes / type_size;
1125     length_in_bytes = (size_t)length * type_size;
1126 
1127     warning("cannot dump array of type %s[] with length %d; truncating to length %d",
1128             type2name_tab[type], array->length(), length);
1129   }
1130   return length;
1131 }
1132 
1133 // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
1134 void DumperSupport::dump_object_array(DumpWriter* writer, objArrayOop array) {
1135   // sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID) + sizeof(classID)
1136   short header_size = 1 + 2 * 4 + 2 * sizeof(address);
1137 
1138   int length = calculate_array_max_length(writer, array, header_size);
1139 
1140   writer->write_u1(HPROF_GC_OBJ_ARRAY_DUMP);
1141   writer->write_objectID(array);
1142   writer->write_u4(STACK_TRACE_ID);
1143   writer->write_u4(length);
1144 
1145   // array class ID
1146   writer->write_classID(array->klass());
1147 
1148   // [id]* elements
1149   for (int index = 0; index < length; index++) {
1150     oop o = array->obj_at(index);
1151     writer->write_objectID(o);
1152   }
1153 }
1154 
1155 #define WRITE_ARRAY(Array, Type, Size, Length) \
1156   for (int i = 0; i < Length; i++) { writer->write_##Size((Size)Array->Type##_at(i)); }
1157 
1158 // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
1159 void DumperSupport::dump_prim_array(DumpWriter* writer, typeArrayOop array) {
1160   BasicType type = TypeArrayKlass::cast(array->klass())->element_type();
1161 
1162   // 2 * sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID)
1163   short header_size = 2 * 1 + 2 * 4 + sizeof(address);
1164 
1165   int length = calculate_array_max_length(writer, array, header_size);
1166   int type_size = type2aelembytes(type);
1167   u4 length_in_bytes = (u4)length * type_size;
1168 
1169   writer->write_u1(HPROF_GC_PRIM_ARRAY_DUMP);
1170   writer->write_objectID(array);
1171   writer->write_u4(STACK_TRACE_ID);
1172   writer->write_u4(length);
1173   writer->write_u1(type2tag(type));
1174 
1175   // nothing to copy
1176   if (length == 0) {
1177     return;
1178   }
1179 
1180   // If the byte ordering is big endian then we can copy most types directly
1181 
1182   switch (type) {
1183     case T_INT : {
1184       if (Endian::is_Java_byte_ordering_different()) {
1185         WRITE_ARRAY(array, int, u4, length);
1186       } else {
1187         writer->write_raw((void*)(array->int_at_addr(0)), length_in_bytes);
1188       }
1189       break;
1190     }
1191     case T_BYTE : {
1192       writer->write_raw((void*)(array->byte_at_addr(0)), length_in_bytes);
1193       break;
1194     }
1195     case T_CHAR : {
1196       if (Endian::is_Java_byte_ordering_different()) {
1197         WRITE_ARRAY(array, char, u2, length);
1198       } else {
1199         writer->write_raw((void*)(array->char_at_addr(0)), length_in_bytes);
1200       }
1201       break;
1202     }
1203     case T_SHORT : {
1204       if (Endian::is_Java_byte_ordering_different()) {
1205         WRITE_ARRAY(array, short, u2, length);
1206       } else {
1207         writer->write_raw((void*)(array->short_at_addr(0)), length_in_bytes);
1208       }
1209       break;
1210     }
1211     case T_BOOLEAN : {
1212       if (Endian::is_Java_byte_ordering_different()) {
1213         WRITE_ARRAY(array, bool, u1, length);
1214       } else {
1215         writer->write_raw((void*)(array->bool_at_addr(0)), length_in_bytes);
1216       }
1217       break;
1218     }
1219     case T_LONG : {
1220       if (Endian::is_Java_byte_ordering_different()) {
1221         WRITE_ARRAY(array, long, u8, length);
1222       } else {
1223         writer->write_raw((void*)(array->long_at_addr(0)), length_in_bytes);
1224       }
1225       break;
1226     }
1227 
1228     // handle float/doubles in a special value to ensure than NaNs are
1229     // written correctly. TO DO: Check if we can avoid this on processors that
1230     // use IEEE 754.
1231 
1232     case T_FLOAT : {
1233       for (int i = 0; i < length; i++) {
1234         dump_float(writer, array->float_at(i));
1235       }
1236       break;
1237     }
1238     case T_DOUBLE : {
1239       for (int i = 0; i < length; i++) {
1240         dump_double(writer, array->double_at(i));
1241       }
1242       break;
1243     }
1244     default : ShouldNotReachHere();
1245   }
1246 }
1247 
1248 // create a HPROF_FRAME record of the given Method* and bci
1249 void DumperSupport::dump_stack_frame(DumpWriter* writer,
1250                                      int frame_serial_num,
1251                                      int class_serial_num,
1252                                      Method* m,
1253                                      int bci) {
1254   int line_number;
1255   if (m->is_native()) {
1256     line_number = -3;  // native frame
1257   } else {
1258     line_number = m->line_number_from_bci(bci);
1259   }
1260 
1261   write_header(writer, HPROF_FRAME, 4*oopSize + 2*sizeof(u4));
1262   writer->write_id(frame_serial_num);               // frame serial number
1263   writer->write_symbolID(m->name());                // method's name
1264   writer->write_symbolID(m->signature());           // method's signature
1265 
1266   assert(m->method_holder()->is_instance_klass(), "not InstanceKlass");
1267   writer->write_symbolID(m->method_holder()->source_file_name());  // source file name
1268   writer->write_u4(class_serial_num);               // class serial number
1269   writer->write_u4((u4) line_number);               // line number
1270 }
1271 
1272 
1273 // Support class used to generate HPROF_UTF8 records from the entries in the
1274 // SymbolTable.
1275 
1276 class SymbolTableDumper : public SymbolClosure {
1277  private:
1278   DumpWriter* _writer;
1279   DumpWriter* writer() const                { return _writer; }
1280  public:
1281   SymbolTableDumper(DumpWriter* writer)     { _writer = writer; }
1282   void do_symbol(Symbol** p);
1283 };
1284 
1285 void SymbolTableDumper::do_symbol(Symbol** p) {
1286   ResourceMark rm;
1287   Symbol* sym = load_symbol(p);
1288   int len = sym->utf8_length();
1289   if (len > 0) {
1290     char* s = sym->as_utf8();
1291     DumperSupport::write_header(writer(), HPROF_UTF8, oopSize + len);
1292     writer()->write_symbolID(sym);
1293     writer()->write_raw(s, len);
1294   }
1295 }
1296 
1297 // Support class used to generate HPROF_GC_ROOT_JNI_LOCAL records
1298 
1299 class JNILocalsDumper : public OopClosure {
1300  private:
1301   DumpWriter* _writer;
1302   u4 _thread_serial_num;
1303   int _frame_num;
1304   DumpWriter* writer() const                { return _writer; }
1305  public:
1306   JNILocalsDumper(DumpWriter* writer, u4 thread_serial_num) {
1307     _writer = writer;
1308     _thread_serial_num = thread_serial_num;
1309     _frame_num = -1;  // default - empty stack
1310   }
1311   void set_frame_number(int n) { _frame_num = n; }
1312   void do_oop(oop* obj_p);
1313   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1314 };
1315 
1316 
1317 void JNILocalsDumper::do_oop(oop* obj_p) {
1318   // ignore null or deleted handles
1319   oop o = *obj_p;
1320   if (o != NULL && o != JNIHandles::deleted_handle()) {
1321     writer()->write_u1(HPROF_GC_ROOT_JNI_LOCAL);
1322     writer()->write_objectID(o);
1323     writer()->write_u4(_thread_serial_num);
1324     writer()->write_u4((u4)_frame_num);
1325   }
1326 }
1327 
1328 
1329 // Support class used to generate HPROF_GC_ROOT_JNI_GLOBAL records
1330 
1331 class JNIGlobalsDumper : public OopClosure {
1332  private:
1333   DumpWriter* _writer;
1334   DumpWriter* writer() const                { return _writer; }
1335 
1336  public:
1337   JNIGlobalsDumper(DumpWriter* writer) {
1338     _writer = writer;
1339   }
1340   void do_oop(oop* obj_p);
1341   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1342 };
1343 
1344 void JNIGlobalsDumper::do_oop(oop* obj_p) {
1345   oop o = *obj_p;
1346 
1347   // ignore these
1348   if (o == NULL || o == JNIHandles::deleted_handle()) return;
1349 
1350   // we ignore global ref to symbols and other internal objects
1351   if (o->is_instance() || o->is_objArray() || o->is_typeArray()) {
1352     writer()->write_u1(HPROF_GC_ROOT_JNI_GLOBAL);
1353     writer()->write_objectID(o);
1354     writer()->write_objectID((oopDesc*)obj_p);      // global ref ID
1355   }
1356 };
1357 
1358 
1359 // Support class used to generate HPROF_GC_ROOT_MONITOR_USED records
1360 
1361 class MonitorUsedDumper : public OopClosure {
1362  private:
1363   DumpWriter* _writer;
1364   DumpWriter* writer() const                { return _writer; }
1365  public:
1366   MonitorUsedDumper(DumpWriter* writer) {
1367     _writer = writer;
1368   }
1369   void do_oop(oop* obj_p) {
1370     writer()->write_u1(HPROF_GC_ROOT_MONITOR_USED);
1371     writer()->write_objectID(*obj_p);
1372   }
1373   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1374 };
1375 
1376 
1377 // Support class used to generate HPROF_GC_ROOT_STICKY_CLASS records
1378 
1379 class StickyClassDumper : public KlassClosure {
1380  private:
1381   DumpWriter* _writer;
1382   DumpWriter* writer() const                { return _writer; }
1383  public:
1384   StickyClassDumper(DumpWriter* writer) {
1385     _writer = writer;
1386   }
1387   void do_klass(Klass* k) {
1388     if (k->is_instance_klass()) {
1389       InstanceKlass* ik = InstanceKlass::cast(k);
1390         writer()->write_u1(HPROF_GC_ROOT_STICKY_CLASS);
1391         writer()->write_classID(ik);
1392       }
1393     }
1394 };
1395 
1396 
1397 class VM_HeapDumper;
1398 
1399 // Support class using when iterating over the heap.
1400 
1401 class HeapObjectDumper : public ObjectClosure {
1402  private:
1403   VM_HeapDumper* _dumper;
1404   DumpWriter* _writer;
1405 
1406   VM_HeapDumper* dumper()               { return _dumper; }
1407   DumpWriter* writer()                  { return _writer; }
1408 
1409   // used to indicate that a record has been writen
1410   void mark_end_of_record();
1411 
1412  public:
1413   HeapObjectDumper(VM_HeapDumper* dumper, DumpWriter* writer) {
1414     _dumper = dumper;
1415     _writer = writer;
1416   }
1417 
1418   // called for each object in the heap
1419   void do_object(oop o);
1420 };
1421 
1422 void HeapObjectDumper::do_object(oop o) {
1423   // hide the sentinel for deleted handles
1424   if (o == JNIHandles::deleted_handle()) return;
1425 
1426   // skip classes as these emitted as HPROF_GC_CLASS_DUMP records
1427   if (o->klass() == SystemDictionary::Class_klass()) {
1428     if (!java_lang_Class::is_primitive(o)) {
1429       return;
1430     }
1431   }
1432 
1433   if (o->is_instance()) {
1434     // create a HPROF_GC_INSTANCE record for each object
1435     DumperSupport::dump_instance(writer(), o);
1436     mark_end_of_record();
1437   } else if (o->is_objArray()) {
1438     // create a HPROF_GC_OBJ_ARRAY_DUMP record for each object array
1439     DumperSupport::dump_object_array(writer(), objArrayOop(o));
1440     mark_end_of_record();
1441   } else if (o->is_typeArray()) {
1442     // create a HPROF_GC_PRIM_ARRAY_DUMP record for each type array
1443     DumperSupport::dump_prim_array(writer(), typeArrayOop(o));
1444     mark_end_of_record();
1445   }
1446 }
1447 
1448 // The VM operation that performs the heap dump
1449 class VM_HeapDumper : public VM_GC_Operation {
1450  private:
1451   static VM_HeapDumper* _global_dumper;
1452   static DumpWriter*    _global_writer;
1453   DumpWriter*           _local_writer;
1454   JavaThread*           _oome_thread;
1455   Method*               _oome_constructor;
1456   bool _gc_before_heap_dump;
1457   GrowableArray<Klass*>* _klass_map;
1458   ThreadStackTrace** _stack_traces;
1459   int _num_threads;
1460 
1461   // accessors and setters
1462   static VM_HeapDumper* dumper()         {  assert(_global_dumper != NULL, "Error"); return _global_dumper; }
1463   static DumpWriter* writer()            {  assert(_global_writer != NULL, "Error"); return _global_writer; }
1464   void set_global_dumper() {
1465     assert(_global_dumper == NULL, "Error");
1466     _global_dumper = this;
1467   }
1468   void set_global_writer() {
1469     assert(_global_writer == NULL, "Error");
1470     _global_writer = _local_writer;
1471   }
1472   void clear_global_dumper() { _global_dumper = NULL; }
1473   void clear_global_writer() { _global_writer = NULL; }
1474 
1475   bool skip_operation() const;
1476 
1477   // writes a HPROF_LOAD_CLASS record
1478   static void do_load_class(Klass* k);
1479 
1480   // writes a HPROF_GC_CLASS_DUMP record for the given class
1481   // (and each array class too)
1482   static void do_class_dump(Klass* k);
1483 
1484   // writes a HPROF_GC_CLASS_DUMP records for a given basic type
1485   // array (and each multi-dimensional array too)
1486   static void do_basic_type_array_class_dump(Klass* k);
1487 
1488   // HPROF_GC_ROOT_THREAD_OBJ records
1489   int do_thread(JavaThread* thread, u4 thread_serial_num);
1490   void do_threads();
1491 
1492   void add_class_serial_number(Klass* k, int serial_num) {
1493     _klass_map->at_put_grow(serial_num, k);
1494   }
1495 
1496   // HPROF_TRACE and HPROF_FRAME records
1497   void dump_stack_traces();
1498 
1499  public:
1500   VM_HeapDumper(DumpWriter* writer, bool gc_before_heap_dump, bool oome) :
1501     VM_GC_Operation(0 /* total collections,      dummy, ignored */,
1502                     GCCause::_heap_dump /* GC Cause */,
1503                     0 /* total full collections, dummy, ignored */,
1504                     gc_before_heap_dump) {
1505     _local_writer = writer;
1506     _gc_before_heap_dump = gc_before_heap_dump;
1507     _klass_map = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<Klass*>(INITIAL_CLASS_COUNT, true);
1508     _stack_traces = NULL;
1509     _num_threads = 0;
1510     if (oome) {
1511       assert(!Thread::current()->is_VM_thread(), "Dump from OutOfMemoryError cannot be called by the VMThread");
1512       // get OutOfMemoryError zero-parameter constructor
1513       InstanceKlass* oome_ik = SystemDictionary::OutOfMemoryError_klass();
1514       _oome_constructor = oome_ik->find_method(vmSymbols::object_initializer_name(),
1515                                                           vmSymbols::void_method_signature());
1516       // get thread throwing OOME when generating the heap dump at OOME
1517       _oome_thread = JavaThread::current();
1518     } else {
1519       _oome_thread = NULL;
1520       _oome_constructor = NULL;
1521     }
1522   }
1523   ~VM_HeapDumper() {
1524     if (_stack_traces != NULL) {
1525       for (int i=0; i < _num_threads; i++) {
1526         delete _stack_traces[i];
1527       }
1528       FREE_C_HEAP_ARRAY(ThreadStackTrace*, _stack_traces);
1529     }
1530     delete _klass_map;
1531   }
1532 
1533   VMOp_Type type() const { return VMOp_HeapDumper; }
1534   // used to mark sub-record boundary
1535   void check_segment_length();
1536   void doit();
1537 };
1538 
1539 VM_HeapDumper* VM_HeapDumper::_global_dumper = NULL;
1540 DumpWriter*    VM_HeapDumper::_global_writer = NULL;
1541 
1542 bool VM_HeapDumper::skip_operation() const {
1543   return false;
1544 }
1545 
1546  // writes a HPROF_HEAP_DUMP_SEGMENT record
1547 void DumperSupport::write_dump_header(DumpWriter* writer) {
1548   if (writer->is_open()) {
1549     writer->write_u1(HPROF_HEAP_DUMP_SEGMENT);
1550     writer->write_u4(0); // current ticks
1551 
1552     // record the starting position for the dump (its length will be fixed up later)
1553     writer->set_dump_start(writer->current_offset());
1554     writer->write_u4(0);
1555   }
1556 }
1557 
1558 // fixes up the length of the current dump record
1559 void DumperSupport::write_current_dump_record_length(DumpWriter* writer) {
1560   if (writer->is_open()) {
1561     julong dump_end = writer->bytes_written() + writer->bytes_unwritten();
1562     julong dump_len = writer->current_record_length();
1563 
1564     // record length must fit in a u4
1565     if (dump_len > max_juint) {
1566       warning("record is too large");
1567     }
1568 
1569     // seek to the dump start and fix-up the length
1570     assert(writer->dump_start() >= 0, "no dump start recorded");
1571     writer->seek_to_offset(writer->dump_start());
1572     writer->write_u4((u4)dump_len);
1573 
1574     // adjust the total size written to keep the bytes written correct.
1575     writer->adjust_bytes_written(-((jlong) sizeof(u4)));
1576 
1577     // seek to dump end so we can continue
1578     writer->seek_to_offset(dump_end);
1579 
1580     // no current dump record
1581     writer->set_dump_start((jlong)-1);
1582   }
1583 }
1584 
1585 // used on a sub-record boundary to check if we need to start a
1586 // new segment.
1587 void VM_HeapDumper::check_segment_length() {
1588   if (writer()->is_open()) {
1589     julong dump_len = writer()->current_record_length();
1590 
1591     if (dump_len > 2UL*G) {
1592       DumperSupport::write_current_dump_record_length(writer());
1593       DumperSupport::write_dump_header(writer());
1594     }
1595   }
1596 }
1597 
1598 // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record
1599 void DumperSupport::end_of_dump(DumpWriter* writer) {
1600   if (writer->is_open()) {
1601     write_current_dump_record_length(writer);
1602 
1603     writer->write_u1(HPROF_HEAP_DUMP_END);
1604     writer->write_u4(0);
1605     writer->write_u4(0);
1606   }
1607 }
1608 
1609 // marks sub-record boundary
1610 void HeapObjectDumper::mark_end_of_record() {
1611   dumper()->check_segment_length();
1612 }
1613 
1614 // writes a HPROF_LOAD_CLASS record for the class (and each of its
1615 // array classes)
1616 void VM_HeapDumper::do_load_class(Klass* k) {
1617   static u4 class_serial_num = 0;
1618 
1619   // len of HPROF_LOAD_CLASS record
1620   u4 remaining = 2*oopSize + 2*sizeof(u4);
1621 
1622   // write a HPROF_LOAD_CLASS for the class and each array class
1623   do {
1624     DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining);
1625 
1626     // class serial number is just a number
1627     writer()->write_u4(++class_serial_num);
1628 
1629     // class ID
1630     Klass* klass = k;
1631     writer()->write_classID(klass);
1632 
1633     // add the Klass* and class serial number pair
1634     dumper()->add_class_serial_number(klass, class_serial_num);
1635 
1636     writer()->write_u4(STACK_TRACE_ID);
1637 
1638     // class name ID
1639     Symbol* name = klass->name();
1640     writer()->write_symbolID(name);
1641 
1642     // write a LOAD_CLASS record for the array type (if it exists)
1643     k = klass->array_klass_or_null();
1644   } while (k != NULL);
1645 }
1646 
1647 // writes a HPROF_GC_CLASS_DUMP record for the given class
1648 void VM_HeapDumper::do_class_dump(Klass* k) {
1649   if (k->is_instance_klass()) {
1650     DumperSupport::dump_class_and_array_classes(writer(), k);
1651   }
1652 }
1653 
1654 // writes a HPROF_GC_CLASS_DUMP records for a given basic type
1655 // array (and each multi-dimensional array too)
1656 void VM_HeapDumper::do_basic_type_array_class_dump(Klass* k) {
1657   DumperSupport::dump_basic_type_array_class(writer(), k);
1658 }
1659 
1660 // Walk the stack of the given thread.
1661 // Dumps a HPROF_GC_ROOT_JAVA_FRAME record for each local
1662 // Dumps a HPROF_GC_ROOT_JNI_LOCAL record for each JNI local
1663 //
1664 // It returns the number of Java frames in this thread stack
1665 int VM_HeapDumper::do_thread(JavaThread* java_thread, u4 thread_serial_num) {
1666   JNILocalsDumper blk(writer(), thread_serial_num);
1667 
1668   oop threadObj = java_thread->threadObj();
1669   assert(threadObj != NULL, "sanity check");
1670 
1671   int stack_depth = 0;
1672   if (java_thread->has_last_Java_frame()) {
1673 
1674     // vframes are resource allocated
1675     Thread* current_thread = Thread::current();
1676     ResourceMark rm(current_thread);
1677     HandleMark hm(current_thread);
1678 
1679     RegisterMap reg_map(java_thread);
1680     frame f = java_thread->last_frame();
1681     vframe* vf = vframe::new_vframe(&f, &reg_map, java_thread);
1682     frame* last_entry_frame = NULL;
1683     int extra_frames = 0;
1684 
1685     if (java_thread == _oome_thread && _oome_constructor != NULL) {
1686       extra_frames++;
1687     }
1688     while (vf != NULL) {
1689       blk.set_frame_number(stack_depth);
1690       if (vf->is_java_frame()) {
1691 
1692         // java frame (interpreted, compiled, ...)
1693         javaVFrame *jvf = javaVFrame::cast(vf);
1694         if (!(jvf->method()->is_native())) {
1695           StackValueCollection* locals = jvf->locals();
1696           for (int slot=0; slot<locals->size(); slot++) {
1697             if (locals->at(slot)->type() == T_OBJECT) {
1698               oop o = locals->obj_at(slot)();
1699 
1700               if (o != NULL) {
1701                 writer()->write_u1(HPROF_GC_ROOT_JAVA_FRAME);
1702                 writer()->write_objectID(o);
1703                 writer()->write_u4(thread_serial_num);
1704                 writer()->write_u4((u4) (stack_depth + extra_frames));
1705               }
1706             }
1707           }
1708           StackValueCollection *exprs = jvf->expressions();
1709           for(int index = 0; index < exprs->size(); index++) {
1710             if (exprs->at(index)->type() == T_OBJECT) {
1711                oop o = exprs->obj_at(index)();
1712                if (o != NULL) {
1713                  writer()->write_u1(HPROF_GC_ROOT_JAVA_FRAME);
1714                  writer()->write_objectID(o);
1715                  writer()->write_u4(thread_serial_num);
1716                  writer()->write_u4((u4) (stack_depth + extra_frames));
1717                }
1718              }
1719           }
1720         } else {
1721           // native frame
1722           if (stack_depth == 0) {
1723             // JNI locals for the top frame.
1724             java_thread->active_handles()->oops_do(&blk);
1725           } else {
1726             if (last_entry_frame != NULL) {
1727               // JNI locals for the entry frame
1728               assert(last_entry_frame->is_entry_frame(), "checking");
1729               last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(&blk);
1730             }
1731           }
1732         }
1733         // increment only for Java frames
1734         stack_depth++;
1735         last_entry_frame = NULL;
1736 
1737       } else {
1738         // externalVFrame - if it's an entry frame then report any JNI locals
1739         // as roots when we find the corresponding native javaVFrame
1740         frame* fr = vf->frame_pointer();
1741         assert(fr != NULL, "sanity check");
1742         if (fr->is_entry_frame()) {
1743           last_entry_frame = fr;
1744         }
1745       }
1746       vf = vf->sender();
1747     }
1748   } else {
1749     // no last java frame but there may be JNI locals
1750     java_thread->active_handles()->oops_do(&blk);
1751   }
1752   return stack_depth;
1753 }
1754 
1755 
1756 // write a HPROF_GC_ROOT_THREAD_OBJ record for each java thread. Then walk
1757 // the stack so that locals and JNI locals are dumped.
1758 void VM_HeapDumper::do_threads() {
1759   for (int i=0; i < _num_threads; i++) {
1760     JavaThread* thread = _stack_traces[i]->thread();
1761     oop threadObj = thread->threadObj();
1762     u4 thread_serial_num = i+1;
1763     u4 stack_serial_num = thread_serial_num + STACK_TRACE_ID;
1764     writer()->write_u1(HPROF_GC_ROOT_THREAD_OBJ);
1765     writer()->write_objectID(threadObj);
1766     writer()->write_u4(thread_serial_num);  // thread number
1767     writer()->write_u4(stack_serial_num);   // stack trace serial number
1768     int num_frames = do_thread(thread, thread_serial_num);
1769     assert(num_frames == _stack_traces[i]->get_stack_depth(),
1770            "total number of Java frames not matched");
1771   }
1772 }
1773 
1774 
1775 // The VM operation that dumps the heap. The dump consists of the following
1776 // records:
1777 //
1778 //  HPROF_HEADER
1779 //  [HPROF_UTF8]*
1780 //  [HPROF_LOAD_CLASS]*
1781 //  [[HPROF_FRAME]*|HPROF_TRACE]*
1782 //  [HPROF_GC_CLASS_DUMP]*
1783 //  [HPROF_HEAP_DUMP_SEGMENT]*
1784 //  HPROF_HEAP_DUMP_END
1785 //
1786 // The HPROF_TRACE records represent the stack traces where the heap dump
1787 // is generated and a "dummy trace" record which does not include
1788 // any frames. The dummy trace record is used to be referenced as the
1789 // unknown object alloc site.
1790 //
1791 // Each HPROF_HEAP_DUMP_SEGMENT record has a length followed by sub-records.
1792 // To allow the heap dump be generated in a single pass we remember the position
1793 // of the dump length and fix it up after all sub-records have been written.
1794 // To generate the sub-records we iterate over the heap, writing
1795 // HPROF_GC_INSTANCE_DUMP, HPROF_GC_OBJ_ARRAY_DUMP, and HPROF_GC_PRIM_ARRAY_DUMP
1796 // records as we go. Once that is done we write records for some of the GC
1797 // roots.
1798 
1799 void VM_HeapDumper::doit() {
1800 
1801   HandleMark hm;
1802   CollectedHeap* ch = Universe::heap();
1803 
1804   ch->ensure_parsability(false); // must happen, even if collection does
1805                                  // not happen (e.g. due to GCLocker)
1806 
1807   if (_gc_before_heap_dump) {
1808     if (GCLocker::is_active()) {
1809       warning("GC locker is held; pre-heapdump GC was skipped");
1810     } else {
1811       ch->collect_as_vm_thread(GCCause::_heap_dump);
1812     }
1813   }
1814 
1815   // At this point we should be the only dumper active, so
1816   // the following should be safe.
1817   set_global_dumper();
1818   set_global_writer();
1819 
1820   // Write the file header - we always use 1.0.2
1821   size_t used = ch->used();
1822   const char* header = "JAVA PROFILE 1.0.2";
1823 
1824   // header is few bytes long - no chance to overflow int
1825   writer()->write_raw((void*)header, (int)strlen(header));
1826   writer()->write_u1(0); // terminator
1827   writer()->write_u4(oopSize);
1828   writer()->write_u8(os::javaTimeMillis());
1829 
1830   // HPROF_UTF8 records
1831   SymbolTableDumper sym_dumper(writer());
1832   SymbolTable::symbols_do(&sym_dumper);
1833 
1834   // write HPROF_LOAD_CLASS records
1835   ClassLoaderDataGraph::classes_do(&do_load_class);
1836   Universe::basic_type_classes_do(&do_load_class);
1837 
1838   // write HPROF_FRAME and HPROF_TRACE records
1839   // this must be called after _klass_map is built when iterating the classes above.
1840   dump_stack_traces();
1841 
1842   // write HPROF_HEAP_DUMP_SEGMENT
1843   DumperSupport::write_dump_header(writer());
1844 
1845   // Writes HPROF_GC_CLASS_DUMP records
1846   ClassLoaderDataGraph::classes_do(&do_class_dump);
1847   Universe::basic_type_classes_do(&do_basic_type_array_class_dump);
1848   check_segment_length();
1849 
1850   // writes HPROF_GC_INSTANCE_DUMP records.
1851   // After each sub-record is written check_segment_length will be invoked
1852   // to check if the current segment exceeds a threshold. If so, a new
1853   // segment is started.
1854   // The HPROF_GC_CLASS_DUMP and HPROF_GC_INSTANCE_DUMP are the vast bulk
1855   // of the heap dump.
1856   HeapObjectDumper obj_dumper(this, writer());
1857   Universe::heap()->safe_object_iterate(&obj_dumper);
1858 
1859   // HPROF_GC_ROOT_THREAD_OBJ + frames + jni locals
1860   do_threads();
1861   check_segment_length();
1862 
1863   // HPROF_GC_ROOT_MONITOR_USED
1864   MonitorUsedDumper mon_dumper(writer());
1865   ObjectSynchronizer::oops_do(&mon_dumper);
1866   check_segment_length();
1867 
1868   // HPROF_GC_ROOT_JNI_GLOBAL
1869   JNIGlobalsDumper jni_dumper(writer());
1870   JNIHandles::oops_do(&jni_dumper);
1871   Universe::oops_do(&jni_dumper);  // technically not jni roots, but global roots
1872                                    // for things like preallocated throwable backtraces
1873   check_segment_length();
1874 
1875   // HPROF_GC_ROOT_STICKY_CLASS
1876   // These should be classes in the NULL class loader data, and not all classes
1877   // if !ClassUnloading
1878   StickyClassDumper class_dumper(writer());
1879   ClassLoaderData::the_null_class_loader_data()->classes_do(&class_dumper);
1880 
1881   // fixes up the length of the dump record and writes the HPROF_HEAP_DUMP_END record.
1882   DumperSupport::end_of_dump(writer());
1883 
1884   // Now we clear the global variables, so that a future dumper might run.
1885   clear_global_dumper();
1886   clear_global_writer();
1887 }
1888 
1889 void VM_HeapDumper::dump_stack_traces() {
1890   // write a HPROF_TRACE record without any frames to be referenced as object alloc sites
1891   DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4));
1892   writer()->write_u4((u4) STACK_TRACE_ID);
1893   writer()->write_u4(0);                    // thread number
1894   writer()->write_u4(0);                    // frame count
1895 
1896   _stack_traces = NEW_C_HEAP_ARRAY(ThreadStackTrace*, Threads::number_of_threads(), mtInternal);
1897   int frame_serial_num = 0;
1898   for (JavaThread* thread = Threads::first(); thread != NULL ; thread = thread->next()) {
1899     oop threadObj = thread->threadObj();
1900     if (threadObj != NULL && !thread->is_exiting() && !thread->is_hidden_from_external_view()) {
1901       // dump thread stack trace
1902       ThreadStackTrace* stack_trace = new ThreadStackTrace(thread, false);
1903       stack_trace->dump_stack_at_safepoint(-1);
1904       _stack_traces[_num_threads++] = stack_trace;
1905 
1906       // write HPROF_FRAME records for this thread's stack trace
1907       int depth = stack_trace->get_stack_depth();
1908       int thread_frame_start = frame_serial_num;
1909       int extra_frames = 0;
1910       // write fake frame that makes it look like the thread, which caused OOME,
1911       // is in the OutOfMemoryError zero-parameter constructor
1912       if (thread == _oome_thread && _oome_constructor != NULL) {
1913         int oome_serial_num = _klass_map->find(_oome_constructor->method_holder());
1914         // the class serial number starts from 1
1915         assert(oome_serial_num > 0, "OutOfMemoryError class not found");
1916         DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, oome_serial_num,
1917                                         _oome_constructor, 0);
1918         extra_frames++;
1919       }
1920       for (int j=0; j < depth; j++) {
1921         StackFrameInfo* frame = stack_trace->stack_frame_at(j);
1922         Method* m = frame->method();
1923         int class_serial_num = _klass_map->find(m->method_holder());
1924         // the class serial number starts from 1
1925         assert(class_serial_num > 0, "class not found");
1926         DumperSupport::dump_stack_frame(writer(), ++frame_serial_num, class_serial_num, m, frame->bci());
1927       }
1928       depth += extra_frames;
1929 
1930       // write HPROF_TRACE record for one thread
1931       DumperSupport::write_header(writer(), HPROF_TRACE, 3*sizeof(u4) + depth*oopSize);
1932       int stack_serial_num = _num_threads + STACK_TRACE_ID;
1933       writer()->write_u4(stack_serial_num);      // stack trace serial number
1934       writer()->write_u4((u4) _num_threads);     // thread serial number
1935       writer()->write_u4(depth);                 // frame count
1936       for (int j=1; j <= depth; j++) {
1937         writer()->write_id(thread_frame_start + j);
1938       }
1939     }
1940   }
1941 }
1942 
1943 // dump the heap to given path.
1944 int HeapDumper::dump(const char* path) {
1945   assert(path != NULL && strlen(path) > 0, "path missing");
1946 
1947   // print message in interactive case
1948   if (print_to_tty()) {
1949     tty->print_cr("Dumping heap to %s ...", path);
1950     timer()->start();
1951   }
1952 
1953   // create the dump writer. If the file can be opened then bail
1954   DumpWriter writer(path);
1955   if (!writer.is_open()) {
1956     set_error(writer.error());
1957     if (print_to_tty()) {
1958       tty->print_cr("Unable to create %s: %s", path,
1959         (error() != NULL) ? error() : "reason unknown");
1960     }
1961     return -1;
1962   }
1963 
1964   // generate the dump
1965   VM_HeapDumper dumper(&writer, _gc_before_heap_dump, _oome);
1966   if (Thread::current()->is_VM_thread()) {
1967     assert(SafepointSynchronize::is_at_safepoint(), "Expected to be called at a safepoint");
1968     dumper.doit();
1969   } else {
1970     VMThread::execute(&dumper);
1971   }
1972 
1973   // close dump file and record any error that the writer may have encountered
1974   writer.close();
1975   set_error(writer.error());
1976 
1977   // print message in interactive case
1978   if (print_to_tty()) {
1979     timer()->stop();
1980     if (error() == NULL) {
1981       tty->print_cr("Heap dump file created [" JULONG_FORMAT " bytes in %3.3f secs]",
1982                     writer.bytes_written(), timer()->seconds());
1983     } else {
1984       tty->print_cr("Dump file is incomplete: %s", writer.error());
1985     }
1986   }
1987 
1988   return (writer.error() == NULL) ? 0 : -1;
1989 }
1990 
1991 // stop timer (if still active), and free any error string we might be holding
1992 HeapDumper::~HeapDumper() {
1993   if (timer()->is_active()) {
1994     timer()->stop();
1995   }
1996   set_error(NULL);
1997 }
1998 
1999 
2000 // returns the error string (resource allocated), or NULL
2001 char* HeapDumper::error_as_C_string() const {
2002   if (error() != NULL) {
2003     char* str = NEW_RESOURCE_ARRAY(char, strlen(error())+1);
2004     strcpy(str, error());
2005     return str;
2006   } else {
2007     return NULL;
2008   }
2009 }
2010 
2011 // set the error string
2012 void HeapDumper::set_error(char* error) {
2013   if (_error != NULL) {
2014     os::free(_error);
2015   }
2016   if (error == NULL) {
2017     _error = NULL;
2018   } else {
2019     _error = os::strdup(error);
2020     assert(_error != NULL, "allocation failure");
2021   }
2022 }
2023 
2024 // Called by out-of-memory error reporting by a single Java thread
2025 // outside of a JVM safepoint
2026 void HeapDumper::dump_heap_from_oome() {
2027   HeapDumper::dump_heap(true);
2028 }
2029 
2030 // Called by error reporting by a single Java thread outside of a JVM safepoint,
2031 // or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various
2032 // callers are strictly serialized and guaranteed not to interfere below. For more
2033 // general use, however, this method will need modification to prevent
2034 // inteference when updating the static variables base_path and dump_file_seq below.
2035 void HeapDumper::dump_heap() {
2036   HeapDumper::dump_heap(false);
2037 }
2038 
2039 void HeapDumper::dump_heap(bool oome) {
2040   static char base_path[JVM_MAXPATHLEN] = {'\0'};
2041   static uint dump_file_seq = 0;
2042   char* my_path;
2043   const int max_digit_chars = 20;
2044 
2045   const char* dump_file_name = "java_pid";
2046   const char* dump_file_ext  = ".hprof";
2047 
2048   // The dump file defaults to java_pid<pid>.hprof in the current working
2049   // directory. HeapDumpPath=<file> can be used to specify an alternative
2050   // dump file name or a directory where dump file is created.
2051   if (dump_file_seq == 0) { // first time in, we initialize base_path
2052     // Calculate potentially longest base path and check if we have enough
2053     // allocated statically.
2054     const size_t total_length =
2055                       (HeapDumpPath == NULL ? 0 : strlen(HeapDumpPath)) +
2056                       strlen(os::file_separator()) + max_digit_chars +
2057                       strlen(dump_file_name) + strlen(dump_file_ext) + 1;
2058     if (total_length > sizeof(base_path)) {
2059       warning("Cannot create heap dump file.  HeapDumpPath is too long.");
2060       return;
2061     }
2062 
2063     bool use_default_filename = true;
2064     if (HeapDumpPath == NULL || HeapDumpPath[0] == '\0') {
2065       // HeapDumpPath=<file> not specified
2066     } else {
2067       strcpy(base_path, HeapDumpPath);
2068       // check if the path is a directory (must exist)
2069       DIR* dir = os::opendir(base_path);
2070       if (dir == NULL) {
2071         use_default_filename = false;
2072       } else {
2073         // HeapDumpPath specified a directory. We append a file separator
2074         // (if needed).
2075         os::closedir(dir);
2076         size_t fs_len = strlen(os::file_separator());
2077         if (strlen(base_path) >= fs_len) {
2078           char* end = base_path;
2079           end += (strlen(base_path) - fs_len);
2080           if (strcmp(end, os::file_separator()) != 0) {
2081             strcat(base_path, os::file_separator());
2082           }
2083         }
2084       }
2085     }
2086     // If HeapDumpPath wasn't a file name then we append the default name
2087     if (use_default_filename) {
2088       const size_t dlen = strlen(base_path);  // if heap dump dir specified
2089       jio_snprintf(&base_path[dlen], sizeof(base_path)-dlen, "%s%d%s",
2090                    dump_file_name, os::current_process_id(), dump_file_ext);
2091     }
2092     const size_t len = strlen(base_path) + 1;
2093     my_path = (char*)os::malloc(len, mtInternal);
2094     if (my_path == NULL) {
2095       warning("Cannot create heap dump file.  Out of system memory.");
2096       return;
2097     }
2098     strncpy(my_path, base_path, len);
2099   } else {
2100     // Append a sequence number id for dumps following the first
2101     const size_t len = strlen(base_path) + max_digit_chars + 2; // for '.' and \0
2102     my_path = (char*)os::malloc(len, mtInternal);
2103     if (my_path == NULL) {
2104       warning("Cannot create heap dump file.  Out of system memory.");
2105       return;
2106     }
2107     jio_snprintf(my_path, len, "%s.%d", base_path, dump_file_seq);
2108   }
2109   dump_file_seq++;   // increment seq number for next time we dump
2110 
2111   HeapDumper dumper(false /* no GC before heap dump */,
2112                     true  /* send to tty */,
2113                     oome  /* pass along out-of-memory-error flag */);
2114   dumper.dump(my_path);
2115   os::free(my_path);
2116 }