1 /*
   2  * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2023, Alibaba Group Holding Limited. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  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/vmClasses.hpp"
  32 #include "classfile/vmSymbols.hpp"
  33 #include "gc/shared/gcLocker.hpp"
  34 #include "gc/shared/gcVMOperations.hpp"
  35 #include "gc/shared/workerThread.hpp"
  36 #include "jfr/jfrEvents.hpp"
  37 #include "jvm.h"
  38 #include "memory/allocation.inline.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "memory/universe.hpp"
  41 #include "oops/fieldStreams.inline.hpp"
  42 #include "oops/klass.inline.hpp"
  43 #include "oops/objArrayKlass.hpp"
  44 #include "oops/objArrayOop.inline.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "oops/typeArrayOop.inline.hpp"
  47 #include "runtime/continuationWrapper.inline.hpp"
  48 #include "runtime/frame.inline.hpp"
  49 #include "runtime/handles.inline.hpp"
  50 #include "runtime/javaCalls.hpp"
  51 #include "runtime/javaThread.inline.hpp"
  52 #include "runtime/jniHandles.hpp"
  53 #include "runtime/os.hpp"
  54 #include "runtime/threads.hpp"
  55 #include "runtime/threadSMR.hpp"
  56 #include "runtime/vframe.hpp"
  57 #include "runtime/vmOperations.hpp"
  58 #include "runtime/vmThread.hpp"
  59 #include "runtime/timerTrace.hpp"
  60 #include "services/heapDumper.hpp"
  61 #include "services/heapDumperCompression.hpp"
  62 #include "services/threadService.hpp"
  63 #include "utilities/checkedCast.hpp"
  64 #include "utilities/macros.hpp"
  65 #include "utilities/ostream.hpp"
  66 #ifdef LINUX
  67 #include "os_linux.hpp"
  68 #endif
  69 
  70 /*
  71  * HPROF binary format - description copied from:
  72  *   src/share/demo/jvmti/hprof/hprof_io.c
  73  *
  74  *
  75  *  header    "JAVA PROFILE 1.0.2" (0-terminated)
  76  *
  77  *  u4        size of identifiers. Identifiers are used to represent
  78  *            UTF8 strings, objects, stack traces, etc. They usually
  79  *            have the same size as host pointers.
  80  * u4         high word
  81  * u4         low word    number of milliseconds since 0:00 GMT, 1/1/70
  82  * [record]*  a sequence of records.
  83  *
  84  *
  85  * Record format:
  86  *
  87  * u1         a TAG denoting the type of the record
  88  * u4         number of *microseconds* since the time stamp in the
  89  *            header. (wraps around in a little more than an hour)
  90  * u4         number of bytes *remaining* in the record. Note that
  91  *            this number excludes the tag and the length field itself.
  92  * [u1]*      BODY of the record (a sequence of bytes)
  93  *
  94  *
  95  * The following TAGs are supported:
  96  *
  97  * TAG           BODY       notes
  98  *----------------------------------------------------------
  99  * HPROF_UTF8               a UTF8-encoded name
 100  *
 101  *               id         name ID
 102  *               [u1]*      UTF8 characters (no trailing zero)
 103  *
 104  * HPROF_LOAD_CLASS         a newly loaded class
 105  *
 106  *                u4        class serial number (> 0)
 107  *                id        class object ID
 108  *                u4        stack trace serial number
 109  *                id        class name ID
 110  *
 111  * HPROF_UNLOAD_CLASS       an unloading class
 112  *
 113  *                u4        class serial_number
 114  *
 115  * HPROF_FRAME              a Java stack frame
 116  *
 117  *                id        stack frame ID
 118  *                id        method name ID
 119  *                id        method signature ID
 120  *                id        source file name ID
 121  *                u4        class serial number
 122  *                i4        line number. >0: normal
 123  *                                       -1: unknown
 124  *                                       -2: compiled method
 125  *                                       -3: native method
 126  *
 127  * HPROF_TRACE              a Java stack trace
 128  *
 129  *               u4         stack trace serial number
 130  *               u4         thread serial number
 131  *               u4         number of frames
 132  *               [id]*      stack frame IDs
 133  *
 134  *
 135  * HPROF_ALLOC_SITES        a set of heap allocation sites, obtained after GC
 136  *
 137  *               u2         flags 0x0001: incremental vs. complete
 138  *                                0x0002: sorted by allocation vs. live
 139  *                                0x0004: whether to force a GC
 140  *               u4         cutoff ratio
 141  *               u4         total live bytes
 142  *               u4         total live instances
 143  *               u8         total bytes allocated
 144  *               u8         total instances allocated
 145  *               u4         number of sites that follow
 146  *               [u1        is_array: 0:  normal object
 147  *                                    2:  object array
 148  *                                    4:  boolean array
 149  *                                    5:  char array
 150  *                                    6:  float array
 151  *                                    7:  double array
 152  *                                    8:  byte array
 153  *                                    9:  short array
 154  *                                    10: int array
 155  *                                    11: long array
 156  *                u4        class serial number (may be zero during startup)
 157  *                u4        stack trace serial number
 158  *                u4        number of bytes alive
 159  *                u4        number of instances alive
 160  *                u4        number of bytes allocated
 161  *                u4]*      number of instance allocated
 162  *
 163  * HPROF_START_THREAD       a newly started thread.
 164  *
 165  *               u4         thread serial number (> 0)
 166  *               id         thread object ID
 167  *               u4         stack trace serial number
 168  *               id         thread name ID
 169  *               id         thread group name ID
 170  *               id         thread group parent name ID
 171  *
 172  * HPROF_END_THREAD         a terminating thread.
 173  *
 174  *               u4         thread serial number
 175  *
 176  * HPROF_HEAP_SUMMARY       heap summary
 177  *
 178  *               u4         total live bytes
 179  *               u4         total live instances
 180  *               u8         total bytes allocated
 181  *               u8         total instances allocated
 182  *
 183  * HPROF_HEAP_DUMP          denote a heap dump
 184  *
 185  *               [heap dump sub-records]*
 186  *
 187  *                          There are four kinds of heap dump sub-records:
 188  *
 189  *               u1         sub-record type
 190  *
 191  *               HPROF_GC_ROOT_UNKNOWN         unknown root
 192  *
 193  *                          id         object ID
 194  *
 195  *               HPROF_GC_ROOT_THREAD_OBJ      thread object
 196  *
 197  *                          id         thread object ID  (may be 0 for a
 198  *                                     thread newly attached through JNI)
 199  *                          u4         thread sequence number
 200  *                          u4         stack trace sequence number
 201  *
 202  *               HPROF_GC_ROOT_JNI_GLOBAL      JNI global ref root
 203  *
 204  *                          id         object ID
 205  *                          id         JNI global ref ID
 206  *
 207  *               HPROF_GC_ROOT_JNI_LOCAL       JNI local ref
 208  *
 209  *                          id         object ID
 210  *                          u4         thread serial number
 211  *                          u4         frame # in stack trace (-1 for empty)
 212  *
 213  *               HPROF_GC_ROOT_JAVA_FRAME      Java stack frame
 214  *
 215  *                          id         object ID
 216  *                          u4         thread serial number
 217  *                          u4         frame # in stack trace (-1 for empty)
 218  *
 219  *               HPROF_GC_ROOT_NATIVE_STACK    Native stack
 220  *
 221  *                          id         object ID
 222  *                          u4         thread serial number
 223  *
 224  *               HPROF_GC_ROOT_STICKY_CLASS    System class
 225  *
 226  *                          id         object ID
 227  *
 228  *               HPROF_GC_ROOT_THREAD_BLOCK    Reference from thread block
 229  *
 230  *                          id         object ID
 231  *                          u4         thread serial number
 232  *
 233  *               HPROF_GC_ROOT_MONITOR_USED    Busy monitor
 234  *
 235  *                          id         object ID
 236  *
 237  *               HPROF_GC_CLASS_DUMP           dump of a class object
 238  *
 239  *                          id         class object ID
 240  *                          u4         stack trace serial number
 241  *                          id         super class object ID
 242  *                          id         class loader object ID
 243  *                          id         signers object ID
 244  *                          id         protection domain object ID
 245  *                          id         reserved
 246  *                          id         reserved
 247  *
 248  *                          u4         instance size (in bytes)
 249  *
 250  *                          u2         size of constant pool
 251  *                          [u2,       constant pool index,
 252  *                           ty,       type
 253  *                                     2:  object
 254  *                                     4:  boolean
 255  *                                     5:  char
 256  *                                     6:  float
 257  *                                     7:  double
 258  *                                     8:  byte
 259  *                                     9:  short
 260  *                                     10: int
 261  *                                     11: long
 262  *                           vl]*      and value
 263  *
 264  *                          u2         number of static fields
 265  *                          [id,       static field name,
 266  *                           ty,       type,
 267  *                           vl]*      and value
 268  *
 269  *                          u2         number of inst. fields (not inc. super)
 270  *                          [id,       instance field name,
 271  *                           ty]*      type
 272  *
 273  *               HPROF_GC_INSTANCE_DUMP        dump of a normal object
 274  *
 275  *                          id         object ID
 276  *                          u4         stack trace serial number
 277  *                          id         class object ID
 278  *                          u4         number of bytes that follow
 279  *                          [vl]*      instance field values (class, followed
 280  *                                     by super, super's super ...)
 281  *
 282  *               HPROF_GC_OBJ_ARRAY_DUMP       dump of an object array
 283  *
 284  *                          id         array object ID
 285  *                          u4         stack trace serial number
 286  *                          u4         number of elements
 287  *                          id         array class ID
 288  *                          [id]*      elements
 289  *
 290  *               HPROF_GC_PRIM_ARRAY_DUMP      dump of a primitive array
 291  *
 292  *                          id         array object ID
 293  *                          u4         stack trace serial number
 294  *                          u4         number of elements
 295  *                          u1         element type
 296  *                                     4:  boolean array
 297  *                                     5:  char array
 298  *                                     6:  float array
 299  *                                     7:  double array
 300  *                                     8:  byte array
 301  *                                     9:  short array
 302  *                                     10: int array
 303  *                                     11: long array
 304  *                          [u1]*      elements
 305  *
 306  * HPROF_CPU_SAMPLES        a set of sample traces of running threads
 307  *
 308  *                u4        total number of samples
 309  *                u4        # of traces
 310  *               [u4        # of samples
 311  *                u4]*      stack trace serial number
 312  *
 313  * HPROF_CONTROL_SETTINGS   the settings of on/off switches
 314  *
 315  *                u4        0x00000001: alloc traces on/off
 316  *                          0x00000002: cpu sampling on/off
 317  *                u2        stack trace depth
 318  *
 319  *
 320  * When the header is "JAVA PROFILE 1.0.2" a heap dump can optionally
 321  * be generated as a sequence of heap dump segments. This sequence is
 322  * terminated by an end record. The additional tags allowed by format
 323  * "JAVA PROFILE 1.0.2" are:
 324  *
 325  * HPROF_HEAP_DUMP_SEGMENT  denote a heap dump segment
 326  *
 327  *               [heap dump sub-records]*
 328  *               The same sub-record types allowed by HPROF_HEAP_DUMP
 329  *
 330  * HPROF_HEAP_DUMP_END      denotes the end of a heap dump
 331  *
 332  */
 333 
 334 
 335 // HPROF tags
 336 
 337 enum hprofTag : u1 {
 338   // top-level records
 339   HPROF_UTF8                    = 0x01,
 340   HPROF_LOAD_CLASS              = 0x02,
 341   HPROF_UNLOAD_CLASS            = 0x03,
 342   HPROF_FRAME                   = 0x04,
 343   HPROF_TRACE                   = 0x05,
 344   HPROF_ALLOC_SITES             = 0x06,
 345   HPROF_HEAP_SUMMARY            = 0x07,
 346   HPROF_START_THREAD            = 0x0A,
 347   HPROF_END_THREAD              = 0x0B,
 348   HPROF_HEAP_DUMP               = 0x0C,
 349   HPROF_CPU_SAMPLES             = 0x0D,
 350   HPROF_CONTROL_SETTINGS        = 0x0E,
 351 
 352   // 1.0.2 record types
 353   HPROF_HEAP_DUMP_SEGMENT       = 0x1C,
 354   HPROF_HEAP_DUMP_END           = 0x2C,
 355 
 356   // field types
 357   HPROF_ARRAY_OBJECT            = 0x01,
 358   HPROF_NORMAL_OBJECT           = 0x02,
 359   HPROF_BOOLEAN                 = 0x04,
 360   HPROF_CHAR                    = 0x05,
 361   HPROF_FLOAT                   = 0x06,
 362   HPROF_DOUBLE                  = 0x07,
 363   HPROF_BYTE                    = 0x08,
 364   HPROF_SHORT                   = 0x09,
 365   HPROF_INT                     = 0x0A,
 366   HPROF_LONG                    = 0x0B,
 367 
 368   // data-dump sub-records
 369   HPROF_GC_ROOT_UNKNOWN         = 0xFF,
 370   HPROF_GC_ROOT_JNI_GLOBAL      = 0x01,
 371   HPROF_GC_ROOT_JNI_LOCAL       = 0x02,
 372   HPROF_GC_ROOT_JAVA_FRAME      = 0x03,
 373   HPROF_GC_ROOT_NATIVE_STACK    = 0x04,
 374   HPROF_GC_ROOT_STICKY_CLASS    = 0x05,
 375   HPROF_GC_ROOT_THREAD_BLOCK    = 0x06,
 376   HPROF_GC_ROOT_MONITOR_USED    = 0x07,
 377   HPROF_GC_ROOT_THREAD_OBJ      = 0x08,
 378   HPROF_GC_CLASS_DUMP           = 0x20,
 379   HPROF_GC_INSTANCE_DUMP        = 0x21,
 380   HPROF_GC_OBJ_ARRAY_DUMP       = 0x22,
 381   HPROF_GC_PRIM_ARRAY_DUMP      = 0x23
 382 };
 383 
 384 // Default stack trace ID (used for dummy HPROF_TRACE record)
 385 enum {
 386   STACK_TRACE_ID = 1,
 387   INITIAL_CLASS_COUNT = 200
 388 };
 389 
 390 // Supports I/O operations for a dump
 391 // Base class for dump and parallel dump
 392 class AbstractDumpWriter : public CHeapObj<mtInternal> {
 393  protected:
 394   enum {
 395     io_buffer_max_size = 1*M,
 396     dump_segment_header_size = 9
 397   };
 398 
 399   char* _buffer;    // internal buffer
 400   size_t _size;
 401   size_t _pos;
 402 
 403   bool _in_dump_segment; // Are we currently in a dump segment?
 404   bool _is_huge_sub_record; // Are we writing a sub-record larger than the buffer size?
 405   DEBUG_ONLY(size_t _sub_record_left;) // The bytes not written for the current sub-record.
 406   DEBUG_ONLY(bool _sub_record_ended;) // True if we have called the end_sub_record().
 407 
 408   char* buffer() const                          { return _buffer; }
 409   size_t buffer_size() const                    { return _size; }
 410   void set_position(size_t pos)                 { _pos = pos; }
 411 
 412   // Can be called if we have enough room in the buffer.
 413   void write_fast(const void* s, size_t len);
 414 
 415   // Returns true if we have enough room in the buffer for 'len' bytes.
 416   bool can_write_fast(size_t len);
 417 
 418   void write_address(address a);
 419 
 420  public:
 421   AbstractDumpWriter() :
 422     _buffer(nullptr),
 423     _size(io_buffer_max_size),
 424     _pos(0),
 425     _in_dump_segment(false) { }
 426 
 427   // Total number of bytes written to the disk
 428   virtual julong bytes_written() const = 0;
 429   // Return non-null if error occurred
 430   virtual char const* error() const = 0;
 431 
 432   size_t position() const                       { return _pos; }
 433   // writer functions
 434   virtual void write_raw(const void* s, size_t len);
 435   void write_u1(u1 x);
 436   void write_u2(u2 x);
 437   void write_u4(u4 x);
 438   void write_u8(u8 x);
 439   void write_objectID(oop o);
 440   void write_rootID(oop* p);
 441   void write_symbolID(Symbol* o);
 442   void write_classID(Klass* k);
 443   void write_id(u4 x);
 444 
 445   // Start a new sub-record. Starts a new heap dump segment if needed.
 446   void start_sub_record(u1 tag, u4 len);
 447   // Ends the current sub-record.
 448   void end_sub_record();
 449   // Finishes the current dump segment if not already finished.
 450   void finish_dump_segment();
 451   // Flush internal buffer to persistent storage
 452   virtual void flush() = 0;
 453 };
 454 
 455 void AbstractDumpWriter::write_fast(const void* s, size_t len) {
 456   assert(!_in_dump_segment || (_sub_record_left >= len), "sub-record too large");
 457   assert(buffer_size() - position() >= len, "Must fit");
 458   debug_only(_sub_record_left -= len);
 459   memcpy(buffer() + position(), s, len);
 460   set_position(position() + len);
 461 }
 462 
 463 bool AbstractDumpWriter::can_write_fast(size_t len) {
 464   return buffer_size() - position() >= len;
 465 }
 466 
 467 // write raw bytes
 468 void AbstractDumpWriter::write_raw(const void* s, size_t len) {
 469   assert(!_in_dump_segment || (_sub_record_left >= len), "sub-record too large");
 470   debug_only(_sub_record_left -= len);
 471 
 472   // flush buffer to make room.
 473   while (len > buffer_size() - position()) {
 474     assert(!_in_dump_segment || _is_huge_sub_record,
 475            "Cannot overflow in non-huge sub-record.");
 476     size_t to_write = buffer_size() - position();
 477     memcpy(buffer() + position(), s, to_write);
 478     s = (void*) ((char*) s + to_write);
 479     len -= to_write;
 480     set_position(position() + to_write);
 481     flush();
 482   }
 483 
 484   memcpy(buffer() + position(), s, len);
 485   set_position(position() + len);
 486 }
 487 
 488 // Makes sure we inline the fast write into the write_u* functions. This is a big speedup.
 489 #define WRITE_KNOWN_TYPE(p, len) do { if (can_write_fast((len))) write_fast((p), (len)); \
 490                                       else write_raw((p), (len)); } while (0)
 491 
 492 void AbstractDumpWriter::write_u1(u1 x) {
 493   WRITE_KNOWN_TYPE(&x, 1);
 494 }
 495 
 496 void AbstractDumpWriter::write_u2(u2 x) {
 497   u2 v;
 498   Bytes::put_Java_u2((address)&v, x);
 499   WRITE_KNOWN_TYPE(&v, 2);
 500 }
 501 
 502 void AbstractDumpWriter::write_u4(u4 x) {
 503   u4 v;
 504   Bytes::put_Java_u4((address)&v, x);
 505   WRITE_KNOWN_TYPE(&v, 4);
 506 }
 507 
 508 void AbstractDumpWriter::write_u8(u8 x) {
 509   u8 v;
 510   Bytes::put_Java_u8((address)&v, x);
 511   WRITE_KNOWN_TYPE(&v, 8);
 512 }
 513 
 514 void AbstractDumpWriter::write_address(address a) {
 515 #ifdef _LP64
 516   write_u8((u8)a);
 517 #else
 518   write_u4((u4)a);
 519 #endif
 520 }
 521 
 522 void AbstractDumpWriter::write_objectID(oop o) {
 523   write_address(cast_from_oop<address>(o));
 524 }
 525 
 526 void AbstractDumpWriter::write_rootID(oop* p) {
 527   write_address((address)p);
 528 }
 529 
 530 void AbstractDumpWriter::write_symbolID(Symbol* s) {
 531   write_address((address)((uintptr_t)s));
 532 }
 533 
 534 void AbstractDumpWriter::write_id(u4 x) {
 535 #ifdef _LP64
 536   write_u8((u8) x);
 537 #else
 538   write_u4(x);
 539 #endif
 540 }
 541 
 542 // We use java mirror as the class ID
 543 void AbstractDumpWriter::write_classID(Klass* k) {
 544   write_objectID(k->java_mirror());
 545 }
 546 
 547 void AbstractDumpWriter::finish_dump_segment() {
 548   if (_in_dump_segment) {
 549     assert(_sub_record_left == 0, "Last sub-record not written completely");
 550     assert(_sub_record_ended, "sub-record must have ended");
 551 
 552     // Fix up the dump segment length if we haven't written a huge sub-record last
 553     // (in which case the segment length was already set to the correct value initially).
 554     if (!_is_huge_sub_record) {
 555       assert(position() > dump_segment_header_size, "Dump segment should have some content");
 556       Bytes::put_Java_u4((address) (buffer() + 5),
 557                          (u4) (position() - dump_segment_header_size));
 558     } else {
 559       // Finish process huge sub record
 560       // Set _is_huge_sub_record to false so the parallel dump writer can flush data to file.
 561       _is_huge_sub_record = false;
 562     }
 563 
 564     _in_dump_segment = false;
 565     flush();
 566   }
 567 }
 568 
 569 void AbstractDumpWriter::start_sub_record(u1 tag, u4 len) {
 570   if (!_in_dump_segment) {
 571     if (position() > 0) {
 572       flush();
 573     }
 574 
 575     assert(position() == 0 && buffer_size() > dump_segment_header_size, "Must be at the start");
 576 
 577     write_u1(HPROF_HEAP_DUMP_SEGMENT);
 578     write_u4(0); // timestamp
 579     // Will be fixed up later if we add more sub-records.  If this is a huge sub-record,
 580     // this is already the correct length, since we don't add more sub-records.
 581     write_u4(len);
 582     assert(Bytes::get_Java_u4((address)(buffer() + 5)) == len, "Inconsistent size!");
 583     _in_dump_segment = true;
 584     _is_huge_sub_record = len > buffer_size() - dump_segment_header_size;
 585   } else if (_is_huge_sub_record || (len > buffer_size() - position())) {
 586     // This object will not fit in completely or the last sub-record was huge.
 587     // Finish the current segment and try again.
 588     finish_dump_segment();
 589     start_sub_record(tag, len);
 590 
 591     return;
 592   }
 593 
 594   debug_only(_sub_record_left = len);
 595   debug_only(_sub_record_ended = false);
 596 
 597   write_u1(tag);
 598 }
 599 
 600 void AbstractDumpWriter::end_sub_record() {
 601   assert(_in_dump_segment, "must be in dump segment");
 602   assert(_sub_record_left == 0, "sub-record not written completely");
 603   assert(!_sub_record_ended, "Must not have ended yet");
 604   debug_only(_sub_record_ended = true);
 605 }
 606 
 607 // Supports I/O operations for a dump
 608 
 609 class DumpWriter : public AbstractDumpWriter {
 610 private:
 611   FileWriter* _writer;
 612   AbstractCompressor* _compressor;
 613   size_t _bytes_written;
 614   char* _error;
 615   // Compression support
 616   char* _out_buffer;
 617   size_t _out_size;
 618   size_t _out_pos;
 619   char* _tmp_buffer;
 620   size_t _tmp_size;
 621 
 622 private:
 623   void do_compress();
 624 
 625 public:
 626   DumpWriter(const char* path, bool overwrite, AbstractCompressor* compressor);
 627   ~DumpWriter();
 628   julong bytes_written() const override        { return (julong) _bytes_written; }
 629   char const* error() const override           { return _error; }
 630   void set_error(const char* error)            { _error = (char*)error; }
 631   bool has_error() const                       { return _error != nullptr; }
 632   const char* get_file_path() const            { return _writer->get_file_path(); }
 633   AbstractCompressor* compressor()             { return _compressor; }
 634   bool is_overwrite() const                    { return _writer->is_overwrite(); }
 635 
 636   void flush() override;
 637 
 638 private:
 639   // internals for DumpMerger
 640   friend class DumpMerger;
 641   void set_bytes_written(julong bytes_written) { _bytes_written = bytes_written; }
 642   int get_fd() const                           { return _writer->get_fd(); }
 643   void set_compressor(AbstractCompressor* p)   { _compressor = p; }
 644 };
 645 
 646 DumpWriter::DumpWriter(const char* path, bool overwrite, AbstractCompressor* compressor) :
 647   AbstractDumpWriter(),
 648   _writer(new (std::nothrow) FileWriter(path, overwrite)),
 649   _compressor(compressor),
 650   _bytes_written(0),
 651   _error(nullptr),
 652   _out_buffer(nullptr),
 653   _out_size(0),
 654   _out_pos(0),
 655   _tmp_buffer(nullptr),
 656   _tmp_size(0) {
 657   _error = (char*)_writer->open_writer();
 658   if (_error == nullptr) {
 659     _buffer = (char*)os::malloc(io_buffer_max_size, mtInternal);
 660     if (compressor != nullptr) {
 661       _error = (char*)_compressor->init(io_buffer_max_size, &_out_size, &_tmp_size);
 662       if (_error == nullptr) {
 663         if (_out_size > 0) {
 664           _out_buffer = (char*)os::malloc(_out_size, mtInternal);
 665         }
 666         if (_tmp_size > 0) {
 667           _tmp_buffer = (char*)os::malloc(_tmp_size, mtInternal);
 668         }
 669       }
 670     }
 671   }
 672   // initialize internal buffer
 673   _pos = 0;
 674   _size = io_buffer_max_size;
 675 }
 676 
 677 DumpWriter::~DumpWriter(){
 678   if (_buffer != nullptr) {
 679     os::free(_buffer);
 680   }
 681   if (_out_buffer != nullptr) {
 682     os::free(_out_buffer);
 683   }
 684   if (_tmp_buffer != nullptr) {
 685     os::free(_tmp_buffer);
 686   }
 687   if (_writer != nullptr) {
 688     delete _writer;
 689   }
 690   _bytes_written = -1;
 691 }
 692 
 693 // flush any buffered bytes to the file
 694 void DumpWriter::flush() {
 695   if (_pos <= 0) {
 696     return;
 697   }
 698   if (has_error()) {
 699     _pos = 0;
 700     return;
 701   }
 702   char* result = nullptr;
 703   if (_compressor == nullptr) {
 704     result = (char*)_writer->write_buf(_buffer, _pos);
 705     _bytes_written += _pos;
 706   } else {
 707     do_compress();
 708     if (!has_error()) {
 709       result = (char*)_writer->write_buf(_out_buffer, _out_pos);
 710       _bytes_written += _out_pos;
 711     }
 712   }
 713   _pos = 0; // reset pos to make internal buffer available
 714 
 715   if (result != nullptr) {
 716     set_error(result);
 717   }
 718 }
 719 
 720 void DumpWriter::do_compress() {
 721   const char* msg = _compressor->compress(_buffer, _pos, _out_buffer, _out_size,
 722                                           _tmp_buffer, _tmp_size, &_out_pos);
 723 
 724   if (msg != nullptr) {
 725     set_error(msg);
 726   }
 727 }
 728 
 729 class DumperClassCacheTable;
 730 class DumperClassCacheTableEntry;
 731 
 732 // Support class with a collection of functions used when dumping the heap
 733 class DumperSupport : AllStatic {
 734  public:
 735 
 736   // write a header of the given type
 737   static void write_header(AbstractDumpWriter* writer, hprofTag tag, u4 len);
 738 
 739   // returns hprof tag for the given type signature
 740   static hprofTag sig2tag(Symbol* sig);
 741   // returns hprof tag for the given basic type
 742   static hprofTag type2tag(BasicType type);
 743   // Returns the size of the data to write.
 744   static u4 sig2size(Symbol* sig);
 745 
 746   // returns the size of the instance of the given class
 747   static u4 instance_size(InstanceKlass* ik, DumperClassCacheTableEntry* class_cache_entry = nullptr);
 748 
 749   // dump a jfloat
 750   static void dump_float(AbstractDumpWriter* writer, jfloat f);
 751   // dump a jdouble
 752   static void dump_double(AbstractDumpWriter* writer, jdouble d);
 753   // dumps the raw value of the given field
 754   static void dump_field_value(AbstractDumpWriter* writer, char type, oop obj, int offset);
 755   // returns the size of the static fields; also counts the static fields
 756   static u4 get_static_fields_size(InstanceKlass* ik, u2& field_count);
 757   // dumps static fields of the given class
 758   static void dump_static_fields(AbstractDumpWriter* writer, Klass* k);
 759   // dump the raw values of the instance fields of the given object
 760   static void dump_instance_fields(AbstractDumpWriter* writer, oop o, DumperClassCacheTableEntry* class_cache_entry);
 761   // get the count of the instance fields for a given class
 762   static u2 get_instance_fields_count(InstanceKlass* ik);
 763   // dumps the definition of the instance fields for a given class
 764   static void dump_instance_field_descriptors(AbstractDumpWriter* writer, Klass* k);
 765   // creates HPROF_GC_INSTANCE_DUMP record for the given object
 766   static void dump_instance(AbstractDumpWriter* writer, oop o, DumperClassCacheTable* class_cache);
 767   // creates HPROF_GC_CLASS_DUMP record for the given instance class
 768   static void dump_instance_class(AbstractDumpWriter* writer, Klass* k);
 769   // creates HPROF_GC_CLASS_DUMP record for a given array class
 770   static void dump_array_class(AbstractDumpWriter* writer, Klass* k);
 771 
 772   // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
 773   static void dump_object_array(AbstractDumpWriter* writer, objArrayOop array);
 774   // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
 775   static void dump_prim_array(AbstractDumpWriter* writer, typeArrayOop array);
 776   // create HPROF_FRAME record for the given method and bci
 777   static void dump_stack_frame(AbstractDumpWriter* writer, int frame_serial_num, int class_serial_num, Method* m, int bci);
 778 
 779   // check if we need to truncate an array
 780   static int calculate_array_max_length(AbstractDumpWriter* writer, arrayOop array, short header_size);
 781 
 782   // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record
 783   static void end_of_dump(AbstractDumpWriter* writer);
 784 
 785   static oop mask_dormant_archived_object(oop o, oop ref_obj) {
 786     if (o != nullptr && o->klass()->java_mirror_no_keepalive() == nullptr) {
 787       // Ignore this object since the corresponding java mirror is not loaded.
 788       // Might be a dormant archive object.
 789       report_dormant_archived_object(o, ref_obj);
 790       return nullptr;
 791     } else {
 792       return o;
 793     }
 794   }
 795 
 796   static void report_dormant_archived_object(oop o, oop ref_obj) {
 797     if (log_is_enabled(Trace, cds, heap)) {
 798       ResourceMark rm;
 799       if (ref_obj != nullptr) {
 800         log_trace(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s) referenced by " INTPTR_FORMAT " (%s)",
 801                   p2i(o), o->klass()->external_name(),
 802                   p2i(ref_obj), ref_obj->klass()->external_name());
 803       } else {
 804         log_trace(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)",
 805                   p2i(o), o->klass()->external_name());
 806       }
 807     }
 808   }
 809 };
 810 
 811 // Hash table of klasses to the klass metadata. This should greatly improve the
 812 // hash dumping performance. This hash table is supposed to be used by a single
 813 // thread only.
 814 //
 815 class DumperClassCacheTableEntry : public CHeapObj<mtServiceability> {
 816   friend class DumperClassCacheTable;
 817 private:
 818   GrowableArray<char> _sigs_start;
 819   GrowableArray<int> _offsets;
 820   u4 _instance_size;
 821   int _entries;
 822 
 823 public:
 824   DumperClassCacheTableEntry() : _instance_size(0), _entries(0) {};
 825 
 826   int field_count()             { return _entries; }
 827   char sig_start(int field_idx) { return _sigs_start.at(field_idx); }
 828   int offset(int field_idx)     { return _offsets.at(field_idx); }
 829   u4 instance_size()            { return _instance_size; }
 830 };
 831 
 832 class DumperClassCacheTable {
 833 private:
 834   // ResourceHashtable SIZE is specified at compile time so we
 835   // use 1031 which is the first prime after 1024.
 836   static constexpr size_t TABLE_SIZE = 1031;
 837 
 838   // Maintain the cache for N classes. This limits memory footprint
 839   // impact, regardless of how many classes we have in the dump.
 840   // This also improves look up performance by keeping the statically
 841   // sized table from overloading.
 842   static constexpr int CACHE_TOP = 256;
 843 
 844   typedef ResourceHashtable<InstanceKlass*, DumperClassCacheTableEntry*,
 845                             TABLE_SIZE, AnyObj::C_HEAP, mtServiceability> PtrTable;
 846   PtrTable* _ptrs;
 847 
 848   // Single-slot cache to handle the major case of objects of the same
 849   // class back-to-back, e.g. from T[].
 850   InstanceKlass* _last_ik;
 851   DumperClassCacheTableEntry* _last_entry;
 852 
 853   void unlink_all(PtrTable* table) {
 854     class CleanupEntry: StackObj {
 855     public:
 856       bool do_entry(InstanceKlass*& key, DumperClassCacheTableEntry*& entry) {
 857         delete entry;
 858         return true;
 859       }
 860     } cleanup;
 861     table->unlink(&cleanup);
 862   }
 863 
 864 public:
 865   DumperClassCacheTableEntry* lookup_or_create(InstanceKlass* ik) {
 866     if (_last_ik == ik) {
 867       return _last_entry;
 868     }
 869 
 870     DumperClassCacheTableEntry* entry;
 871     DumperClassCacheTableEntry** from_cache = _ptrs->get(ik);
 872     if (from_cache == nullptr) {
 873       entry = new DumperClassCacheTableEntry();
 874       for (HierarchicalFieldStream<JavaFieldStream> fld(ik); !fld.done(); fld.next()) {
 875         if (!fld.access_flags().is_static()) {
 876           Symbol* sig = fld.signature();
 877           entry->_sigs_start.push(sig->char_at(0));
 878           entry->_offsets.push(fld.offset());
 879           entry->_entries++;
 880           entry->_instance_size += DumperSupport::sig2size(sig);
 881         }
 882       }
 883 
 884       if (_ptrs->number_of_entries() >= CACHE_TOP) {
 885         // We do not track the individual hit rates for table entries.
 886         // Purge the entire table, and let the cache catch up with new
 887         // distribution.
 888         unlink_all(_ptrs);
 889       }
 890 
 891       _ptrs->put(ik, entry);
 892     } else {
 893       entry = *from_cache;
 894     }
 895 
 896     // Remember for single-slot cache.
 897     _last_ik = ik;
 898     _last_entry = entry;
 899 
 900     return entry;
 901   }
 902 
 903   DumperClassCacheTable() : _ptrs(new (mtServiceability) PtrTable), _last_ik(nullptr), _last_entry(nullptr) {}
 904 
 905   ~DumperClassCacheTable() {
 906     unlink_all(_ptrs);
 907     delete _ptrs;
 908   }
 909 };
 910 
 911 // write a header of the given type
 912 void DumperSupport:: write_header(AbstractDumpWriter* writer, hprofTag tag, u4 len) {
 913   writer->write_u1(tag);
 914   writer->write_u4(0);                  // current ticks
 915   writer->write_u4(len);
 916 }
 917 
 918 // returns hprof tag for the given type signature
 919 hprofTag DumperSupport::sig2tag(Symbol* sig) {
 920   switch (sig->char_at(0)) {
 921     case JVM_SIGNATURE_CLASS    : return HPROF_NORMAL_OBJECT;
 922     case JVM_SIGNATURE_ARRAY    : return HPROF_NORMAL_OBJECT;
 923     case JVM_SIGNATURE_BYTE     : return HPROF_BYTE;
 924     case JVM_SIGNATURE_CHAR     : return HPROF_CHAR;
 925     case JVM_SIGNATURE_FLOAT    : return HPROF_FLOAT;
 926     case JVM_SIGNATURE_DOUBLE   : return HPROF_DOUBLE;
 927     case JVM_SIGNATURE_INT      : return HPROF_INT;
 928     case JVM_SIGNATURE_LONG     : return HPROF_LONG;
 929     case JVM_SIGNATURE_SHORT    : return HPROF_SHORT;
 930     case JVM_SIGNATURE_BOOLEAN  : return HPROF_BOOLEAN;
 931     default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
 932   }
 933 }
 934 
 935 hprofTag DumperSupport::type2tag(BasicType type) {
 936   switch (type) {
 937     case T_BYTE     : return HPROF_BYTE;
 938     case T_CHAR     : return HPROF_CHAR;
 939     case T_FLOAT    : return HPROF_FLOAT;
 940     case T_DOUBLE   : return HPROF_DOUBLE;
 941     case T_INT      : return HPROF_INT;
 942     case T_LONG     : return HPROF_LONG;
 943     case T_SHORT    : return HPROF_SHORT;
 944     case T_BOOLEAN  : return HPROF_BOOLEAN;
 945     default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
 946   }
 947 }
 948 
 949 u4 DumperSupport::sig2size(Symbol* sig) {
 950   switch (sig->char_at(0)) {
 951     case JVM_SIGNATURE_CLASS:
 952     case JVM_SIGNATURE_ARRAY: return sizeof(address);
 953     case JVM_SIGNATURE_BOOLEAN:
 954     case JVM_SIGNATURE_BYTE: return 1;
 955     case JVM_SIGNATURE_SHORT:
 956     case JVM_SIGNATURE_CHAR: return 2;
 957     case JVM_SIGNATURE_INT:
 958     case JVM_SIGNATURE_FLOAT: return 4;
 959     case JVM_SIGNATURE_LONG:
 960     case JVM_SIGNATURE_DOUBLE: return 8;
 961     default: ShouldNotReachHere(); /* to shut up compiler */ return 0;
 962   }
 963 }
 964 
 965 template<typename T, typename F> T bit_cast(F from) { // replace with the real thing when we can use c++20
 966   T to;
 967   static_assert(sizeof(to) == sizeof(from), "must be of the same size");
 968   memcpy(&to, &from, sizeof(to));
 969   return to;
 970 }
 971 
 972 // dump a jfloat
 973 void DumperSupport::dump_float(AbstractDumpWriter* writer, jfloat f) {
 974   if (g_isnan(f)) {
 975     writer->write_u4(0x7fc00000); // collapsing NaNs
 976   } else {
 977     writer->write_u4(bit_cast<u4>(f));
 978   }
 979 }
 980 
 981 // dump a jdouble
 982 void DumperSupport::dump_double(AbstractDumpWriter* writer, jdouble d) {
 983   if (g_isnan(d)) {
 984     writer->write_u8(0x7ff80000ull << 32); // collapsing NaNs
 985   } else {
 986     writer->write_u8(bit_cast<u8>(d));
 987   }
 988 }
 989 
 990 // dumps the raw value of the given field
 991 void DumperSupport::dump_field_value(AbstractDumpWriter* writer, char type, oop obj, int offset) {
 992   switch (type) {
 993     case JVM_SIGNATURE_CLASS :
 994     case JVM_SIGNATURE_ARRAY : {
 995       oop o = obj->obj_field_access<ON_UNKNOWN_OOP_REF | AS_NO_KEEPALIVE>(offset);
 996       o = mask_dormant_archived_object(o, obj);
 997       assert(oopDesc::is_oop_or_null(o), "Expected an oop or nullptr at " PTR_FORMAT, p2i(o));
 998       writer->write_objectID(o);
 999       break;
1000     }
1001     case JVM_SIGNATURE_BYTE : {
1002       jbyte b = obj->byte_field(offset);
1003       writer->write_u1(b);
1004       break;
1005     }
1006     case JVM_SIGNATURE_CHAR : {
1007       jchar c = obj->char_field(offset);
1008       writer->write_u2(c);
1009       break;
1010     }
1011     case JVM_SIGNATURE_SHORT : {
1012       jshort s = obj->short_field(offset);
1013       writer->write_u2(s);
1014       break;
1015     }
1016     case JVM_SIGNATURE_FLOAT : {
1017       jfloat f = obj->float_field(offset);
1018       dump_float(writer, f);
1019       break;
1020     }
1021     case JVM_SIGNATURE_DOUBLE : {
1022       jdouble d = obj->double_field(offset);
1023       dump_double(writer, d);
1024       break;
1025     }
1026     case JVM_SIGNATURE_INT : {
1027       jint i = obj->int_field(offset);
1028       writer->write_u4(i);
1029       break;
1030     }
1031     case JVM_SIGNATURE_LONG : {
1032       jlong l = obj->long_field(offset);
1033       writer->write_u8(l);
1034       break;
1035     }
1036     case JVM_SIGNATURE_BOOLEAN : {
1037       jboolean b = obj->bool_field(offset);
1038       writer->write_u1(b);
1039       break;
1040     }
1041     default : {
1042       ShouldNotReachHere();
1043       break;
1044     }
1045   }
1046 }
1047 
1048 // returns the size of the instance of the given class
1049 u4 DumperSupport::instance_size(InstanceKlass* ik, DumperClassCacheTableEntry* class_cache_entry) {
1050   if (class_cache_entry != nullptr) {
1051     return class_cache_entry->instance_size();
1052   } else {
1053     u4 size = 0;
1054     for (HierarchicalFieldStream<JavaFieldStream> fld(ik); !fld.done(); fld.next()) {
1055       if (!fld.access_flags().is_static()) {
1056         size += sig2size(fld.signature());
1057       }
1058     }
1059     return size;
1060   }
1061 }
1062 
1063 u4 DumperSupport::get_static_fields_size(InstanceKlass* ik, u2& field_count) {
1064   field_count = 0;
1065   u4 size = 0;
1066 
1067   for (JavaFieldStream fldc(ik); !fldc.done(); fldc.next()) {
1068     if (fldc.access_flags().is_static()) {
1069       field_count++;
1070       size += sig2size(fldc.signature());
1071     }
1072   }
1073 
1074   // Add in resolved_references which is referenced by the cpCache
1075   // The resolved_references is an array per InstanceKlass holding the
1076   // strings and other oops resolved from the constant pool.
1077   oop resolved_references = ik->constants()->resolved_references_or_null();
1078   if (resolved_references != nullptr) {
1079     field_count++;
1080     size += sizeof(address);
1081 
1082     // Add in the resolved_references of the used previous versions of the class
1083     // in the case of RedefineClasses
1084     InstanceKlass* prev = ik->previous_versions();
1085     while (prev != nullptr && prev->constants()->resolved_references_or_null() != nullptr) {
1086       field_count++;
1087       size += sizeof(address);
1088       prev = prev->previous_versions();
1089     }
1090   }
1091 
1092   // Also provide a pointer to the init_lock if present, so there aren't unreferenced int[0]
1093   // arrays.
1094   oop init_lock = ik->init_lock();
1095   if (init_lock != nullptr) {
1096     field_count++;
1097     size += sizeof(address);
1098   }
1099 
1100   // We write the value itself plus a name and a one byte type tag per field.
1101   return checked_cast<u4>(size + field_count * (sizeof(address) + 1));
1102 }
1103 
1104 // dumps static fields of the given class
1105 void DumperSupport::dump_static_fields(AbstractDumpWriter* writer, Klass* k) {
1106   InstanceKlass* ik = InstanceKlass::cast(k);
1107 
1108   // dump the field descriptors and raw values
1109   for (JavaFieldStream fld(ik); !fld.done(); fld.next()) {
1110     if (fld.access_flags().is_static()) {
1111       Symbol* sig = fld.signature();
1112 
1113       writer->write_symbolID(fld.name());   // name
1114       writer->write_u1(sig2tag(sig));       // type
1115 
1116       // value
1117       dump_field_value(writer, sig->char_at(0), ik->java_mirror(), fld.offset());
1118     }
1119   }
1120 
1121   // Add resolved_references for each class that has them
1122   oop resolved_references = ik->constants()->resolved_references_or_null();
1123   if (resolved_references != nullptr) {
1124     writer->write_symbolID(vmSymbols::resolved_references_name());  // name
1125     writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
1126     writer->write_objectID(resolved_references);
1127 
1128     // Also write any previous versions
1129     InstanceKlass* prev = ik->previous_versions();
1130     while (prev != nullptr && prev->constants()->resolved_references_or_null() != nullptr) {
1131       writer->write_symbolID(vmSymbols::resolved_references_name());  // name
1132       writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
1133       writer->write_objectID(prev->constants()->resolved_references());
1134       prev = prev->previous_versions();
1135     }
1136   }
1137 
1138   // Add init lock to the end if the class is not yet initialized
1139   oop init_lock = ik->init_lock();
1140   if (init_lock != nullptr) {
1141     writer->write_symbolID(vmSymbols::init_lock_name());         // name
1142     writer->write_u1(sig2tag(vmSymbols::int_array_signature())); // type
1143     writer->write_objectID(init_lock);
1144   }
1145 }
1146 
1147 // dump the raw values of the instance fields of the given object
1148 void DumperSupport::dump_instance_fields(AbstractDumpWriter* writer, oop o, DumperClassCacheTableEntry* class_cache_entry) {
1149   assert(class_cache_entry != nullptr, "Pre-condition: must be provided");
1150   for (int idx = 0; idx < class_cache_entry->field_count(); idx++) {
1151     dump_field_value(writer, class_cache_entry->sig_start(idx), o, class_cache_entry->offset(idx));
1152   }
1153 }
1154 
1155 // dumps the definition of the instance fields for a given class
1156 u2 DumperSupport::get_instance_fields_count(InstanceKlass* ik) {
1157   u2 field_count = 0;
1158 
1159   for (JavaFieldStream fldc(ik); !fldc.done(); fldc.next()) {
1160     if (!fldc.access_flags().is_static()) field_count++;
1161   }
1162 
1163   return field_count;
1164 }
1165 
1166 // dumps the definition of the instance fields for a given class
1167 void DumperSupport::dump_instance_field_descriptors(AbstractDumpWriter* writer, Klass* k) {
1168   InstanceKlass* ik = InstanceKlass::cast(k);
1169 
1170   // dump the field descriptors
1171   for (JavaFieldStream fld(ik); !fld.done(); fld.next()) {
1172     if (!fld.access_flags().is_static()) {
1173       Symbol* sig = fld.signature();
1174 
1175       writer->write_symbolID(fld.name());   // name
1176       writer->write_u1(sig2tag(sig));       // type
1177     }
1178   }
1179 }
1180 
1181 // creates HPROF_GC_INSTANCE_DUMP record for the given object
1182 void DumperSupport::dump_instance(AbstractDumpWriter* writer, oop o, DumperClassCacheTable* class_cache) {
1183   InstanceKlass* ik = InstanceKlass::cast(o->klass());
1184 
1185   DumperClassCacheTableEntry* cache_entry = class_cache->lookup_or_create(ik);
1186 
1187   u4 is = instance_size(ik, cache_entry);
1188   u4 size = 1 + sizeof(address) + 4 + sizeof(address) + 4 + is;
1189 
1190   writer->start_sub_record(HPROF_GC_INSTANCE_DUMP, size);
1191   writer->write_objectID(o);
1192   writer->write_u4(STACK_TRACE_ID);
1193 
1194   // class ID
1195   writer->write_classID(ik);
1196 
1197   // number of bytes that follow
1198   writer->write_u4(is);
1199 
1200   // field values
1201   dump_instance_fields(writer, o, cache_entry);
1202 
1203   writer->end_sub_record();
1204 }
1205 
1206 // creates HPROF_GC_CLASS_DUMP record for the given instance class
1207 void DumperSupport::dump_instance_class(AbstractDumpWriter* writer, Klass* k) {
1208   InstanceKlass* ik = InstanceKlass::cast(k);
1209 
1210   // We can safepoint and do a heap dump at a point where we have a Klass,
1211   // but no java mirror class has been setup for it. So we need to check
1212   // that the class is at least loaded, to avoid crash from a null mirror.
1213   if (!ik->is_loaded()) {
1214     return;
1215   }
1216 
1217   u2 static_fields_count = 0;
1218   u4 static_size = get_static_fields_size(ik, static_fields_count);
1219   u2 instance_fields_count = get_instance_fields_count(ik);
1220   u4 instance_fields_size = instance_fields_count * (sizeof(address) + 1);
1221   u4 size = checked_cast<u4>(1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + static_size + 2 + instance_fields_size);
1222 
1223   writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);
1224 
1225   // class ID
1226   writer->write_classID(ik);
1227   writer->write_u4(STACK_TRACE_ID);
1228 
1229   // super class ID
1230   InstanceKlass* java_super = ik->java_super();
1231   if (java_super == nullptr) {
1232     writer->write_objectID(oop(nullptr));
1233   } else {
1234     writer->write_classID(java_super);
1235   }
1236 
1237   writer->write_objectID(ik->class_loader());
1238   writer->write_objectID(ik->signers());
1239   writer->write_objectID(ik->protection_domain());
1240 
1241   // reserved
1242   writer->write_objectID(oop(nullptr));
1243   writer->write_objectID(oop(nullptr));
1244 
1245   // instance size
1246   writer->write_u4(DumperSupport::instance_size(ik));
1247 
1248   // size of constant pool - ignored by HAT 1.1
1249   writer->write_u2(0);
1250 
1251   // static fields
1252   writer->write_u2(static_fields_count);
1253   dump_static_fields(writer, ik);
1254 
1255   // description of instance fields
1256   writer->write_u2(instance_fields_count);
1257   dump_instance_field_descriptors(writer, ik);
1258 
1259   writer->end_sub_record();
1260 }
1261 
1262 // creates HPROF_GC_CLASS_DUMP record for the given array class
1263 void DumperSupport::dump_array_class(AbstractDumpWriter* writer, Klass* k) {
1264   InstanceKlass* ik = nullptr; // bottom class for object arrays, null for primitive type arrays
1265   if (k->is_objArray_klass()) {
1266     Klass *bk = ObjArrayKlass::cast(k)->bottom_klass();
1267     assert(bk != nullptr, "checking");
1268     if (bk->is_instance_klass()) {
1269       ik = InstanceKlass::cast(bk);
1270     }
1271   }
1272 
1273   u4 size = 1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + 2;
1274   writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);
1275   writer->write_classID(k);
1276   writer->write_u4(STACK_TRACE_ID);
1277 
1278   // super class of array classes is java.lang.Object
1279   InstanceKlass* java_super = k->java_super();
1280   assert(java_super != nullptr, "checking");
1281   writer->write_classID(java_super);
1282 
1283   writer->write_objectID(ik == nullptr ? oop(nullptr) : ik->class_loader());
1284   writer->write_objectID(ik == nullptr ? oop(nullptr) : ik->signers());
1285   writer->write_objectID(ik == nullptr ? oop(nullptr) : ik->protection_domain());
1286 
1287   writer->write_objectID(oop(nullptr));    // reserved
1288   writer->write_objectID(oop(nullptr));
1289   writer->write_u4(0);             // instance size
1290   writer->write_u2(0);             // constant pool
1291   writer->write_u2(0);             // static fields
1292   writer->write_u2(0);             // instance fields
1293 
1294   writer->end_sub_record();
1295 
1296 }
1297 
1298 // Hprof uses an u4 as record length field,
1299 // which means we need to truncate arrays that are too long.
1300 int DumperSupport::calculate_array_max_length(AbstractDumpWriter* writer, arrayOop array, short header_size) {
1301   BasicType type = ArrayKlass::cast(array->klass())->element_type();
1302   assert(type >= T_BOOLEAN && type <= T_OBJECT, "invalid array element type");
1303 
1304   int length = array->length();
1305 
1306   int type_size;
1307   if (type == T_OBJECT) {
1308     type_size = sizeof(address);
1309   } else {
1310     type_size = type2aelembytes(type);
1311   }
1312 
1313   size_t length_in_bytes = (size_t)length * type_size;
1314   uint max_bytes = max_juint - header_size;
1315 
1316   if (length_in_bytes > max_bytes) {
1317     length = max_bytes / type_size;
1318     length_in_bytes = (size_t)length * type_size;
1319 
1320     warning("cannot dump array of type %s[] with length %d; truncating to length %d",
1321             type2name_tab[type], array->length(), length);
1322   }
1323   return length;
1324 }
1325 
1326 // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
1327 void DumperSupport::dump_object_array(AbstractDumpWriter* writer, objArrayOop array) {
1328   // sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID) + sizeof(classID)
1329   short header_size = 1 + 2 * 4 + 2 * sizeof(address);
1330   int length = calculate_array_max_length(writer, array, header_size);
1331   u4 size = checked_cast<u4>(header_size + length * sizeof(address));
1332 
1333   writer->start_sub_record(HPROF_GC_OBJ_ARRAY_DUMP, size);
1334   writer->write_objectID(array);
1335   writer->write_u4(STACK_TRACE_ID);
1336   writer->write_u4(length);
1337 
1338   // array class ID
1339   writer->write_classID(array->klass());
1340 
1341   // [id]* elements
1342   for (int index = 0; index < length; index++) {
1343     oop o = array->obj_at(index);
1344     o = mask_dormant_archived_object(o, array);
1345     writer->write_objectID(o);
1346   }
1347 
1348   writer->end_sub_record();
1349 }
1350 
1351 #define WRITE_ARRAY(Array, Type, Size, Length) \
1352   for (int i = 0; i < Length; i++) { writer->write_##Size((Size)Array->Type##_at(i)); }
1353 
1354 // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
1355 void DumperSupport::dump_prim_array(AbstractDumpWriter* writer, typeArrayOop array) {
1356   BasicType type = TypeArrayKlass::cast(array->klass())->element_type();
1357   // 2 * sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID)
1358   short header_size = 2 * 1 + 2 * 4 + sizeof(address);
1359 
1360   int length = calculate_array_max_length(writer, array, header_size);
1361   int type_size = type2aelembytes(type);
1362   u4 length_in_bytes = (u4)length * type_size;
1363   u4 size = header_size + length_in_bytes;
1364 
1365   writer->start_sub_record(HPROF_GC_PRIM_ARRAY_DUMP, size);
1366   writer->write_objectID(array);
1367   writer->write_u4(STACK_TRACE_ID);
1368   writer->write_u4(length);
1369   writer->write_u1(type2tag(type));
1370 
1371   // nothing to copy
1372   if (length == 0) {
1373     writer->end_sub_record();
1374     return;
1375   }
1376 
1377   // If the byte ordering is big endian then we can copy most types directly
1378 
1379   switch (type) {
1380     case T_INT : {
1381       if (Endian::is_Java_byte_ordering_different()) {
1382         WRITE_ARRAY(array, int, u4, length);
1383       } else {
1384         writer->write_raw(array->int_at_addr(0), length_in_bytes);
1385       }
1386       break;
1387     }
1388     case T_BYTE : {
1389       writer->write_raw(array->byte_at_addr(0), length_in_bytes);
1390       break;
1391     }
1392     case T_CHAR : {
1393       if (Endian::is_Java_byte_ordering_different()) {
1394         WRITE_ARRAY(array, char, u2, length);
1395       } else {
1396         writer->write_raw(array->char_at_addr(0), length_in_bytes);
1397       }
1398       break;
1399     }
1400     case T_SHORT : {
1401       if (Endian::is_Java_byte_ordering_different()) {
1402         WRITE_ARRAY(array, short, u2, length);
1403       } else {
1404         writer->write_raw(array->short_at_addr(0), length_in_bytes);
1405       }
1406       break;
1407     }
1408     case T_BOOLEAN : {
1409       if (Endian::is_Java_byte_ordering_different()) {
1410         WRITE_ARRAY(array, bool, u1, length);
1411       } else {
1412         writer->write_raw(array->bool_at_addr(0), length_in_bytes);
1413       }
1414       break;
1415     }
1416     case T_LONG : {
1417       if (Endian::is_Java_byte_ordering_different()) {
1418         WRITE_ARRAY(array, long, u8, length);
1419       } else {
1420         writer->write_raw(array->long_at_addr(0), length_in_bytes);
1421       }
1422       break;
1423     }
1424 
1425     // handle float/doubles in a special value to ensure than NaNs are
1426     // written correctly. TO DO: Check if we can avoid this on processors that
1427     // use IEEE 754.
1428 
1429     case T_FLOAT : {
1430       for (int i = 0; i < length; i++) {
1431         dump_float(writer, array->float_at(i));
1432       }
1433       break;
1434     }
1435     case T_DOUBLE : {
1436       for (int i = 0; i < length; i++) {
1437         dump_double(writer, array->double_at(i));
1438       }
1439       break;
1440     }
1441     default : ShouldNotReachHere();
1442   }
1443 
1444   writer->end_sub_record();
1445 }
1446 
1447 // create a HPROF_FRAME record of the given Method* and bci
1448 void DumperSupport::dump_stack_frame(AbstractDumpWriter* writer,
1449                                      int frame_serial_num,
1450                                      int class_serial_num,
1451                                      Method* m,
1452                                      int bci) {
1453   int line_number;
1454   if (m->is_native()) {
1455     line_number = -3;  // native frame
1456   } else {
1457     line_number = m->line_number_from_bci(bci);
1458   }
1459 
1460   write_header(writer, HPROF_FRAME, 4*oopSize + 2*sizeof(u4));
1461   writer->write_id(frame_serial_num);               // frame serial number
1462   writer->write_symbolID(m->name());                // method's name
1463   writer->write_symbolID(m->signature());           // method's signature
1464 
1465   assert(m->method_holder()->is_instance_klass(), "not InstanceKlass");
1466   writer->write_symbolID(m->method_holder()->source_file_name());  // source file name
1467   writer->write_u4(class_serial_num);               // class serial number
1468   writer->write_u4((u4) line_number);               // line number
1469 }
1470 
1471 
1472 // Support class used to generate HPROF_UTF8 records from the entries in the
1473 // SymbolTable.
1474 
1475 class SymbolTableDumper : public SymbolClosure {
1476  private:
1477   AbstractDumpWriter* _writer;
1478   AbstractDumpWriter* writer() const                { return _writer; }
1479  public:
1480   SymbolTableDumper(AbstractDumpWriter* writer)     { _writer = writer; }
1481   void do_symbol(Symbol** p);
1482 };
1483 
1484 void SymbolTableDumper::do_symbol(Symbol** p) {
1485   ResourceMark rm;
1486   Symbol* sym = *p;
1487   int len = sym->utf8_length();
1488   if (len > 0) {
1489     char* s = sym->as_utf8();
1490     DumperSupport::write_header(writer(), HPROF_UTF8, oopSize + len);
1491     writer()->write_symbolID(sym);
1492     writer()->write_raw(s, len);
1493   }
1494 }
1495 
1496 // Support class used to generate HPROF_GC_CLASS_DUMP records
1497 
1498 class ClassDumper : public KlassClosure {
1499  private:
1500   AbstractDumpWriter* _writer;
1501   AbstractDumpWriter* writer() const { return _writer; }
1502 
1503  public:
1504   ClassDumper(AbstractDumpWriter* writer) : _writer(writer) {}
1505 
1506   void do_klass(Klass* k) {
1507     if (k->is_instance_klass()) {
1508       DumperSupport::dump_instance_class(writer(), k);
1509     } else {
1510       DumperSupport::dump_array_class(writer(), k);
1511     }
1512   }
1513 };
1514 
1515 // Support class used to generate HPROF_LOAD_CLASS records
1516 
1517 class LoadedClassDumper : public LockedClassesDo {
1518  private:
1519   AbstractDumpWriter* _writer;
1520   GrowableArray<Klass*>* _klass_map;
1521   u4 _class_serial_num;
1522   AbstractDumpWriter* writer() const { return _writer; }
1523   void add_class_serial_number(Klass* k, int serial_num) {
1524     _klass_map->at_put_grow(serial_num, k);
1525   }
1526  public:
1527   LoadedClassDumper(AbstractDumpWriter* writer, GrowableArray<Klass*>* klass_map)
1528     : _writer(writer), _klass_map(klass_map), _class_serial_num(0) {}
1529 
1530   void do_klass(Klass* k) {
1531     // len of HPROF_LOAD_CLASS record
1532     u4 remaining = 2 * oopSize + 2 * sizeof(u4);
1533     DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining);
1534     // class serial number is just a number
1535     writer()->write_u4(++_class_serial_num);
1536     // class ID
1537     writer()->write_classID(k);
1538     // add the Klass* and class serial number pair
1539     add_class_serial_number(k, _class_serial_num);
1540     writer()->write_u4(STACK_TRACE_ID);
1541     // class name ID
1542     Symbol* name = k->name();
1543     writer()->write_symbolID(name);
1544   }
1545 };
1546 
1547 // Support class used to generate HPROF_GC_ROOT_JNI_LOCAL records
1548 
1549 class JNILocalsDumper : public OopClosure {
1550  private:
1551   AbstractDumpWriter* _writer;
1552   u4 _thread_serial_num;
1553   int _frame_num;
1554   AbstractDumpWriter* writer() const                { return _writer; }
1555  public:
1556   JNILocalsDumper(AbstractDumpWriter* writer, u4 thread_serial_num) {
1557     _writer = writer;
1558     _thread_serial_num = thread_serial_num;
1559     _frame_num = -1;  // default - empty stack
1560   }
1561   void set_frame_number(int n) { _frame_num = n; }
1562   void do_oop(oop* obj_p);
1563   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1564 };
1565 
1566 void JNILocalsDumper::do_oop(oop* obj_p) {
1567   // ignore null handles
1568   oop o = *obj_p;
1569   if (o != nullptr) {
1570     u4 size = 1 + sizeof(address) + 4 + 4;
1571     writer()->start_sub_record(HPROF_GC_ROOT_JNI_LOCAL, size);
1572     writer()->write_objectID(o);
1573     writer()->write_u4(_thread_serial_num);
1574     writer()->write_u4((u4)_frame_num);
1575     writer()->end_sub_record();
1576   }
1577 }
1578 
1579 
1580 // Support class used to generate HPROF_GC_ROOT_JNI_GLOBAL records
1581 
1582 class JNIGlobalsDumper : public OopClosure {
1583  private:
1584   AbstractDumpWriter* _writer;
1585   AbstractDumpWriter* writer() const                { return _writer; }
1586 
1587  public:
1588   JNIGlobalsDumper(AbstractDumpWriter* writer) {
1589     _writer = writer;
1590   }
1591   void do_oop(oop* obj_p);
1592   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1593 };
1594 
1595 void JNIGlobalsDumper::do_oop(oop* obj_p) {
1596   oop o = NativeAccess<AS_NO_KEEPALIVE>::oop_load(obj_p);
1597 
1598   // ignore these
1599   if (o == nullptr) return;
1600   // we ignore global ref to symbols and other internal objects
1601   if (o->is_instance() || o->is_objArray() || o->is_typeArray()) {
1602     u4 size = 1 + 2 * sizeof(address);
1603     writer()->start_sub_record(HPROF_GC_ROOT_JNI_GLOBAL, size);
1604     writer()->write_objectID(o);
1605     writer()->write_rootID(obj_p);      // global ref ID
1606     writer()->end_sub_record();
1607   }
1608 };
1609 
1610 // Support class used to generate HPROF_GC_ROOT_STICKY_CLASS records
1611 
1612 class StickyClassDumper : public KlassClosure {
1613  private:
1614   AbstractDumpWriter* _writer;
1615   AbstractDumpWriter* writer() const                { return _writer; }
1616  public:
1617   StickyClassDumper(AbstractDumpWriter* writer) {
1618     _writer = writer;
1619   }
1620   void do_klass(Klass* k) {
1621     if (k->is_instance_klass()) {
1622       InstanceKlass* ik = InstanceKlass::cast(k);
1623       u4 size = 1 + sizeof(address);
1624       writer()->start_sub_record(HPROF_GC_ROOT_STICKY_CLASS, size);
1625       writer()->write_classID(ik);
1626       writer()->end_sub_record();
1627     }
1628   }
1629 };
1630 
1631 // Support class used to generate HPROF_GC_ROOT_JAVA_FRAME records.
1632 
1633 class JavaStackRefDumper : public StackObj {
1634 private:
1635   AbstractDumpWriter* _writer;
1636   u4 _thread_serial_num;
1637   int _frame_num;
1638   AbstractDumpWriter* writer() const { return _writer; }
1639 public:
1640   JavaStackRefDumper(AbstractDumpWriter* writer, u4 thread_serial_num)
1641       : _writer(writer), _thread_serial_num(thread_serial_num), _frame_num(-1) // default - empty stack
1642   {
1643   }
1644 
1645   void set_frame_number(int n) { _frame_num = n; }
1646 
1647   void dump_java_stack_refs(StackValueCollection* values);
1648 };
1649 
1650 void JavaStackRefDumper::dump_java_stack_refs(StackValueCollection* values) {
1651   for (int index = 0; index < values->size(); index++) {
1652     if (values->at(index)->type() == T_OBJECT) {
1653       oop o = values->obj_at(index)();
1654       if (o != nullptr) {
1655         u4 size = 1 + sizeof(address) + 4 + 4;
1656         writer()->start_sub_record(HPROF_GC_ROOT_JAVA_FRAME, size);
1657         writer()->write_objectID(o);
1658         writer()->write_u4(_thread_serial_num);
1659         writer()->write_u4((u4)_frame_num);
1660         writer()->end_sub_record();
1661       }
1662     }
1663   }
1664 }
1665 
1666 // Class to collect, store and dump thread-related data:
1667 // - HPROF_TRACE and HPROF_FRAME records;
1668 // - HPROF_GC_ROOT_THREAD_OBJ/HPROF_GC_ROOT_JAVA_FRAME/HPROF_GC_ROOT_JNI_LOCAL subrecords.
1669 class ThreadDumper : public CHeapObj<mtInternal> {
1670 public:
1671   enum class ThreadType { Platform, MountedVirtual, UnmountedVirtual };
1672 
1673 private:
1674   ThreadType _thread_type;
1675   JavaThread* _java_thread;
1676   oop _thread_oop;
1677 
1678   GrowableArray<StackFrameInfo*>* _frames;
1679   // non-null if the thread is OOM thread
1680   Method* _oome_constructor;
1681   int _thread_serial_num;
1682   int _start_frame_serial_num;
1683 
1684   vframe* get_top_frame() const;
1685 
1686 public:
1687   static bool should_dump_pthread(JavaThread* thread) {
1688     return thread->threadObj() != nullptr && !thread->is_exiting() && !thread->is_hidden_from_external_view();
1689   }
1690 
1691   static bool should_dump_vthread(oop vt) {
1692     return java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::NEW
1693         && java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::TERMINATED;
1694   }
1695 
1696   static bool is_vthread_mounted(oop vt) {
1697     // The code should be consistent with the "mounted virtual thread" case
1698     // (VM_HeapDumper::dump_stack_traces(), ThreadDumper::get_top_frame()).
1699     // I.e. virtual thread is mounted if its carrierThread is not null
1700     // and is_vthread_mounted() for the carrier thread returns true.
1701     oop carrier_thread = java_lang_VirtualThread::carrier_thread(vt);
1702     if (carrier_thread == nullptr) {
1703       return false;
1704     }
1705     JavaThread* java_thread = java_lang_Thread::thread(carrier_thread);
1706     return java_thread->is_vthread_mounted();
1707   }
1708 
1709   ThreadDumper(ThreadType thread_type, JavaThread* java_thread, oop thread_oop);
1710 
1711   // affects frame_count
1712   void add_oom_frame(Method* oome_constructor) {
1713     assert(_start_frame_serial_num == 0, "add_oom_frame cannot be called after init_serial_nums");
1714     _oome_constructor = oome_constructor;
1715   }
1716 
1717   void init_serial_nums(volatile int* thread_counter, volatile int* frame_counter) {
1718     assert(_start_frame_serial_num == 0, "already initialized");
1719     _thread_serial_num = Atomic::fetch_then_add(thread_counter, 1);
1720     _start_frame_serial_num = Atomic::fetch_then_add(frame_counter, frame_count());
1721   }
1722 
1723   bool oom_thread() const {
1724     return _oome_constructor != nullptr;
1725   }
1726 
1727   int frame_count() const {
1728     return _frames->length() + (oom_thread() ? 1 : 0);
1729   }
1730 
1731   u4 thread_serial_num() const {
1732     return (u4)_thread_serial_num;
1733   }
1734 
1735   u4 stack_trace_serial_num() const {
1736     return (u4)(_thread_serial_num + STACK_TRACE_ID);
1737   }
1738 
1739   // writes HPROF_TRACE and HPROF_FRAME records
1740   // returns number of dumped frames
1741   void dump_stack_traces(AbstractDumpWriter* writer, GrowableArray<Klass*>* klass_map);
1742 
1743   // writes HPROF_GC_ROOT_THREAD_OBJ subrecord
1744   void dump_thread_obj(AbstractDumpWriter* writer);
1745 
1746   // Walk the stack of the thread.
1747   // Dumps a HPROF_GC_ROOT_JAVA_FRAME subrecord for each local
1748   // Dumps a HPROF_GC_ROOT_JNI_LOCAL subrecord for each JNI local
1749   void dump_stack_refs(AbstractDumpWriter* writer);
1750 
1751 };
1752 
1753 ThreadDumper::ThreadDumper(ThreadType thread_type, JavaThread* java_thread, oop thread_oop)
1754     : _thread_type(thread_type), _java_thread(java_thread), _thread_oop(thread_oop),
1755       _oome_constructor(nullptr),
1756       _thread_serial_num(0), _start_frame_serial_num(0)
1757 {
1758   // sanity checks
1759   if (_thread_type == ThreadType::UnmountedVirtual) {
1760     assert(_java_thread == nullptr, "sanity");
1761     assert(_thread_oop != nullptr, "sanity");
1762   } else {
1763     assert(_java_thread != nullptr, "sanity");
1764     assert(_thread_oop != nullptr, "sanity");
1765   }
1766 
1767   _frames = new (mtServiceability) GrowableArray<StackFrameInfo*>(10, mtServiceability);
1768   bool stop_at_vthread_entry = _thread_type == ThreadType::MountedVirtual;
1769 
1770   // vframes are resource allocated
1771   Thread* current_thread = Thread::current();
1772   ResourceMark rm(current_thread);
1773   HandleMark hm(current_thread);
1774 
1775   for (vframe* vf = get_top_frame(); vf != nullptr; vf = vf->sender()) {
1776     if (stop_at_vthread_entry && vf->is_vthread_entry()) {
1777       break;
1778     }
1779     if (vf->is_java_frame()) {
1780       javaVFrame* jvf = javaVFrame::cast(vf);
1781       _frames->append(new StackFrameInfo(jvf, false));
1782     } else {
1783       // ignore non-Java frames
1784     }
1785   }
1786 }
1787 
1788 void ThreadDumper::dump_stack_traces(AbstractDumpWriter* writer, GrowableArray<Klass*>* klass_map) {
1789   assert(_thread_serial_num != 0 && _start_frame_serial_num != 0, "serial_nums are not initialized");
1790 
1791   // write HPROF_FRAME records for this thread's stack trace
1792   int depth = _frames->length();
1793   int frame_serial_num = _start_frame_serial_num;
1794 
1795   if (oom_thread()) {
1796     // OOM thread
1797     // write fake frame that makes it look like the thread, which caused OOME,
1798     // is in the OutOfMemoryError zero-parameter constructor
1799     int oome_serial_num = klass_map->find(_oome_constructor->method_holder());
1800     // the class serial number starts from 1
1801     assert(oome_serial_num > 0, "OutOfMemoryError class not found");
1802     DumperSupport::dump_stack_frame(writer, ++frame_serial_num, oome_serial_num, _oome_constructor, 0);
1803     depth++;
1804   }
1805 
1806   for (int j = 0; j < _frames->length(); j++) {
1807     StackFrameInfo* frame = _frames->at(j);
1808     Method* m = frame->method();
1809     int class_serial_num = klass_map->find(m->method_holder());
1810     // the class serial number starts from 1
1811     assert(class_serial_num > 0, "class not found");
1812     DumperSupport::dump_stack_frame(writer, ++frame_serial_num, class_serial_num, m, frame->bci());
1813   }
1814 
1815   // write HPROF_TRACE record for the thread
1816   DumperSupport::write_header(writer, HPROF_TRACE, checked_cast<u4>(3 * sizeof(u4) + depth * oopSize));
1817   writer->write_u4(stack_trace_serial_num());   // stack trace serial number
1818   writer->write_u4(thread_serial_num());        // thread serial number
1819   writer->write_u4((u4)depth);                  // frame count (including oom frame)
1820   for (int j = 1; j <= depth; j++) {
1821     writer->write_id(_start_frame_serial_num + j);
1822   }
1823 }
1824 
1825 void ThreadDumper::dump_thread_obj(AbstractDumpWriter * writer) {
1826   assert(_thread_serial_num != 0 && _start_frame_serial_num != 0, "serial_num is not initialized");
1827 
1828   u4 size = 1 + sizeof(address) + 4 + 4;
1829   writer->start_sub_record(HPROF_GC_ROOT_THREAD_OBJ, size);
1830   writer->write_objectID(_thread_oop);
1831   writer->write_u4(thread_serial_num());      // thread serial number
1832   writer->write_u4(stack_trace_serial_num()); // stack trace serial number
1833   writer->end_sub_record();
1834 }
1835 
1836 void ThreadDumper::dump_stack_refs(AbstractDumpWriter * writer) {
1837   assert(_thread_serial_num != 0 && _start_frame_serial_num != 0, "serial_num is not initialized");
1838 
1839   JNILocalsDumper blk(writer, thread_serial_num());
1840   if (_thread_type == ThreadType::Platform) {
1841     if (!_java_thread->has_last_Java_frame()) {
1842       // no last java frame but there may be JNI locals
1843       _java_thread->active_handles()->oops_do(&blk);
1844       return;
1845     }
1846   }
1847 
1848   JavaStackRefDumper java_ref_dumper(writer, thread_serial_num());
1849 
1850   // vframes are resource allocated
1851   Thread* current_thread = Thread::current();
1852   ResourceMark rm(current_thread);
1853   HandleMark hm(current_thread);
1854 
1855   bool stopAtVthreadEntry = _thread_type == ThreadType::MountedVirtual;
1856   frame* last_entry_frame = nullptr;
1857   bool is_top_frame = true;
1858   int depth = 0;
1859   if (oom_thread()) {
1860     depth++;
1861   }
1862 
1863   for (vframe* vf = get_top_frame(); vf != nullptr; vf = vf->sender()) {
1864     if (stopAtVthreadEntry && vf->is_vthread_entry()) {
1865       break;
1866     }
1867 
1868     if (vf->is_java_frame()) {
1869       javaVFrame* jvf = javaVFrame::cast(vf);
1870       if (!(jvf->method()->is_native())) {
1871         java_ref_dumper.set_frame_number(depth);
1872         java_ref_dumper.dump_java_stack_refs(jvf->locals());
1873         java_ref_dumper.dump_java_stack_refs(jvf->expressions());
1874       } else {
1875         // native frame
1876         blk.set_frame_number(depth);
1877         if (is_top_frame) {
1878           // JNI locals for the top frame.
1879           assert(_java_thread != nullptr, "impossible for unmounted vthread");
1880           _java_thread->active_handles()->oops_do(&blk);
1881         } else {
1882           if (last_entry_frame != nullptr) {
1883             // JNI locals for the entry frame
1884             assert(last_entry_frame->is_entry_frame(), "checking");
1885             last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(&blk);
1886           }
1887         }
1888       }
1889       last_entry_frame = nullptr;
1890       // increment only for Java frames
1891       depth++;
1892     } else {
1893       // externalVFrame - for an entry frame then we report the JNI locals
1894       // when we find the corresponding javaVFrame
1895       frame* fr = vf->frame_pointer();
1896       assert(fr != nullptr, "sanity check");
1897       if (fr->is_entry_frame()) {
1898         last_entry_frame = fr;
1899       }
1900     }
1901   is_top_frame = false;
1902   }
1903   assert(depth == frame_count(), "total number of Java frames not matched");
1904 }
1905 
1906 vframe* ThreadDumper::get_top_frame() const {
1907   if (_thread_type == ThreadType::UnmountedVirtual) {
1908     ContinuationWrapper cont(java_lang_VirtualThread::continuation(_thread_oop));
1909     if (cont.is_empty()) {
1910       return nullptr;
1911     }
1912     assert(!cont.is_mounted(), "sanity check");
1913     stackChunkOop chunk = cont.last_nonempty_chunk();
1914     if (chunk == nullptr || chunk->is_empty()) {
1915       return nullptr;
1916     }
1917 
1918     RegisterMap reg_map(cont.continuation(), RegisterMap::UpdateMap::include);
1919     frame fr = chunk->top_frame(&reg_map);
1920     vframe* vf = vframe::new_vframe(&fr, &reg_map, nullptr); // don't need JavaThread
1921     return vf;
1922   }
1923 
1924   RegisterMap reg_map(_java_thread,
1925       RegisterMap::UpdateMap::include,
1926       RegisterMap::ProcessFrames::include,
1927       RegisterMap::WalkContinuation::skip);
1928   switch (_thread_type) {
1929   case ThreadType::Platform:
1930     if (!_java_thread->has_last_Java_frame()) {
1931       return nullptr;
1932     }
1933     return _java_thread->is_vthread_mounted()
1934         ? _java_thread->carrier_last_java_vframe(&reg_map)
1935         : _java_thread->platform_thread_last_java_vframe(&reg_map);
1936 
1937   case ThreadType::MountedVirtual:
1938     return _java_thread->last_java_vframe(&reg_map);
1939 
1940   default: // make compilers happy
1941       break;
1942   }
1943   ShouldNotReachHere();
1944   return nullptr;
1945 }
1946 
1947 // Callback to dump thread-related data for unmounted virtual threads;
1948 // implemented by VM_HeapDumper.
1949 class UnmountedVThreadDumper {
1950  public:
1951   virtual void dump_vthread(oop vt, AbstractDumpWriter* segment_writer) = 0;
1952 };
1953 
1954 // Support class used when iterating over the heap.
1955 class HeapObjectDumper : public ObjectClosure {
1956  private:
1957   AbstractDumpWriter* _writer;
1958   AbstractDumpWriter* writer()                  { return _writer; }
1959   UnmountedVThreadDumper* _vthread_dumper;
1960 
1961   DumperClassCacheTable _class_cache;
1962 
1963  public:
1964   HeapObjectDumper(AbstractDumpWriter* writer, UnmountedVThreadDumper* vthread_dumper)
1965     : _writer(writer), _vthread_dumper(vthread_dumper) {}
1966 
1967   // called for each object in the heap
1968   void do_object(oop o);
1969 };
1970 
1971 void HeapObjectDumper::do_object(oop o) {
1972   // skip classes as these emitted as HPROF_GC_CLASS_DUMP records
1973   if (o->klass() == vmClasses::Class_klass()) {
1974     if (!java_lang_Class::is_primitive(o)) {
1975       return;
1976     }
1977   }
1978 
1979   if (DumperSupport::mask_dormant_archived_object(o, nullptr) == nullptr) {
1980     return;
1981   }
1982 
1983   if (o->is_instance()) {
1984     // create a HPROF_GC_INSTANCE record for each object
1985     DumperSupport::dump_instance(writer(), o, &_class_cache);
1986     // If we encounter an unmounted virtual thread it needs to be dumped explicitly
1987     // (mounted virtual threads are dumped with their carriers).
1988     if (java_lang_VirtualThread::is_instance(o)
1989         && ThreadDumper::should_dump_vthread(o) && !ThreadDumper::is_vthread_mounted(o)) {
1990       _vthread_dumper->dump_vthread(o, writer());
1991     }
1992   } else if (o->is_objArray()) {
1993     // create a HPROF_GC_OBJ_ARRAY_DUMP record for each object array
1994     DumperSupport::dump_object_array(writer(), objArrayOop(o));
1995   } else if (o->is_typeArray()) {
1996     // create a HPROF_GC_PRIM_ARRAY_DUMP record for each type array
1997     DumperSupport::dump_prim_array(writer(), typeArrayOop(o));
1998   }
1999 }
2000 
2001 // The dumper controller for parallel heap dump
2002 class DumperController : public CHeapObj<mtInternal> {
2003  private:
2004    Monitor* _lock;
2005    Mutex* _global_writer_lock;
2006 
2007    const uint   _dumper_number;
2008    uint   _complete_number;
2009 
2010    bool   _started; // VM dumper started and acquired global writer lock
2011 
2012  public:
2013    DumperController(uint number) :
2014      // _lock and _global_writer_lock are used for synchronization between GC worker threads inside safepoint,
2015      // so we lock with _no_safepoint_check_flag.
2016      // signal_start() acquires _lock when global writer is locked,
2017      // its rank must be less than _global_writer_lock rank.
2018      _lock(new (std::nothrow) PaddedMonitor(Mutex::nosafepoint - 1, "DumperController_lock")),
2019      _global_writer_lock(new (std::nothrow) Mutex(Mutex::nosafepoint, "DumpWriter_lock")),
2020      _dumper_number(number),
2021      _complete_number(0),
2022      _started(false)
2023    {}
2024 
2025    ~DumperController() {
2026      delete _lock;
2027      delete _global_writer_lock;
2028    }
2029 
2030    // parallel (non VM) dumpers must wait until VM dumper acquires global writer lock
2031    void wait_for_start_signal() {
2032      MonitorLocker ml(_lock, Mutex::_no_safepoint_check_flag);
2033      while (_started == false) {
2034        ml.wait();
2035      }
2036    }
2037 
2038    void signal_start() {
2039      MonitorLocker ml(_lock, Mutex::_no_safepoint_check_flag);
2040      _started = true;
2041      ml.notify_all();
2042    }
2043 
2044    void lock_global_writer() {
2045      _global_writer_lock->lock_without_safepoint_check();
2046    }
2047 
2048    void unlock_global_writer() {
2049      _global_writer_lock->unlock();
2050    }
2051 
2052    void dumper_complete(DumpWriter* local_writer, DumpWriter* global_writer) {
2053      MonitorLocker ml(_lock, Mutex::_no_safepoint_check_flag);
2054      _complete_number++;
2055      // propagate local error to global if any
2056      if (local_writer->has_error()) {
2057        global_writer->set_error(local_writer->error());
2058      }
2059      ml.notify();
2060    }
2061 
2062    void wait_all_dumpers_complete() {
2063      MonitorLocker ml(_lock, Mutex::_no_safepoint_check_flag);
2064      while (_complete_number != _dumper_number) {
2065         ml.wait();
2066      }
2067    }
2068 };
2069 
2070 // DumpMerger merges separate dump files into a complete one
2071 class DumpMerger : public StackObj {
2072 private:
2073   DumpWriter* _writer;
2074   const char* _path;
2075   bool _has_error;
2076   int _dump_seq;
2077 
2078 private:
2079   void merge_file(const char* path);
2080   void merge_done();
2081   void set_error(const char* msg);
2082 
2083 public:
2084   DumpMerger(const char* path, DumpWriter* writer, int dump_seq) :
2085     _writer(writer),
2086     _path(path),
2087     _has_error(_writer->has_error()),
2088     _dump_seq(dump_seq) {}
2089 
2090   void do_merge();
2091 
2092   // returns path for the parallel DumpWriter (resource allocated)
2093   static char* get_writer_path(const char* base_path, int seq);
2094 
2095 };
2096 
2097 char* DumpMerger::get_writer_path(const char* base_path, int seq) {
2098   // approximate required buffer size
2099   size_t buf_size = strlen(base_path)
2100                     + 2                 // ".p"
2101                     + 10                // number (that's enough for 2^32 parallel dumpers)
2102                     + 1;                // '\0'
2103 
2104   char* path = NEW_RESOURCE_ARRAY(char, buf_size);
2105   memset(path, 0, buf_size);
2106 
2107   os::snprintf(path, buf_size, "%s.p%d", base_path, seq);
2108 
2109   return path;
2110 }
2111 
2112 
2113 void DumpMerger::merge_done() {
2114   // Writes the HPROF_HEAP_DUMP_END record.
2115   if (!_has_error) {
2116     DumperSupport::end_of_dump(_writer);
2117     _writer->flush();
2118   }
2119   _dump_seq = 0; //reset
2120 }
2121 
2122 void DumpMerger::set_error(const char* msg) {
2123   assert(msg != nullptr, "sanity check");
2124   log_error(heapdump)("%s (file: %s)", msg, _path);
2125   _writer->set_error(msg);
2126   _has_error = true;
2127 }
2128 
2129 #ifdef LINUX
2130 // Merge segmented heap files via sendfile, it's more efficient than the
2131 // read+write combination, which would require transferring data to and from
2132 // user space.
2133 void DumpMerger::merge_file(const char* path) {
2134   TraceTime timer("Merge segmented heap file directly", TRACETIME_LOG(Info, heapdump));
2135 
2136   int segment_fd = os::open(path, O_RDONLY, 0);
2137   if (segment_fd == -1) {
2138     set_error("Can not open segmented heap file during merging");
2139     return;
2140   }
2141 
2142   struct stat st;
2143   if (os::stat(path, &st) != 0) {
2144     ::close(segment_fd);
2145     set_error("Can not get segmented heap file size during merging");
2146     return;
2147   }
2148 
2149   // A successful call to sendfile may write fewer bytes than requested; the
2150   // caller should be prepared to retry the call if there were unsent bytes.
2151   jlong offset = 0;
2152   while (offset < st.st_size) {
2153     int ret = os::Linux::sendfile(_writer->get_fd(), segment_fd, &offset, st.st_size);
2154     if (ret == -1) {
2155       ::close(segment_fd);
2156       set_error("Failed to merge segmented heap file");
2157       return;
2158     }
2159   }
2160 
2161   // As sendfile variant does not call the write method of the global writer,
2162   // bytes_written is also incorrect for this variant, we need to explicitly
2163   // accumulate bytes_written for the global writer in this case
2164   julong accum = _writer->bytes_written() + st.st_size;
2165   _writer->set_bytes_written(accum);
2166   ::close(segment_fd);
2167 }
2168 #else
2169 // Generic implementation using read+write
2170 void DumpMerger::merge_file(const char* path) {
2171   TraceTime timer("Merge segmented heap file", TRACETIME_LOG(Info, heapdump));
2172 
2173   fileStream segment_fs(path, "rb");
2174   if (!segment_fs.is_open()) {
2175     set_error("Can not open segmented heap file during merging");
2176     return;
2177   }
2178 
2179   jlong total = 0;
2180   size_t cnt = 0;
2181 
2182   // Use _writer buffer for reading.
2183   while ((cnt = segment_fs.read(_writer->buffer(), 1, _writer->buffer_size())) != 0) {
2184     _writer->set_position(cnt);
2185     _writer->flush();
2186     total += cnt;
2187   }
2188 
2189   if (segment_fs.fileSize() != total) {
2190     set_error("Merged heap dump is incomplete");
2191   }
2192 }
2193 #endif
2194 
2195 void DumpMerger::do_merge() {
2196   TraceTime timer("Merge heap files complete", TRACETIME_LOG(Info, heapdump));
2197 
2198   // Since contents in segmented heap file were already zipped, we don't need to zip
2199   // them again during merging.
2200   AbstractCompressor* saved_compressor = _writer->compressor();
2201   _writer->set_compressor(nullptr);
2202 
2203   // Merge the content of the remaining files into base file. Regardless of whether
2204   // the merge process is successful or not, these segmented files will be deleted.
2205   for (int i = 0; i < _dump_seq; i++) {
2206     ResourceMark rm;
2207     const char* path = get_writer_path(_path, i);
2208     if (!_has_error) {
2209       merge_file(path);
2210     }
2211     // Delete selected segmented heap file nevertheless
2212     if (remove(path) != 0) {
2213       log_info(heapdump)("Removal of segment file (%d) failed (%d)", i, errno);
2214     }
2215   }
2216 
2217   // restore compressor for further use
2218   _writer->set_compressor(saved_compressor);
2219   merge_done();
2220 }
2221 
2222 // The VM operation that performs the heap dump
2223 class VM_HeapDumper : public VM_GC_Operation, public WorkerTask, public UnmountedVThreadDumper {
2224  private:
2225   DumpWriter*             _writer;
2226   JavaThread*             _oome_thread;
2227   Method*                 _oome_constructor;
2228   bool                    _gc_before_heap_dump;
2229   GrowableArray<Klass*>*  _klass_map;
2230 
2231   ThreadDumper**          _thread_dumpers; // platform, carrier and mounted virtual threads
2232   int                     _thread_dumpers_count;
2233   volatile int            _thread_serial_num;
2234   volatile int            _frame_serial_num;
2235 
2236   volatile int            _dump_seq;
2237   // parallel heap dump support
2238   uint                    _num_dumper_threads;
2239   DumperController*       _dumper_controller;
2240   ParallelObjectIterator* _poi;
2241 
2242   // Dumper id of VMDumper thread.
2243   static const int VMDumperId = 0;
2244   // VM dumper dumps both heap and non-heap data, other dumpers dump heap-only data.
2245   static bool is_vm_dumper(int dumper_id) { return dumper_id == VMDumperId; }
2246   // the 1st dumper calling get_next_dumper_id becomes VM dumper
2247   int get_next_dumper_id() {
2248     return Atomic::fetch_then_add(&_dump_seq, 1);
2249   }
2250 
2251   DumpWriter* writer() const { return _writer; }
2252 
2253   bool skip_operation() const;
2254 
2255   // HPROF_GC_ROOT_THREAD_OBJ records for platform and mounted virtual threads
2256   void dump_threads(AbstractDumpWriter* writer);
2257 
2258   bool is_oom_thread(JavaThread* thread) const {
2259     return thread == _oome_thread && _oome_constructor != nullptr;
2260   }
2261 
2262   // HPROF_TRACE and HPROF_FRAME records for platform and mounted virtual threads
2263   void dump_stack_traces(AbstractDumpWriter* writer);
2264 
2265  public:
2266   VM_HeapDumper(DumpWriter* writer, bool gc_before_heap_dump, bool oome, uint num_dump_threads) :
2267     VM_GC_Operation(0 /* total collections,      dummy, ignored */,
2268                     GCCause::_heap_dump /* GC Cause */,
2269                     0 /* total full collections, dummy, ignored */,
2270                     gc_before_heap_dump),
2271     WorkerTask("dump heap") {
2272     _writer = writer;
2273     _gc_before_heap_dump = gc_before_heap_dump;
2274     _klass_map = new (mtServiceability) GrowableArray<Klass*>(INITIAL_CLASS_COUNT, mtServiceability);
2275 
2276     _thread_dumpers = nullptr;
2277     _thread_dumpers_count = 0;
2278     _thread_serial_num = 1;
2279     _frame_serial_num = 1;
2280 
2281     _dump_seq = VMDumperId;
2282     _num_dumper_threads = num_dump_threads;
2283     _dumper_controller = nullptr;
2284     _poi = nullptr;
2285     if (oome) {
2286       assert(!Thread::current()->is_VM_thread(), "Dump from OutOfMemoryError cannot be called by the VMThread");
2287       // get OutOfMemoryError zero-parameter constructor
2288       InstanceKlass* oome_ik = vmClasses::OutOfMemoryError_klass();
2289       _oome_constructor = oome_ik->find_method(vmSymbols::object_initializer_name(),
2290                                                           vmSymbols::void_method_signature());
2291       // get thread throwing OOME when generating the heap dump at OOME
2292       _oome_thread = JavaThread::current();
2293     } else {
2294       _oome_thread = nullptr;
2295       _oome_constructor = nullptr;
2296     }
2297   }
2298 
2299   ~VM_HeapDumper() {
2300     if (_thread_dumpers != nullptr) {
2301       for (int i = 0; i < _thread_dumpers_count; i++) {
2302         delete _thread_dumpers[i];
2303       }
2304       FREE_C_HEAP_ARRAY(ThreadDumper*, _thread_dumpers);
2305     }
2306 
2307     if (_dumper_controller != nullptr) {
2308       delete _dumper_controller;
2309       _dumper_controller = nullptr;
2310     }
2311     delete _klass_map;
2312   }
2313   int dump_seq()           { return _dump_seq; }
2314   bool is_parallel_dump()  { return _num_dumper_threads > 1; }
2315   void prepare_parallel_dump(WorkerThreads* workers);
2316 
2317   VMOp_Type type() const { return VMOp_HeapDumper; }
2318   virtual bool doit_prologue();
2319   void doit();
2320   void work(uint worker_id);
2321 
2322   // UnmountedVThreadDumper implementation
2323   void dump_vthread(oop vt, AbstractDumpWriter* segment_writer);
2324 };
2325 
2326 bool VM_HeapDumper::skip_operation() const {
2327   return false;
2328 }
2329 
2330 // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record
2331 void DumperSupport::end_of_dump(AbstractDumpWriter* writer) {
2332   writer->finish_dump_segment();
2333 
2334   writer->write_u1(HPROF_HEAP_DUMP_END);
2335   writer->write_u4(0);
2336   writer->write_u4(0);
2337 }
2338 
2339 // Write a HPROF_GC_ROOT_THREAD_OBJ record for platform/carrier and mounted virtual threads.
2340 // Then walk the stack so that locals and JNI locals are dumped.
2341 void VM_HeapDumper::dump_threads(AbstractDumpWriter* writer) {
2342   for (int i = 0; i < _thread_dumpers_count; i++) {
2343     _thread_dumpers[i]->dump_thread_obj(writer);
2344     _thread_dumpers[i]->dump_stack_refs(writer);
2345   }
2346 }
2347 
2348 bool VM_HeapDumper::doit_prologue() {
2349   if (_gc_before_heap_dump && UseZGC) {
2350     // ZGC cannot perform a synchronous GC cycle from within the VM thread.
2351     // So ZCollectedHeap::collect_as_vm_thread() is a noop. To respect the
2352     // _gc_before_heap_dump flag a synchronous GC cycle is performed from
2353     // the caller thread in the prologue.
2354     Universe::heap()->collect(GCCause::_heap_dump);
2355   }
2356   return VM_GC_Operation::doit_prologue();
2357 }
2358 
2359 void VM_HeapDumper::prepare_parallel_dump(WorkerThreads* workers) {
2360   uint num_active_workers = workers != nullptr ? workers->active_workers() : 0;
2361   uint num_requested_dump_threads = _num_dumper_threads;
2362   // check if we can dump in parallel based on requested and active threads
2363   if (num_active_workers <= 1 || num_requested_dump_threads <= 1) {
2364     _num_dumper_threads = 1;
2365   } else {
2366     _num_dumper_threads = clamp(num_requested_dump_threads, 2U, num_active_workers);
2367   }
2368   _dumper_controller = new (std::nothrow) DumperController(_num_dumper_threads);
2369   bool can_parallel = _num_dumper_threads > 1;
2370   log_info(heapdump)("Requested dump threads %u, active dump threads %u, "
2371                      "actual dump threads %u, parallelism %s",
2372                      num_requested_dump_threads, num_active_workers,
2373                      _num_dumper_threads, can_parallel ? "true" : "false");
2374 }
2375 
2376 // The VM operation that dumps the heap. The dump consists of the following
2377 // records:
2378 //
2379 //  HPROF_HEADER
2380 //  [HPROF_UTF8]*
2381 //  [HPROF_LOAD_CLASS]*
2382 //  [[HPROF_FRAME]*|HPROF_TRACE]*
2383 //  [HPROF_GC_CLASS_DUMP]*
2384 //  [HPROF_HEAP_DUMP_SEGMENT]*
2385 //  HPROF_HEAP_DUMP_END
2386 //
2387 // The HPROF_TRACE records represent the stack traces where the heap dump
2388 // is generated and a "dummy trace" record which does not include
2389 // any frames. The dummy trace record is used to be referenced as the
2390 // unknown object alloc site.
2391 //
2392 // Each HPROF_HEAP_DUMP_SEGMENT record has a length followed by sub-records.
2393 // To allow the heap dump be generated in a single pass we remember the position
2394 // of the dump length and fix it up after all sub-records have been written.
2395 // To generate the sub-records we iterate over the heap, writing
2396 // HPROF_GC_INSTANCE_DUMP, HPROF_GC_OBJ_ARRAY_DUMP, and HPROF_GC_PRIM_ARRAY_DUMP
2397 // records as we go. Once that is done we write records for some of the GC
2398 // roots.
2399 
2400 void VM_HeapDumper::doit() {
2401 
2402   CollectedHeap* ch = Universe::heap();
2403 
2404   ch->ensure_parsability(false); // must happen, even if collection does
2405                                  // not happen (e.g. due to GCLocker)
2406 
2407   if (_gc_before_heap_dump) {
2408     if (GCLocker::is_active()) {
2409       warning("GC locker is held; pre-heapdump GC was skipped");
2410     } else {
2411       ch->collect_as_vm_thread(GCCause::_heap_dump);
2412     }
2413   }
2414 
2415   WorkerThreads* workers = ch->safepoint_workers();
2416   prepare_parallel_dump(workers);
2417 
2418   if (!is_parallel_dump()) {
2419     work(VMDumperId);
2420   } else {
2421     ParallelObjectIterator poi(_num_dumper_threads);
2422     _poi = &poi;
2423     workers->run_task(this, _num_dumper_threads);
2424     _poi = nullptr;
2425   }
2426 }
2427 
2428 void VM_HeapDumper::work(uint worker_id) {
2429   // VM Dumper works on all non-heap data dumping and part of heap iteration.
2430   int dumper_id = get_next_dumper_id();
2431 
2432   if (is_vm_dumper(dumper_id)) {
2433     // lock global writer, it will be unlocked after VM Dumper finishes with non-heap data
2434     _dumper_controller->lock_global_writer();
2435     _dumper_controller->signal_start();
2436   } else {
2437     _dumper_controller->wait_for_start_signal();
2438   }
2439 
2440   if (is_vm_dumper(dumper_id)) {
2441     TraceTime timer("Dump non-objects", TRACETIME_LOG(Info, heapdump));
2442     // Write the file header - we always use 1.0.2
2443     const char* header = "JAVA PROFILE 1.0.2";
2444 
2445     // header is few bytes long - no chance to overflow int
2446     writer()->write_raw(header, strlen(header) + 1); // NUL terminated
2447     writer()->write_u4(oopSize);
2448     // timestamp is current time in ms
2449     writer()->write_u8(os::javaTimeMillis());
2450     // HPROF_UTF8 records
2451     SymbolTableDumper sym_dumper(writer());
2452     SymbolTable::symbols_do(&sym_dumper);
2453 
2454     // write HPROF_LOAD_CLASS records
2455     {
2456       LoadedClassDumper loaded_class_dumper(writer(), _klass_map);
2457       ClassLoaderDataGraph::classes_do(&loaded_class_dumper);
2458     }
2459 
2460     // write HPROF_FRAME and HPROF_TRACE records
2461     // this must be called after _klass_map is built when iterating the classes above.
2462     dump_stack_traces(writer());
2463 
2464     // unlock global writer, so parallel dumpers can dump stack traces of unmounted virtual threads
2465     _dumper_controller->unlock_global_writer();
2466   }
2467 
2468   // HPROF_HEAP_DUMP/HPROF_HEAP_DUMP_SEGMENT starts here
2469 
2470   ResourceMark rm;
2471   // share global compressor, local DumpWriter is not responsible for its life cycle
2472   DumpWriter segment_writer(DumpMerger::get_writer_path(writer()->get_file_path(), dumper_id),
2473                             writer()->is_overwrite(), writer()->compressor());
2474   if (!segment_writer.has_error()) {
2475     if (is_vm_dumper(dumper_id)) {
2476       // dump some non-heap subrecords to heap dump segment
2477       TraceTime timer("Dump non-objects (part 2)", TRACETIME_LOG(Info, heapdump));
2478       // Writes HPROF_GC_CLASS_DUMP records
2479       ClassDumper class_dumper(&segment_writer);
2480       ClassLoaderDataGraph::classes_do(&class_dumper);
2481 
2482       // HPROF_GC_ROOT_THREAD_OBJ + frames + jni locals
2483       dump_threads(&segment_writer);
2484 
2485       // HPROF_GC_ROOT_JNI_GLOBAL
2486       JNIGlobalsDumper jni_dumper(&segment_writer);
2487       JNIHandles::oops_do(&jni_dumper);
2488       // technically not jni roots, but global roots
2489       // for things like preallocated throwable backtraces
2490       Universe::vm_global()->oops_do(&jni_dumper);
2491       // HPROF_GC_ROOT_STICKY_CLASS
2492       // These should be classes in the null class loader data, and not all classes
2493       // if !ClassUnloading
2494       StickyClassDumper stiky_class_dumper(&segment_writer);
2495       ClassLoaderData::the_null_class_loader_data()->classes_do(&stiky_class_dumper);
2496     }
2497 
2498     // Heap iteration.
2499     // writes HPROF_GC_INSTANCE_DUMP records.
2500     // After each sub-record is written check_segment_length will be invoked
2501     // to check if the current segment exceeds a threshold. If so, a new
2502     // segment is started.
2503     // The HPROF_GC_CLASS_DUMP and HPROF_GC_INSTANCE_DUMP are the vast bulk
2504     // of the heap dump.
2505 
2506     TraceTime timer(is_parallel_dump() ? "Dump heap objects in parallel" : "Dump heap objects", TRACETIME_LOG(Info, heapdump));
2507     HeapObjectDumper obj_dumper(&segment_writer, this);
2508     if (!is_parallel_dump()) {
2509       Universe::heap()->object_iterate(&obj_dumper);
2510     } else {
2511       // == Parallel dump
2512       _poi->object_iterate(&obj_dumper, worker_id);
2513     }
2514 
2515     segment_writer.finish_dump_segment();
2516     segment_writer.flush();
2517   }
2518 
2519   _dumper_controller->dumper_complete(&segment_writer, writer());
2520 
2521   if (is_vm_dumper(dumper_id)) {
2522     _dumper_controller->wait_all_dumpers_complete();
2523 
2524     // flush global writer
2525     writer()->flush();
2526 
2527     // At this point, all fragments of the heapdump have been written to separate files.
2528     // We need to merge them into a complete heapdump and write HPROF_HEAP_DUMP_END at that time.
2529   }
2530 }
2531 
2532 void VM_HeapDumper::dump_stack_traces(AbstractDumpWriter* writer) {
2533   // write a HPROF_TRACE record without any frames to be referenced as object alloc sites
2534   DumperSupport::write_header(writer, HPROF_TRACE, 3 * sizeof(u4));
2535   writer->write_u4((u4)STACK_TRACE_ID);
2536   writer->write_u4(0);                    // thread number
2537   writer->write_u4(0);                    // frame count
2538 
2539   // max number if every platform thread is carrier with mounted virtual thread
2540   _thread_dumpers = NEW_C_HEAP_ARRAY(ThreadDumper*, Threads::number_of_threads() * 2, mtInternal);
2541 
2542   for (JavaThreadIteratorWithHandle jtiwh; JavaThread * thread = jtiwh.next(); ) {
2543     if (ThreadDumper::should_dump_pthread(thread)) {
2544       bool add_oom_frame = is_oom_thread(thread);
2545 
2546       oop mounted_vt = thread->is_vthread_mounted() ? thread->vthread() : nullptr;
2547       if (mounted_vt != nullptr && !ThreadDumper::should_dump_vthread(mounted_vt)) {
2548         mounted_vt = nullptr;
2549       }
2550 
2551       // mounted vthread (if any)
2552       if (mounted_vt != nullptr) {
2553         ThreadDumper* thread_dumper = new ThreadDumper(ThreadDumper::ThreadType::MountedVirtual, thread, mounted_vt);
2554         _thread_dumpers[_thread_dumpers_count++] = thread_dumper;
2555         if (add_oom_frame) {
2556           thread_dumper->add_oom_frame(_oome_constructor);
2557           // we add oom frame to the VT stack, don't add it to the carrier thread stack
2558           add_oom_frame = false;
2559         }
2560         thread_dumper->init_serial_nums(&_thread_serial_num, &_frame_serial_num);
2561         thread_dumper->dump_stack_traces(writer, _klass_map);
2562       }
2563 
2564       // platform or carrier thread
2565       ThreadDumper* thread_dumper = new ThreadDumper(ThreadDumper::ThreadType::Platform, thread, thread->threadObj());
2566       _thread_dumpers[_thread_dumpers_count++] = thread_dumper;
2567       if (add_oom_frame) {
2568         thread_dumper->add_oom_frame(_oome_constructor);
2569       }
2570       thread_dumper->init_serial_nums(&_thread_serial_num, &_frame_serial_num);
2571       thread_dumper->dump_stack_traces(writer, _klass_map);
2572     }
2573   }
2574 }
2575 
2576 void VM_HeapDumper::dump_vthread(oop vt, AbstractDumpWriter* segment_writer) {
2577   // unmounted vthread has no JavaThread
2578   ThreadDumper thread_dumper(ThreadDumper::ThreadType::UnmountedVirtual, nullptr, vt);
2579   thread_dumper.init_serial_nums(&_thread_serial_num, &_frame_serial_num);
2580 
2581   // write HPROF_TRACE/HPROF_FRAME records to global writer
2582   _dumper_controller->lock_global_writer();
2583   thread_dumper.dump_stack_traces(writer(), _klass_map);
2584   _dumper_controller->unlock_global_writer();
2585 
2586   // write HPROF_GC_ROOT_THREAD_OBJ/HPROF_GC_ROOT_JAVA_FRAME/HPROF_GC_ROOT_JNI_LOCAL subrecord
2587   // to segment writer
2588   thread_dumper.dump_thread_obj(segment_writer);
2589   thread_dumper.dump_stack_refs(segment_writer);
2590 }
2591 
2592 // dump the heap to given path.
2593 int HeapDumper::dump(const char* path, outputStream* out, int compression, bool overwrite, uint num_dump_threads) {
2594   assert(path != nullptr && strlen(path) > 0, "path missing");
2595 
2596   // print message in interactive case
2597   if (out != nullptr) {
2598     out->print_cr("Dumping heap to %s ...", path);
2599     timer()->start();
2600   }
2601 
2602   if (_oome && num_dump_threads > 1) {
2603     // Each additional parallel writer requires several MB of internal memory
2604     // (DumpWriter buffer, DumperClassCacheTable, GZipCompressor buffers).
2605     // For the OOM handling we may already be limited in memory.
2606     // Lets ensure we have at least 20MB per thread.
2607     julong max_threads = os::free_memory() / (20 * M);
2608     if (num_dump_threads > max_threads) {
2609       num_dump_threads = MAX2<uint>(1, (uint)max_threads);
2610     }
2611   }
2612 
2613   // create JFR event
2614   EventHeapDump event;
2615 
2616   AbstractCompressor* compressor = nullptr;
2617 
2618   if (compression > 0) {
2619     compressor = new (std::nothrow) GZipCompressor(compression);
2620 
2621     if (compressor == nullptr) {
2622       set_error("Could not allocate gzip compressor");
2623       return -1;
2624     }
2625   }
2626 
2627   DumpWriter writer(path, overwrite, compressor);
2628 
2629   if (writer.error() != nullptr) {
2630     set_error(writer.error());
2631     if (out != nullptr) {
2632       out->print_cr("Unable to create %s: %s", path,
2633         (error() != nullptr) ? error() : "reason unknown");
2634     }
2635     return -1;
2636   }
2637 
2638   // generate the segmented heap dump into separate files
2639   VM_HeapDumper dumper(&writer, _gc_before_heap_dump, _oome, num_dump_threads);
2640   VMThread::execute(&dumper);
2641 
2642   // record any error that the writer may have encountered
2643   set_error(writer.error());
2644 
2645   // Heap dump process is done in two phases
2646   //
2647   // Phase 1: Concurrent threads directly write heap data to multiple heap files.
2648   //          This is done by VM_HeapDumper, which is performed within safepoint.
2649   //
2650   // Phase 2: Merge multiple heap files into one complete heap dump file.
2651   //          This is done by DumpMerger, which is performed outside safepoint
2652 
2653   DumpMerger merger(path, &writer, dumper.dump_seq());
2654   // Perform heapdump file merge operation in the current thread prevents us
2655   // from occupying the VM Thread, which in turn affects the occurrence of
2656   // GC and other VM operations.
2657   merger.do_merge();
2658   if (writer.error() != nullptr) {
2659     set_error(writer.error());
2660   }
2661 
2662   // emit JFR event
2663   if (error() == nullptr) {
2664     event.set_destination(path);
2665     event.set_gcBeforeDump(_gc_before_heap_dump);
2666     event.set_size(writer.bytes_written());
2667     event.set_onOutOfMemoryError(_oome);
2668     event.set_overwrite(overwrite);
2669     event.set_compression(compression);
2670     event.commit();
2671   } else {
2672     log_debug(cds, heap)("Error %s while dumping heap", error());
2673   }
2674 
2675   // print message in interactive case
2676   if (out != nullptr) {
2677     timer()->stop();
2678     if (error() == nullptr) {
2679       out->print_cr("Heap dump file created [" JULONG_FORMAT " bytes in %3.3f secs]",
2680                     writer.bytes_written(), timer()->seconds());
2681     } else {
2682       out->print_cr("Dump file is incomplete: %s", writer.error());
2683     }
2684   }
2685 
2686   if (compressor != nullptr) {
2687     delete compressor;
2688   }
2689   return (writer.error() == nullptr) ? 0 : -1;
2690 }
2691 
2692 // stop timer (if still active), and free any error string we might be holding
2693 HeapDumper::~HeapDumper() {
2694   if (timer()->is_active()) {
2695     timer()->stop();
2696   }
2697   set_error(nullptr);
2698 }
2699 
2700 
2701 // returns the error string (resource allocated), or null
2702 char* HeapDumper::error_as_C_string() const {
2703   if (error() != nullptr) {
2704     char* str = NEW_RESOURCE_ARRAY(char, strlen(error())+1);
2705     strcpy(str, error());
2706     return str;
2707   } else {
2708     return nullptr;
2709   }
2710 }
2711 
2712 // set the error string
2713 void HeapDumper::set_error(char const* error) {
2714   if (_error != nullptr) {
2715     os::free(_error);
2716   }
2717   if (error == nullptr) {
2718     _error = nullptr;
2719   } else {
2720     _error = os::strdup(error);
2721     assert(_error != nullptr, "allocation failure");
2722   }
2723 }
2724 
2725 // Called by out-of-memory error reporting by a single Java thread
2726 // outside of a JVM safepoint
2727 void HeapDumper::dump_heap_from_oome() {
2728   HeapDumper::dump_heap(true);
2729 }
2730 
2731 // Called by error reporting by a single Java thread outside of a JVM safepoint,
2732 // or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various
2733 // callers are strictly serialized and guaranteed not to interfere below. For more
2734 // general use, however, this method will need modification to prevent
2735 // inteference when updating the static variables base_path and dump_file_seq below.
2736 void HeapDumper::dump_heap() {
2737   HeapDumper::dump_heap(false);
2738 }
2739 
2740 void HeapDumper::dump_heap(bool oome) {
2741   static char base_path[JVM_MAXPATHLEN] = {'\0'};
2742   static uint dump_file_seq = 0;
2743   char* my_path;
2744   const int max_digit_chars = 20;
2745 
2746   const char* dump_file_name = "java_pid";
2747   const char* dump_file_ext  = HeapDumpGzipLevel > 0 ? ".hprof.gz" : ".hprof";
2748 
2749   // The dump file defaults to java_pid<pid>.hprof in the current working
2750   // directory. HeapDumpPath=<file> can be used to specify an alternative
2751   // dump file name or a directory where dump file is created.
2752   if (dump_file_seq == 0) { // first time in, we initialize base_path
2753     // Calculate potentially longest base path and check if we have enough
2754     // allocated statically.
2755     const size_t total_length =
2756                       (HeapDumpPath == nullptr ? 0 : strlen(HeapDumpPath)) +
2757                       strlen(os::file_separator()) + max_digit_chars +
2758                       strlen(dump_file_name) + strlen(dump_file_ext) + 1;
2759     if (total_length > sizeof(base_path)) {
2760       warning("Cannot create heap dump file.  HeapDumpPath is too long.");
2761       return;
2762     }
2763 
2764     bool use_default_filename = true;
2765     if (HeapDumpPath == nullptr || HeapDumpPath[0] == '\0') {
2766       // HeapDumpPath=<file> not specified
2767     } else {
2768       strcpy(base_path, HeapDumpPath);
2769       // check if the path is a directory (must exist)
2770       DIR* dir = os::opendir(base_path);
2771       if (dir == nullptr) {
2772         use_default_filename = false;
2773       } else {
2774         // HeapDumpPath specified a directory. We append a file separator
2775         // (if needed).
2776         os::closedir(dir);
2777         size_t fs_len = strlen(os::file_separator());
2778         if (strlen(base_path) >= fs_len) {
2779           char* end = base_path;
2780           end += (strlen(base_path) - fs_len);
2781           if (strcmp(end, os::file_separator()) != 0) {
2782             strcat(base_path, os::file_separator());
2783           }
2784         }
2785       }
2786     }
2787     // If HeapDumpPath wasn't a file name then we append the default name
2788     if (use_default_filename) {
2789       const size_t dlen = strlen(base_path);  // if heap dump dir specified
2790       jio_snprintf(&base_path[dlen], sizeof(base_path)-dlen, "%s%d%s",
2791                    dump_file_name, os::current_process_id(), dump_file_ext);
2792     }
2793     const size_t len = strlen(base_path) + 1;
2794     my_path = (char*)os::malloc(len, mtInternal);
2795     if (my_path == nullptr) {
2796       warning("Cannot create heap dump file.  Out of system memory.");
2797       return;
2798     }
2799     strncpy(my_path, base_path, len);
2800   } else {
2801     // Append a sequence number id for dumps following the first
2802     const size_t len = strlen(base_path) + max_digit_chars + 2; // for '.' and \0
2803     my_path = (char*)os::malloc(len, mtInternal);
2804     if (my_path == nullptr) {
2805       warning("Cannot create heap dump file.  Out of system memory.");
2806       return;
2807     }
2808     jio_snprintf(my_path, len, "%s.%d", base_path, dump_file_seq);
2809   }
2810   dump_file_seq++;   // increment seq number for next time we dump
2811 
2812   HeapDumper dumper(false /* no GC before heap dump */,
2813                     oome  /* pass along out-of-memory-error flag */);
2814   dumper.dump(my_path, tty, HeapDumpGzipLevel);
2815   os::free(my_path);
2816 }