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