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