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