1 /*
   2  * Copyright (c) 2005, 2023, 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   void set_bytes_written(julong bytes_written) { _bytes_written = bytes_written; }
 630   char const* error() const override           { return _error; }
 631   void set_error(const char* error)            { _error = (char*)error; }
 632   bool has_error() const                       { return _error != nullptr; }
 633   const char* get_file_path() const            { return _writer->get_file_path(); }
 634   AbstractCompressor* compressor()             { return _compressor; }
 635   void set_compressor(AbstractCompressor* p)   { _compressor = p; }
 636   bool is_overwrite() const                    { return _writer->is_overwrite(); }
 637   int get_fd() const                           { return _writer->get_fd(); }
 638 
 639   void flush() override;
 640 };
 641 
 642 DumpWriter::DumpWriter(const char* path, bool overwrite, AbstractCompressor* compressor) :
 643   AbstractDumpWriter(),
 644   _writer(new (std::nothrow) FileWriter(path, overwrite)),
 645   _compressor(compressor),
 646   _bytes_written(0),
 647   _error(nullptr),
 648   _out_buffer(nullptr),
 649   _out_size(0),
 650   _out_pos(0),
 651   _tmp_buffer(nullptr),
 652   _tmp_size(0) {
 653   _error = (char*)_writer->open_writer();
 654   if (_error == nullptr) {
 655     _buffer = (char*)os::malloc(io_buffer_max_size, mtInternal);
 656     if (compressor != nullptr) {
 657       _error = (char*)_compressor->init(io_buffer_max_size, &_out_size, &_tmp_size);
 658       if (_error == nullptr) {
 659         if (_out_size > 0) {
 660           _out_buffer = (char*)os::malloc(_out_size, mtInternal);
 661         }
 662         if (_tmp_size > 0) {
 663           _tmp_buffer = (char*)os::malloc(_tmp_size, mtInternal);
 664         }
 665       }
 666     }
 667   }
 668   // initialize internal buffer
 669   _pos = 0;
 670   _size = io_buffer_max_size;
 671 }
 672 
 673 DumpWriter::~DumpWriter(){
 674   if (_buffer != nullptr) {
 675     os::free(_buffer);
 676   }
 677   if (_out_buffer != nullptr) {
 678     os::free(_out_buffer);
 679   }
 680   if (_tmp_buffer != nullptr) {
 681     os::free(_tmp_buffer);
 682   }
 683   if (_writer != NULL) {
 684     delete _writer;
 685   }
 686   _bytes_written = -1;
 687 }
 688 
 689 // flush any buffered bytes to the file
 690 void DumpWriter::flush() {
 691   if (_pos <= 0) {
 692     return;
 693   }
 694   if (has_error()) {
 695     _pos = 0;
 696     return;
 697   }
 698   char* result = nullptr;
 699   if (_compressor == nullptr) {
 700     result = (char*)_writer->write_buf(_buffer, _pos);
 701     _bytes_written += _pos;
 702   } else {
 703     do_compress();
 704     if (!has_error()) {
 705       result = (char*)_writer->write_buf(_out_buffer, _out_pos);
 706       _bytes_written += _out_pos;
 707     }
 708   }
 709   _pos = 0; // reset pos to make internal buffer available
 710 
 711   if (result != nullptr) {
 712     set_error(result);
 713   }
 714 }
 715 
 716 void DumpWriter::do_compress() {
 717   const char* msg = _compressor->compress(_buffer, _pos, _out_buffer, _out_size,
 718                                           _tmp_buffer, _tmp_size, &_out_pos);
 719 
 720   if (msg != nullptr) {
 721     set_error(msg);
 722   }
 723 }
 724 
 725 class DumperClassCacheTable;
 726 class DumperClassCacheTableEntry;
 727 
 728 // Support class with a collection of functions used when dumping the heap
 729 class DumperSupport : AllStatic {
 730  public:
 731 
 732   // write a header of the given type
 733   static void write_header(AbstractDumpWriter* writer, hprofTag tag, u4 len);
 734 
 735   // returns hprof tag for the given type signature
 736   static hprofTag sig2tag(Symbol* sig);
 737   // returns hprof tag for the given basic type
 738   static hprofTag type2tag(BasicType type);
 739   // Returns the size of the data to write.
 740   static u4 sig2size(Symbol* sig);
 741 
 742   // returns the size of the instance of the given class
 743   static u4 instance_size(InstanceKlass* ik, DumperClassCacheTableEntry* class_cache_entry = nullptr);
 744 
 745   // dump a jfloat
 746   static void dump_float(AbstractDumpWriter* writer, jfloat f);
 747   // dump a jdouble
 748   static void dump_double(AbstractDumpWriter* writer, jdouble d);
 749   // dumps the raw value of the given field
 750   static void dump_field_value(AbstractDumpWriter* writer, char type, oop obj, int offset);
 751   // returns the size of the static fields; also counts the static fields
 752   static u4 get_static_fields_size(InstanceKlass* ik, u2& field_count);
 753   // dumps static fields of the given class
 754   static void dump_static_fields(AbstractDumpWriter* writer, Klass* k);
 755   // dump the raw values of the instance fields of the given object
 756   static void dump_instance_fields(AbstractDumpWriter* writer, oop o, DumperClassCacheTableEntry* class_cache_entry);
 757   // get the count of the instance fields for a given class
 758   static u2 get_instance_fields_count(InstanceKlass* ik);
 759   // dumps the definition of the instance fields for a given class
 760   static void dump_instance_field_descriptors(AbstractDumpWriter* writer, Klass* k);
 761   // creates HPROF_GC_INSTANCE_DUMP record for the given object
 762   static void dump_instance(AbstractDumpWriter* writer, oop o, DumperClassCacheTable* class_cache);
 763   // creates HPROF_GC_CLASS_DUMP record for the given instance class
 764   static void dump_instance_class(AbstractDumpWriter* writer, Klass* k);
 765   // creates HPROF_GC_CLASS_DUMP record for a given array class
 766   static void dump_array_class(AbstractDumpWriter* writer, Klass* k);
 767 
 768   // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
 769   static void dump_object_array(AbstractDumpWriter* writer, objArrayOop array);
 770   // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
 771   static void dump_prim_array(AbstractDumpWriter* writer, typeArrayOop array);
 772   // create HPROF_FRAME record for the given method and bci
 773   static void dump_stack_frame(AbstractDumpWriter* writer, int frame_serial_num, int class_serial_num, Method* m, int bci);
 774 
 775   // check if we need to truncate an array
 776   static int calculate_array_max_length(AbstractDumpWriter* writer, arrayOop array, short header_size);
 777 
 778   // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record
 779   static void end_of_dump(AbstractDumpWriter* writer);
 780 
 781   static oop mask_dormant_archived_object(oop o) {
 782     if (o != nullptr && o->klass()->java_mirror() == nullptr) {
 783       // Ignore this object since the corresponding java mirror is not loaded.
 784       // Might be a dormant archive object.
 785       return nullptr;
 786     } else {
 787       return o;
 788     }
 789   }
 790 };
 791 
 792 // Hash table of klasses to the klass metadata. This should greatly improve the
 793 // hash dumping performance. This hash table is supposed to be used by a single
 794 // thread only.
 795 //
 796 class DumperClassCacheTableEntry : public CHeapObj<mtServiceability> {
 797   friend class DumperClassCacheTable;
 798 private:
 799   GrowableArray<char> _sigs_start;
 800   GrowableArray<int> _offsets;
 801   u4 _instance_size;
 802   int _entries;
 803 
 804 public:
 805   DumperClassCacheTableEntry() : _instance_size(0), _entries(0) {};
 806 
 807   int field_count()             { return _entries; }
 808   char sig_start(int field_idx) { return _sigs_start.at(field_idx); }
 809   int offset(int field_idx)     { return _offsets.at(field_idx); }
 810   u4 instance_size()            { return _instance_size; }
 811 };
 812 
 813 class DumperClassCacheTable {
 814 private:
 815   // ResourceHashtable SIZE is specified at compile time so we
 816   // use 1031 which is the first prime after 1024.
 817   static constexpr size_t TABLE_SIZE = 1031;
 818 
 819   // Maintain the cache for N classes. This limits memory footprint
 820   // impact, regardless of how many classes we have in the dump.
 821   // This also improves look up performance by keeping the statically
 822   // sized table from overloading.
 823   static constexpr int CACHE_TOP = 256;
 824 
 825   typedef ResourceHashtable<InstanceKlass*, DumperClassCacheTableEntry*,
 826                             TABLE_SIZE, AnyObj::C_HEAP, mtServiceability> PtrTable;
 827   PtrTable* _ptrs;
 828 
 829   // Single-slot cache to handle the major case of objects of the same
 830   // class back-to-back, e.g. from T[].
 831   InstanceKlass* _last_ik;
 832   DumperClassCacheTableEntry* _last_entry;
 833 
 834   void unlink_all(PtrTable* table) {
 835     class CleanupEntry: StackObj {
 836     public:
 837       bool do_entry(InstanceKlass*& key, DumperClassCacheTableEntry*& entry) {
 838         delete entry;
 839         return true;
 840       }
 841     } cleanup;
 842     table->unlink(&cleanup);
 843   }
 844 
 845 public:
 846   DumperClassCacheTableEntry* lookup_or_create(InstanceKlass* ik) {
 847     if (_last_ik == ik) {
 848       return _last_entry;
 849     }
 850 
 851     DumperClassCacheTableEntry* entry;
 852     DumperClassCacheTableEntry** from_cache = _ptrs->get(ik);
 853     if (from_cache == nullptr) {
 854       entry = new DumperClassCacheTableEntry();
 855       for (HierarchicalFieldStream<JavaFieldStream> fld(ik); !fld.done(); fld.next()) {
 856         if (!fld.access_flags().is_static()) {
 857           Symbol* sig = fld.signature();
 858           entry->_sigs_start.push(sig->char_at(0));
 859           entry->_offsets.push(fld.offset());
 860           entry->_entries++;
 861           entry->_instance_size += DumperSupport::sig2size(sig);
 862         }
 863       }
 864 
 865       if (_ptrs->number_of_entries() >= CACHE_TOP) {
 866         // We do not track the individual hit rates for table entries.
 867         // Purge the entire table, and let the cache catch up with new
 868         // distribution.
 869         unlink_all(_ptrs);
 870       }
 871 
 872       _ptrs->put(ik, entry);
 873     } else {
 874       entry = *from_cache;
 875     }
 876 
 877     // Remember for single-slot cache.
 878     _last_ik = ik;
 879     _last_entry = entry;
 880 
 881     return entry;
 882   }
 883 
 884   DumperClassCacheTable() : _ptrs(new (mtServiceability) PtrTable), _last_ik(nullptr), _last_entry(nullptr) {}
 885 
 886   ~DumperClassCacheTable() {
 887     unlink_all(_ptrs);
 888     delete _ptrs;
 889   }
 890 };
 891 
 892 // write a header of the given type
 893 void DumperSupport:: write_header(AbstractDumpWriter* writer, hprofTag tag, u4 len) {
 894   writer->write_u1(tag);
 895   writer->write_u4(0);                  // current ticks
 896   writer->write_u4(len);
 897 }
 898 
 899 // returns hprof tag for the given type signature
 900 hprofTag DumperSupport::sig2tag(Symbol* sig) {
 901   switch (sig->char_at(0)) {
 902     case JVM_SIGNATURE_CLASS    : return HPROF_NORMAL_OBJECT;
 903     case JVM_SIGNATURE_ARRAY    : return HPROF_NORMAL_OBJECT;
 904     case JVM_SIGNATURE_BYTE     : return HPROF_BYTE;
 905     case JVM_SIGNATURE_CHAR     : return HPROF_CHAR;
 906     case JVM_SIGNATURE_FLOAT    : return HPROF_FLOAT;
 907     case JVM_SIGNATURE_DOUBLE   : return HPROF_DOUBLE;
 908     case JVM_SIGNATURE_INT      : return HPROF_INT;
 909     case JVM_SIGNATURE_LONG     : return HPROF_LONG;
 910     case JVM_SIGNATURE_SHORT    : return HPROF_SHORT;
 911     case JVM_SIGNATURE_BOOLEAN  : return HPROF_BOOLEAN;
 912     default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
 913   }
 914 }
 915 
 916 hprofTag DumperSupport::type2tag(BasicType type) {
 917   switch (type) {
 918     case T_BYTE     : return HPROF_BYTE;
 919     case T_CHAR     : return HPROF_CHAR;
 920     case T_FLOAT    : return HPROF_FLOAT;
 921     case T_DOUBLE   : return HPROF_DOUBLE;
 922     case T_INT      : return HPROF_INT;
 923     case T_LONG     : return HPROF_LONG;
 924     case T_SHORT    : return HPROF_SHORT;
 925     case T_BOOLEAN  : return HPROF_BOOLEAN;
 926     default : ShouldNotReachHere(); /* to shut up compiler */ return HPROF_BYTE;
 927   }
 928 }
 929 
 930 u4 DumperSupport::sig2size(Symbol* sig) {
 931   switch (sig->char_at(0)) {
 932     case JVM_SIGNATURE_CLASS:
 933     case JVM_SIGNATURE_ARRAY: return sizeof(address);
 934     case JVM_SIGNATURE_BOOLEAN:
 935     case JVM_SIGNATURE_BYTE: return 1;
 936     case JVM_SIGNATURE_SHORT:
 937     case JVM_SIGNATURE_CHAR: return 2;
 938     case JVM_SIGNATURE_INT:
 939     case JVM_SIGNATURE_FLOAT: return 4;
 940     case JVM_SIGNATURE_LONG:
 941     case JVM_SIGNATURE_DOUBLE: return 8;
 942     default: ShouldNotReachHere(); /* to shut up compiler */ return 0;
 943   }
 944 }
 945 
 946 template<typename T, typename F> T bit_cast(F from) { // replace with the real thing when we can use c++20
 947   T to;
 948   static_assert(sizeof(to) == sizeof(from), "must be of the same size");
 949   memcpy(&to, &from, sizeof(to));
 950   return to;
 951 }
 952 
 953 // dump a jfloat
 954 void DumperSupport::dump_float(AbstractDumpWriter* writer, jfloat f) {
 955   if (g_isnan(f)) {
 956     writer->write_u4(0x7fc00000); // collapsing NaNs
 957   } else {
 958     writer->write_u4(bit_cast<u4>(f));
 959   }
 960 }
 961 
 962 // dump a jdouble
 963 void DumperSupport::dump_double(AbstractDumpWriter* writer, jdouble d) {
 964   if (g_isnan(d)) {
 965     writer->write_u8(0x7ff80000ull << 32); // collapsing NaNs
 966   } else {
 967     writer->write_u8(bit_cast<u8>(d));
 968   }
 969 }
 970 
 971 // dumps the raw value of the given field
 972 void DumperSupport::dump_field_value(AbstractDumpWriter* writer, char type, oop obj, int offset) {
 973   switch (type) {
 974     case JVM_SIGNATURE_CLASS :
 975     case JVM_SIGNATURE_ARRAY : {
 976       oop o = obj->obj_field_access<ON_UNKNOWN_OOP_REF | AS_NO_KEEPALIVE>(offset);
 977       if (o != nullptr && log_is_enabled(Debug, cds, heap) && mask_dormant_archived_object(o) == nullptr) {
 978         ResourceMark rm;
 979         log_debug(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s) referenced by " INTPTR_FORMAT " (%s)",
 980                              p2i(o), o->klass()->external_name(),
 981                              p2i(obj), obj->klass()->external_name());
 982       }
 983       o = mask_dormant_archived_object(o);
 984       assert(oopDesc::is_oop_or_null(o), "Expected an oop or nullptr at " PTR_FORMAT, p2i(o));
 985       writer->write_objectID(o);
 986       break;
 987     }
 988     case JVM_SIGNATURE_BYTE : {
 989       jbyte b = obj->byte_field(offset);
 990       writer->write_u1(b);
 991       break;
 992     }
 993     case JVM_SIGNATURE_CHAR : {
 994       jchar c = obj->char_field(offset);
 995       writer->write_u2(c);
 996       break;
 997     }
 998     case JVM_SIGNATURE_SHORT : {
 999       jshort s = obj->short_field(offset);
1000       writer->write_u2(s);
1001       break;
1002     }
1003     case JVM_SIGNATURE_FLOAT : {
1004       jfloat f = obj->float_field(offset);
1005       dump_float(writer, f);
1006       break;
1007     }
1008     case JVM_SIGNATURE_DOUBLE : {
1009       jdouble d = obj->double_field(offset);
1010       dump_double(writer, d);
1011       break;
1012     }
1013     case JVM_SIGNATURE_INT : {
1014       jint i = obj->int_field(offset);
1015       writer->write_u4(i);
1016       break;
1017     }
1018     case JVM_SIGNATURE_LONG : {
1019       jlong l = obj->long_field(offset);
1020       writer->write_u8(l);
1021       break;
1022     }
1023     case JVM_SIGNATURE_BOOLEAN : {
1024       jboolean b = obj->bool_field(offset);
1025       writer->write_u1(b);
1026       break;
1027     }
1028     default : {
1029       ShouldNotReachHere();
1030       break;
1031     }
1032   }
1033 }
1034 
1035 // returns the size of the instance of the given class
1036 u4 DumperSupport::instance_size(InstanceKlass* ik, DumperClassCacheTableEntry* class_cache_entry) {
1037   if (class_cache_entry != nullptr) {
1038     return class_cache_entry->instance_size();
1039   } else {
1040     u4 size = 0;
1041     for (HierarchicalFieldStream<JavaFieldStream> fld(ik); !fld.done(); fld.next()) {
1042       if (!fld.access_flags().is_static()) {
1043         size += sig2size(fld.signature());
1044       }
1045     }
1046     return size;
1047   }
1048 }
1049 
1050 u4 DumperSupport::get_static_fields_size(InstanceKlass* ik, u2& field_count) {
1051   field_count = 0;
1052   u4 size = 0;
1053 
1054   for (JavaFieldStream fldc(ik); !fldc.done(); fldc.next()) {
1055     if (fldc.access_flags().is_static()) {
1056       field_count++;
1057       size += sig2size(fldc.signature());
1058     }
1059   }
1060 
1061   // Add in resolved_references which is referenced by the cpCache
1062   // The resolved_references is an array per InstanceKlass holding the
1063   // strings and other oops resolved from the constant pool.
1064   oop resolved_references = ik->constants()->resolved_references_or_null();
1065   if (resolved_references != nullptr) {
1066     field_count++;
1067     size += sizeof(address);
1068 
1069     // Add in the resolved_references of the used previous versions of the class
1070     // in the case of RedefineClasses
1071     InstanceKlass* prev = ik->previous_versions();
1072     while (prev != nullptr && prev->constants()->resolved_references_or_null() != nullptr) {
1073       field_count++;
1074       size += sizeof(address);
1075       prev = prev->previous_versions();
1076     }
1077   }
1078 
1079   // We write the value itself plus a name and a one byte type tag per field.
1080   return checked_cast<u4>(size + field_count * (sizeof(address) + 1));
1081 }
1082 
1083 // dumps static fields of the given class
1084 void DumperSupport::dump_static_fields(AbstractDumpWriter* writer, Klass* k) {
1085   InstanceKlass* ik = InstanceKlass::cast(k);
1086 
1087   // dump the field descriptors and raw values
1088   for (JavaFieldStream fld(ik); !fld.done(); fld.next()) {
1089     if (fld.access_flags().is_static()) {
1090       Symbol* sig = fld.signature();
1091 
1092       writer->write_symbolID(fld.name());   // name
1093       writer->write_u1(sig2tag(sig));       // type
1094 
1095       // value
1096       dump_field_value(writer, sig->char_at(0), ik->java_mirror(), fld.offset());
1097     }
1098   }
1099 
1100   // Add resolved_references for each class that has them
1101   oop resolved_references = ik->constants()->resolved_references_or_null();
1102   if (resolved_references != nullptr) {
1103     writer->write_symbolID(vmSymbols::resolved_references_name());  // name
1104     writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
1105     writer->write_objectID(resolved_references);
1106 
1107     // Also write any previous versions
1108     InstanceKlass* prev = ik->previous_versions();
1109     while (prev != nullptr && prev->constants()->resolved_references_or_null() != nullptr) {
1110       writer->write_symbolID(vmSymbols::resolved_references_name());  // name
1111       writer->write_u1(sig2tag(vmSymbols::object_array_signature())); // type
1112       writer->write_objectID(prev->constants()->resolved_references());
1113       prev = prev->previous_versions();
1114     }
1115   }
1116 }
1117 
1118 // dump the raw values of the instance fields of the given object
1119 void DumperSupport::dump_instance_fields(AbstractDumpWriter* writer, oop o, DumperClassCacheTableEntry* class_cache_entry) {
1120   assert(class_cache_entry != nullptr, "Pre-condition: must be provided");
1121   for (int idx = 0; idx < class_cache_entry->field_count(); idx++) {
1122     dump_field_value(writer, class_cache_entry->sig_start(idx), o, class_cache_entry->offset(idx));
1123   }
1124 }
1125 
1126 // dumps the definition of the instance fields for a given class
1127 u2 DumperSupport::get_instance_fields_count(InstanceKlass* ik) {
1128   u2 field_count = 0;
1129 
1130   for (JavaFieldStream fldc(ik); !fldc.done(); fldc.next()) {
1131     if (!fldc.access_flags().is_static()) field_count++;
1132   }
1133 
1134   return field_count;
1135 }
1136 
1137 // dumps the definition of the instance fields for a given class
1138 void DumperSupport::dump_instance_field_descriptors(AbstractDumpWriter* writer, Klass* k) {
1139   InstanceKlass* ik = InstanceKlass::cast(k);
1140 
1141   // dump the field descriptors
1142   for (JavaFieldStream fld(ik); !fld.done(); fld.next()) {
1143     if (!fld.access_flags().is_static()) {
1144       Symbol* sig = fld.signature();
1145 
1146       writer->write_symbolID(fld.name());   // name
1147       writer->write_u1(sig2tag(sig));       // type
1148     }
1149   }
1150 }
1151 
1152 // creates HPROF_GC_INSTANCE_DUMP record for the given object
1153 void DumperSupport::dump_instance(AbstractDumpWriter* writer, oop o, DumperClassCacheTable* class_cache) {
1154   InstanceKlass* ik = InstanceKlass::cast(o->klass());
1155 
1156   DumperClassCacheTableEntry* cache_entry = class_cache->lookup_or_create(ik);
1157 
1158   u4 is = instance_size(ik, cache_entry);
1159   u4 size = 1 + sizeof(address) + 4 + sizeof(address) + 4 + is;
1160 
1161   writer->start_sub_record(HPROF_GC_INSTANCE_DUMP, size);
1162   writer->write_objectID(o);
1163   writer->write_u4(STACK_TRACE_ID);
1164 
1165   // class ID
1166   writer->write_classID(ik);
1167 
1168   // number of bytes that follow
1169   writer->write_u4(is);
1170 
1171   // field values
1172   dump_instance_fields(writer, o, cache_entry);
1173 
1174   writer->end_sub_record();
1175 }
1176 
1177 // creates HPROF_GC_CLASS_DUMP record for the given instance class
1178 void DumperSupport::dump_instance_class(AbstractDumpWriter* writer, Klass* k) {
1179   InstanceKlass* ik = InstanceKlass::cast(k);
1180 
1181   // We can safepoint and do a heap dump at a point where we have a Klass,
1182   // but no java mirror class has been setup for it. So we need to check
1183   // that the class is at least loaded, to avoid crash from a null mirror.
1184   if (!ik->is_loaded()) {
1185     return;
1186   }
1187 
1188   u2 static_fields_count = 0;
1189   u4 static_size = get_static_fields_size(ik, static_fields_count);
1190   u2 instance_fields_count = get_instance_fields_count(ik);
1191   u4 instance_fields_size = instance_fields_count * (sizeof(address) + 1);
1192   u4 size = checked_cast<u4>(1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + static_size + 2 + instance_fields_size);
1193 
1194   writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);
1195 
1196   // class ID
1197   writer->write_classID(ik);
1198   writer->write_u4(STACK_TRACE_ID);
1199 
1200   // super class ID
1201   InstanceKlass* java_super = ik->java_super();
1202   if (java_super == nullptr) {
1203     writer->write_objectID(oop(nullptr));
1204   } else {
1205     writer->write_classID(java_super);
1206   }
1207 
1208   writer->write_objectID(ik->class_loader());
1209   writer->write_objectID(ik->signers());
1210   writer->write_objectID(ik->protection_domain());
1211 
1212   // reserved
1213   writer->write_objectID(oop(nullptr));
1214   writer->write_objectID(oop(nullptr));
1215 
1216   // instance size
1217   writer->write_u4(DumperSupport::instance_size(ik));
1218 
1219   // size of constant pool - ignored by HAT 1.1
1220   writer->write_u2(0);
1221 
1222   // static fields
1223   writer->write_u2(static_fields_count);
1224   dump_static_fields(writer, ik);
1225 
1226   // description of instance fields
1227   writer->write_u2(instance_fields_count);
1228   dump_instance_field_descriptors(writer, ik);
1229 
1230   writer->end_sub_record();
1231 }
1232 
1233 // creates HPROF_GC_CLASS_DUMP record for the given array class
1234 void DumperSupport::dump_array_class(AbstractDumpWriter* writer, Klass* k) {
1235   InstanceKlass* ik = nullptr; // bottom class for object arrays, null for primitive type arrays
1236   if (k->is_objArray_klass()) {
1237     Klass *bk = ObjArrayKlass::cast(k)->bottom_klass();
1238     assert(bk != nullptr, "checking");
1239     if (bk->is_instance_klass()) {
1240       ik = InstanceKlass::cast(bk);
1241     }
1242   }
1243 
1244   u4 size = 1 + sizeof(address) + 4 + 6 * sizeof(address) + 4 + 2 + 2 + 2;
1245   writer->start_sub_record(HPROF_GC_CLASS_DUMP, size);
1246   writer->write_classID(k);
1247   writer->write_u4(STACK_TRACE_ID);
1248 
1249   // super class of array classes is java.lang.Object
1250   InstanceKlass* java_super = k->java_super();
1251   assert(java_super != nullptr, "checking");
1252   writer->write_classID(java_super);
1253 
1254   writer->write_objectID(ik == nullptr ? oop(nullptr) : ik->class_loader());
1255   writer->write_objectID(ik == nullptr ? oop(nullptr) : ik->signers());
1256   writer->write_objectID(ik == nullptr ? oop(nullptr) : ik->protection_domain());
1257 
1258   writer->write_objectID(oop(nullptr));    // reserved
1259   writer->write_objectID(oop(nullptr));
1260   writer->write_u4(0);             // instance size
1261   writer->write_u2(0);             // constant pool
1262   writer->write_u2(0);             // static fields
1263   writer->write_u2(0);             // instance fields
1264 
1265   writer->end_sub_record();
1266 
1267 }
1268 
1269 // Hprof uses an u4 as record length field,
1270 // which means we need to truncate arrays that are too long.
1271 int DumperSupport::calculate_array_max_length(AbstractDumpWriter* writer, arrayOop array, short header_size) {
1272   BasicType type = ArrayKlass::cast(array->klass())->element_type();
1273   assert(type >= T_BOOLEAN && type <= T_OBJECT, "invalid array element type");
1274 
1275   int length = array->length();
1276 
1277   int type_size;
1278   if (type == T_OBJECT) {
1279     type_size = sizeof(address);
1280   } else {
1281     type_size = type2aelembytes(type);
1282   }
1283 
1284   size_t length_in_bytes = (size_t)length * type_size;
1285   uint max_bytes = max_juint - header_size;
1286 
1287   if (length_in_bytes > max_bytes) {
1288     length = max_bytes / type_size;
1289     length_in_bytes = (size_t)length * type_size;
1290 
1291     warning("cannot dump array of type %s[] with length %d; truncating to length %d",
1292             type2name_tab[type], array->length(), length);
1293   }
1294   return length;
1295 }
1296 
1297 // creates HPROF_GC_OBJ_ARRAY_DUMP record for the given object array
1298 void DumperSupport::dump_object_array(AbstractDumpWriter* writer, objArrayOop array) {
1299   // sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID) + sizeof(classID)
1300   short header_size = 1 + 2 * 4 + 2 * sizeof(address);
1301   int length = calculate_array_max_length(writer, array, header_size);
1302   u4 size = checked_cast<u4>(header_size + length * sizeof(address));
1303 
1304   writer->start_sub_record(HPROF_GC_OBJ_ARRAY_DUMP, size);
1305   writer->write_objectID(array);
1306   writer->write_u4(STACK_TRACE_ID);
1307   writer->write_u4(length);
1308 
1309   // array class ID
1310   writer->write_classID(array->klass());
1311 
1312   // [id]* elements
1313   for (int index = 0; index < length; index++) {
1314     oop o = array->obj_at(index);
1315     if (o != nullptr && log_is_enabled(Debug, cds, heap) && mask_dormant_archived_object(o) == nullptr) {
1316       ResourceMark rm;
1317       log_debug(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s) referenced by " INTPTR_FORMAT " (%s)",
1318                            p2i(o), o->klass()->external_name(),
1319                            p2i(array), array->klass()->external_name());
1320     }
1321     o = mask_dormant_archived_object(o);
1322     writer->write_objectID(o);
1323   }
1324 
1325   writer->end_sub_record();
1326 }
1327 
1328 #define WRITE_ARRAY(Array, Type, Size, Length) \
1329   for (int i = 0; i < Length; i++) { writer->write_##Size((Size)Array->Type##_at(i)); }
1330 
1331 // creates HPROF_GC_PRIM_ARRAY_DUMP record for the given type array
1332 void DumperSupport::dump_prim_array(AbstractDumpWriter* writer, typeArrayOop array) {
1333   BasicType type = TypeArrayKlass::cast(array->klass())->element_type();
1334   // 2 * sizeof(u1) + 2 * sizeof(u4) + sizeof(objectID)
1335   short header_size = 2 * 1 + 2 * 4 + sizeof(address);
1336 
1337   int length = calculate_array_max_length(writer, array, header_size);
1338   int type_size = type2aelembytes(type);
1339   u4 length_in_bytes = (u4)length * type_size;
1340   u4 size = header_size + length_in_bytes;
1341 
1342   writer->start_sub_record(HPROF_GC_PRIM_ARRAY_DUMP, size);
1343   writer->write_objectID(array);
1344   writer->write_u4(STACK_TRACE_ID);
1345   writer->write_u4(length);
1346   writer->write_u1(type2tag(type));
1347 
1348   // nothing to copy
1349   if (length == 0) {
1350     writer->end_sub_record();
1351     return;
1352   }
1353 
1354   // If the byte ordering is big endian then we can copy most types directly
1355 
1356   switch (type) {
1357     case T_INT : {
1358       if (Endian::is_Java_byte_ordering_different()) {
1359         WRITE_ARRAY(array, int, u4, length);
1360       } else {
1361         writer->write_raw(array->int_at_addr(0), length_in_bytes);
1362       }
1363       break;
1364     }
1365     case T_BYTE : {
1366       writer->write_raw(array->byte_at_addr(0), length_in_bytes);
1367       break;
1368     }
1369     case T_CHAR : {
1370       if (Endian::is_Java_byte_ordering_different()) {
1371         WRITE_ARRAY(array, char, u2, length);
1372       } else {
1373         writer->write_raw(array->char_at_addr(0), length_in_bytes);
1374       }
1375       break;
1376     }
1377     case T_SHORT : {
1378       if (Endian::is_Java_byte_ordering_different()) {
1379         WRITE_ARRAY(array, short, u2, length);
1380       } else {
1381         writer->write_raw(array->short_at_addr(0), length_in_bytes);
1382       }
1383       break;
1384     }
1385     case T_BOOLEAN : {
1386       if (Endian::is_Java_byte_ordering_different()) {
1387         WRITE_ARRAY(array, bool, u1, length);
1388       } else {
1389         writer->write_raw(array->bool_at_addr(0), length_in_bytes);
1390       }
1391       break;
1392     }
1393     case T_LONG : {
1394       if (Endian::is_Java_byte_ordering_different()) {
1395         WRITE_ARRAY(array, long, u8, length);
1396       } else {
1397         writer->write_raw(array->long_at_addr(0), length_in_bytes);
1398       }
1399       break;
1400     }
1401 
1402     // handle float/doubles in a special value to ensure than NaNs are
1403     // written correctly. TO DO: Check if we can avoid this on processors that
1404     // use IEEE 754.
1405 
1406     case T_FLOAT : {
1407       for (int i = 0; i < length; i++) {
1408         dump_float(writer, array->float_at(i));
1409       }
1410       break;
1411     }
1412     case T_DOUBLE : {
1413       for (int i = 0; i < length; i++) {
1414         dump_double(writer, array->double_at(i));
1415       }
1416       break;
1417     }
1418     default : ShouldNotReachHere();
1419   }
1420 
1421   writer->end_sub_record();
1422 }
1423 
1424 // create a HPROF_FRAME record of the given Method* and bci
1425 void DumperSupport::dump_stack_frame(AbstractDumpWriter* writer,
1426                                      int frame_serial_num,
1427                                      int class_serial_num,
1428                                      Method* m,
1429                                      int bci) {
1430   int line_number;
1431   if (m->is_native()) {
1432     line_number = -3;  // native frame
1433   } else {
1434     line_number = m->line_number_from_bci(bci);
1435   }
1436 
1437   write_header(writer, HPROF_FRAME, 4*oopSize + 2*sizeof(u4));
1438   writer->write_id(frame_serial_num);               // frame serial number
1439   writer->write_symbolID(m->name());                // method's name
1440   writer->write_symbolID(m->signature());           // method's signature
1441 
1442   assert(m->method_holder()->is_instance_klass(), "not InstanceKlass");
1443   writer->write_symbolID(m->method_holder()->source_file_name());  // source file name
1444   writer->write_u4(class_serial_num);               // class serial number
1445   writer->write_u4((u4) line_number);               // line number
1446 }
1447 
1448 
1449 // Support class used to generate HPROF_UTF8 records from the entries in the
1450 // SymbolTable.
1451 
1452 class SymbolTableDumper : public SymbolClosure {
1453  private:
1454   AbstractDumpWriter* _writer;
1455   AbstractDumpWriter* writer() const                { return _writer; }
1456  public:
1457   SymbolTableDumper(AbstractDumpWriter* writer)     { _writer = writer; }
1458   void do_symbol(Symbol** p);
1459 };
1460 
1461 void SymbolTableDumper::do_symbol(Symbol** p) {
1462   ResourceMark rm;
1463   Symbol* sym = *p;
1464   int len = sym->utf8_length();
1465   if (len > 0) {
1466     char* s = sym->as_utf8();
1467     DumperSupport::write_header(writer(), HPROF_UTF8, oopSize + len);
1468     writer()->write_symbolID(sym);
1469     writer()->write_raw(s, len);
1470   }
1471 }
1472 
1473 // Support class used to generate HPROF_GC_ROOT_JNI_LOCAL records
1474 
1475 class JNILocalsDumper : public OopClosure {
1476  private:
1477   AbstractDumpWriter* _writer;
1478   u4 _thread_serial_num;
1479   int _frame_num;
1480   AbstractDumpWriter* writer() const                { return _writer; }
1481  public:
1482   JNILocalsDumper(AbstractDumpWriter* writer, u4 thread_serial_num) {
1483     _writer = writer;
1484     _thread_serial_num = thread_serial_num;
1485     _frame_num = -1;  // default - empty stack
1486   }
1487   void set_frame_number(int n) { _frame_num = n; }
1488   void do_oop(oop* obj_p);
1489   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1490 };
1491 
1492 void JNILocalsDumper::do_oop(oop* obj_p) {
1493   // ignore null handles
1494   oop o = *obj_p;
1495   if (o != nullptr) {
1496     u4 size = 1 + sizeof(address) + 4 + 4;
1497     writer()->start_sub_record(HPROF_GC_ROOT_JNI_LOCAL, size);
1498     writer()->write_objectID(o);
1499     writer()->write_u4(_thread_serial_num);
1500     writer()->write_u4((u4)_frame_num);
1501     writer()->end_sub_record();
1502   }
1503 }
1504 
1505 
1506 // Support class used to generate HPROF_GC_ROOT_JNI_GLOBAL records
1507 
1508 class JNIGlobalsDumper : public OopClosure {
1509  private:
1510   AbstractDumpWriter* _writer;
1511   AbstractDumpWriter* writer() const                { return _writer; }
1512 
1513  public:
1514   JNIGlobalsDumper(AbstractDumpWriter* writer) {
1515     _writer = writer;
1516   }
1517   void do_oop(oop* obj_p);
1518   void do_oop(narrowOop* obj_p) { ShouldNotReachHere(); }
1519 };
1520 
1521 void JNIGlobalsDumper::do_oop(oop* obj_p) {
1522   oop o = NativeAccess<AS_NO_KEEPALIVE>::oop_load(obj_p);
1523 
1524   // ignore these
1525   if (o == nullptr) return;
1526   // we ignore global ref to symbols and other internal objects
1527   if (o->is_instance() || o->is_objArray() || o->is_typeArray()) {
1528     u4 size = 1 + 2 * sizeof(address);
1529     writer()->start_sub_record(HPROF_GC_ROOT_JNI_GLOBAL, size);
1530     writer()->write_objectID(o);
1531     writer()->write_rootID(obj_p);      // global ref ID
1532     writer()->end_sub_record();
1533   }
1534 };
1535 
1536 // Support class used to generate HPROF_GC_ROOT_STICKY_CLASS records
1537 
1538 class StickyClassDumper : public KlassClosure {
1539  private:
1540   AbstractDumpWriter* _writer;
1541   AbstractDumpWriter* writer() const                { return _writer; }
1542  public:
1543   StickyClassDumper(AbstractDumpWriter* writer) {
1544     _writer = writer;
1545   }
1546   void do_klass(Klass* k) {
1547     if (k->is_instance_klass()) {
1548       InstanceKlass* ik = InstanceKlass::cast(k);
1549       u4 size = 1 + sizeof(address);
1550       writer()->start_sub_record(HPROF_GC_ROOT_STICKY_CLASS, size);
1551       writer()->write_classID(ik);
1552       writer()->end_sub_record();
1553     }
1554   }
1555 };
1556 
1557 // Support class used to generate HPROF_GC_ROOT_JAVA_FRAME records.
1558 
1559 class JavaStackRefDumper : public StackObj {
1560 private:
1561   AbstractDumpWriter* _writer;
1562   u4 _thread_serial_num;
1563   int _frame_num;
1564   AbstractDumpWriter* writer() const { return _writer; }
1565 public:
1566   JavaStackRefDumper(AbstractDumpWriter* writer, u4 thread_serial_num)
1567       : _writer(writer), _thread_serial_num(thread_serial_num), _frame_num(-1) // default - empty stack
1568   {
1569   }
1570 
1571   void set_frame_number(int n) { _frame_num = n; }
1572 
1573   void dump_java_stack_refs(StackValueCollection* values);
1574 };
1575 
1576 void JavaStackRefDumper::dump_java_stack_refs(StackValueCollection* values) {
1577   for (int index = 0; index < values->size(); index++) {
1578     if (values->at(index)->type() == T_OBJECT) {
1579       oop o = values->obj_at(index)();
1580       if (o != nullptr) {
1581         u4 size = 1 + sizeof(address) + 4 + 4;
1582         writer()->start_sub_record(HPROF_GC_ROOT_JAVA_FRAME, size);
1583         writer()->write_objectID(o);
1584         writer()->write_u4(_thread_serial_num);
1585         writer()->write_u4((u4)_frame_num);
1586         writer()->end_sub_record();
1587       }
1588     }
1589   }
1590 }
1591 
1592 // Class to collect, store and dump thread-related data:
1593 // - HPROF_TRACE and HPROF_FRAME records;
1594 // - HPROF_GC_ROOT_THREAD_OBJ/HPROF_GC_ROOT_JAVA_FRAME/HPROF_GC_ROOT_JNI_LOCAL subrecords.
1595 class ThreadDumper : public CHeapObj<mtInternal> {
1596 public:
1597   enum class ThreadType { Platform, MountedVirtual, UnmountedVirtual };
1598 
1599 private:
1600   ThreadType _thread_type;
1601   JavaThread* _java_thread;
1602   oop _thread_oop;
1603 
1604   GrowableArray<StackFrameInfo*>* _frames;
1605   // non-null if the thread is OOM thread
1606   Method* _oome_constructor;
1607   int _thread_serial_num;
1608   int _start_frame_serial_num;
1609 
1610   vframe* get_top_frame() const;
1611 
1612 public:
1613   static bool should_dump_pthread(JavaThread* thread) {
1614     return thread->threadObj() != nullptr && !thread->is_exiting() && !thread->is_hidden_from_external_view();
1615   }
1616 
1617   static bool should_dump_vthread(oop vt) {
1618     return java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::NEW
1619         && java_lang_VirtualThread::state(vt) != java_lang_VirtualThread::TERMINATED;
1620   }
1621 
1622   ThreadDumper(ThreadType thread_type, JavaThread* java_thread, oop thread_oop);
1623 
1624   // affects frame_count
1625   void add_oom_frame(Method* oome_constructor) {
1626     assert(_start_frame_serial_num == 0, "add_oom_frame cannot be called after init_serial_nums");
1627     _oome_constructor = oome_constructor;
1628   }
1629 
1630   void init_serial_nums(volatile int* thread_counter, volatile int* frame_counter) {
1631     assert(_start_frame_serial_num == 0, "already initialized");
1632     _thread_serial_num = Atomic::fetch_then_add(thread_counter, 1);
1633     _start_frame_serial_num = Atomic::fetch_then_add(frame_counter, frame_count());
1634   }
1635 
1636   bool oom_thread() const {
1637     return _oome_constructor != nullptr;
1638   }
1639 
1640   int frame_count() const {
1641     return _frames->length() + (oom_thread() ? 1 : 0);
1642   }
1643 
1644   u4 thread_serial_num() const {
1645     return (u4)_thread_serial_num;
1646   }
1647 
1648   u4 stack_trace_serial_num() const {
1649     return (u4)(_thread_serial_num + STACK_TRACE_ID);
1650   }
1651 
1652   // writes HPROF_TRACE and HPROF_FRAME records
1653   // returns number of dumped frames
1654   void dump_stack_traces(AbstractDumpWriter* writer, GrowableArray<Klass*>* klass_map);
1655 
1656   // writes HPROF_GC_ROOT_THREAD_OBJ subrecord
1657   void dump_thread_obj(AbstractDumpWriter* writer);
1658 
1659   // Walk the stack of the thread.
1660   // Dumps a HPROF_GC_ROOT_JAVA_FRAME subrecord for each local
1661   // Dumps a HPROF_GC_ROOT_JNI_LOCAL subrecord for each JNI local
1662   void dump_stack_refs(AbstractDumpWriter* writer);
1663 
1664 };
1665 
1666 ThreadDumper::ThreadDumper(ThreadType thread_type, JavaThread* java_thread, oop thread_oop)
1667     : _thread_type(thread_type), _java_thread(java_thread), _thread_oop(thread_oop),
1668       _oome_constructor(nullptr),
1669       _thread_serial_num(0), _start_frame_serial_num(0)
1670 {
1671   // sanity checks
1672   if (_thread_type == ThreadType::UnmountedVirtual) {
1673     assert(_java_thread == nullptr, "sanity");
1674     assert(_thread_oop != nullptr, "sanity");
1675   } else {
1676     assert(_java_thread != nullptr, "sanity");
1677     assert(_thread_oop != nullptr, "sanity");
1678   }
1679 
1680   _frames = new (mtServiceability) GrowableArray<StackFrameInfo*>(10, mtServiceability);
1681   bool stop_at_vthread_entry = _thread_type == ThreadType::MountedVirtual;
1682 
1683   // vframes are resource allocated
1684   Thread* current_thread = Thread::current();
1685   ResourceMark rm(current_thread);
1686   HandleMark hm(current_thread);
1687 
1688   for (vframe* vf = get_top_frame(); vf != nullptr; vf = vf->sender()) {
1689     if (stop_at_vthread_entry && vf->is_vthread_entry()) {
1690       break;
1691     }
1692     if (vf->is_java_frame()) {
1693       javaVFrame* jvf = javaVFrame::cast(vf);
1694       _frames->append(new StackFrameInfo(jvf, false));
1695     } else {
1696       // ignore non-Java frames
1697     }
1698   }
1699 }
1700 
1701 void ThreadDumper::dump_stack_traces(AbstractDumpWriter* writer, GrowableArray<Klass*>* klass_map) {
1702   assert(_thread_serial_num != 0 && _start_frame_serial_num != 0, "serial_nums are not initialized");
1703 
1704   // write HPROF_FRAME records for this thread's stack trace
1705   int depth = _frames->length();
1706   int frame_serial_num = _start_frame_serial_num;
1707 
1708   if (oom_thread()) {
1709     // OOM thread
1710     // write fake frame that makes it look like the thread, which caused OOME,
1711     // is in the OutOfMemoryError zero-parameter constructor
1712     int oome_serial_num = klass_map->find(_oome_constructor->method_holder());
1713     // the class serial number starts from 1
1714     assert(oome_serial_num > 0, "OutOfMemoryError class not found");
1715     DumperSupport::dump_stack_frame(writer, ++frame_serial_num, oome_serial_num, _oome_constructor, 0);
1716     depth++;
1717   }
1718 
1719   for (int j = 0; j < _frames->length(); j++) {
1720     StackFrameInfo* frame = _frames->at(j);
1721     Method* m = frame->method();
1722     int class_serial_num = klass_map->find(m->method_holder());
1723     // the class serial number starts from 1
1724     assert(class_serial_num > 0, "class not found");
1725     DumperSupport::dump_stack_frame(writer, ++frame_serial_num, class_serial_num, m, frame->bci());
1726   }
1727 
1728   // write HPROF_TRACE record for the thread
1729   DumperSupport::write_header(writer, HPROF_TRACE, checked_cast<u4>(3 * sizeof(u4) + depth * oopSize));
1730   writer->write_u4(stack_trace_serial_num());   // stack trace serial number
1731   writer->write_u4(thread_serial_num());        // thread serial number
1732   writer->write_u4((u4)depth);                  // frame count (including oom frame)
1733   for (int j = 1; j <= depth; j++) {
1734     writer->write_id(_start_frame_serial_num + j);
1735   }
1736 }
1737 
1738 void ThreadDumper::dump_thread_obj(AbstractDumpWriter * writer) {
1739   assert(_thread_serial_num != 0 && _start_frame_serial_num != 0, "serial_num is not initialized");
1740 
1741   u4 size = 1 + sizeof(address) + 4 + 4;
1742   writer->start_sub_record(HPROF_GC_ROOT_THREAD_OBJ, size);
1743   writer->write_objectID(_thread_oop);
1744   writer->write_u4(thread_serial_num());      // thread serial number
1745   writer->write_u4(stack_trace_serial_num()); // stack trace serial number
1746   writer->end_sub_record();
1747 }
1748 
1749 void ThreadDumper::dump_stack_refs(AbstractDumpWriter * writer) {
1750   assert(_thread_serial_num != 0 && _start_frame_serial_num != 0, "serial_num is not initialized");
1751 
1752   JNILocalsDumper blk(writer, thread_serial_num());
1753   if (_thread_type == ThreadType::Platform) {
1754     if (!_java_thread->has_last_Java_frame()) {
1755       // no last java frame but there may be JNI locals
1756       _java_thread->active_handles()->oops_do(&blk);
1757       return;
1758     }
1759   }
1760 
1761   JavaStackRefDumper java_ref_dumper(writer, thread_serial_num());
1762 
1763   // vframes are resource allocated
1764   Thread* current_thread = Thread::current();
1765   ResourceMark rm(current_thread);
1766   HandleMark hm(current_thread);
1767 
1768   bool stopAtVthreadEntry = _thread_type == ThreadType::MountedVirtual;
1769   frame* last_entry_frame = nullptr;
1770   bool is_top_frame = true;
1771   int depth = 0;
1772   if (oom_thread()) {
1773     depth++;
1774   }
1775 
1776   for (vframe* vf = get_top_frame(); vf != nullptr; vf = vf->sender()) {
1777     if (stopAtVthreadEntry && vf->is_vthread_entry()) {
1778       break;
1779     }
1780 
1781     if (vf->is_java_frame()) {
1782       javaVFrame* jvf = javaVFrame::cast(vf);
1783       if (!(jvf->method()->is_native())) {
1784         java_ref_dumper.set_frame_number(depth);
1785         java_ref_dumper.dump_java_stack_refs(jvf->locals());
1786         java_ref_dumper.dump_java_stack_refs(jvf->expressions());
1787       } else {
1788         // native frame
1789         blk.set_frame_number(depth);
1790         if (is_top_frame) {
1791           // JNI locals for the top frame.
1792           assert(_java_thread != nullptr, "impossible for unmounted vthread");
1793           _java_thread->active_handles()->oops_do(&blk);
1794         } else {
1795           if (last_entry_frame != nullptr) {
1796             // JNI locals for the entry frame
1797             assert(last_entry_frame->is_entry_frame(), "checking");
1798             last_entry_frame->entry_frame_call_wrapper()->handles()->oops_do(&blk);
1799           }
1800         }
1801       }
1802       last_entry_frame = nullptr;
1803       // increment only for Java frames
1804       depth++;
1805     } else {
1806       // externalVFrame - for an entry frame then we report the JNI locals
1807       // when we find the corresponding javaVFrame
1808       frame* fr = vf->frame_pointer();
1809       assert(fr != nullptr, "sanity check");
1810       if (fr->is_entry_frame()) {
1811         last_entry_frame = fr;
1812       }
1813     }
1814   is_top_frame = false;
1815   }
1816   assert(depth == frame_count(), "total number of Java frames not matched");
1817 }
1818 
1819 vframe* ThreadDumper::get_top_frame() const {
1820   if (_thread_type == ThreadType::UnmountedVirtual) {
1821     ContinuationWrapper cont(java_lang_VirtualThread::continuation(_thread_oop));
1822     if (cont.is_empty()) {
1823       return nullptr;
1824     }
1825     assert(!cont.is_mounted(), "sanity check");
1826     stackChunkOop chunk = cont.last_nonempty_chunk();
1827     if (chunk == nullptr || chunk->is_empty()) {
1828       return nullptr;
1829     }
1830 
1831     RegisterMap reg_map(cont.continuation(), RegisterMap::UpdateMap::include);
1832     frame fr = chunk->top_frame(&reg_map);
1833     vframe* vf = vframe::new_vframe(&fr, &reg_map, nullptr); // don't need JavaThread
1834     return vf;
1835   }
1836 
1837   RegisterMap reg_map(_java_thread,
1838       RegisterMap::UpdateMap::include,
1839       RegisterMap::ProcessFrames::include,
1840       RegisterMap::WalkContinuation::skip);
1841   switch (_thread_type) {
1842   case ThreadType::Platform:
1843     if (!_java_thread->has_last_Java_frame()) {
1844       return nullptr;
1845     }
1846     return _java_thread->is_vthread_mounted()
1847         ? _java_thread->carrier_last_java_vframe(&reg_map)
1848         : _java_thread->platform_thread_last_java_vframe(&reg_map);
1849 
1850   case ThreadType::MountedVirtual:
1851     return _java_thread->last_java_vframe(&reg_map);
1852 
1853   default: // make compilers happy
1854       break;
1855   }
1856   ShouldNotReachHere();
1857   return nullptr;
1858 }
1859 
1860 
1861 class VM_HeapDumper;
1862 
1863 // Support class using when iterating over the heap.
1864 class HeapObjectDumper : public ObjectClosure {
1865  private:
1866   AbstractDumpWriter* _writer;
1867   AbstractDumpWriter* writer()                  { return _writer; }
1868 
1869   DumperClassCacheTable _class_cache;
1870 
1871  public:
1872   HeapObjectDumper(AbstractDumpWriter* writer) {
1873     _writer = writer;
1874   }
1875 
1876   // called for each object in the heap
1877   void do_object(oop o);
1878 };
1879 
1880 void HeapObjectDumper::do_object(oop o) {
1881   // skip classes as these emitted as HPROF_GC_CLASS_DUMP records
1882   if (o->klass() == vmClasses::Class_klass()) {
1883     if (!java_lang_Class::is_primitive(o)) {
1884       return;
1885     }
1886   }
1887 
1888   if (DumperSupport::mask_dormant_archived_object(o) == nullptr) {
1889     log_debug(cds, heap)("skipped dormant archived object " INTPTR_FORMAT " (%s)", p2i(o), o->klass()->external_name());
1890     return;
1891   }
1892 
1893   if (o->is_instance()) {
1894     // create a HPROF_GC_INSTANCE record for each object
1895     DumperSupport::dump_instance(writer(), o, &_class_cache);
1896   } else if (o->is_objArray()) {
1897     // create a HPROF_GC_OBJ_ARRAY_DUMP record for each object array
1898     DumperSupport::dump_object_array(writer(), objArrayOop(o));
1899   } else if (o->is_typeArray()) {
1900     // create a HPROF_GC_PRIM_ARRAY_DUMP record for each type array
1901     DumperSupport::dump_prim_array(writer(), typeArrayOop(o));
1902   }
1903 }
1904 
1905 // The dumper controller for parallel heap dump
1906 class DumperController : public CHeapObj<mtInternal> {
1907  private:
1908    Monitor* _lock;
1909    const uint   _dumper_number;
1910    uint   _complete_number;
1911 
1912  public:
1913    DumperController(uint number) :
1914      _lock(new (std::nothrow) PaddedMonitor(Mutex::safepoint, "DumperController_lock")),
1915      _dumper_number(number),
1916      _complete_number(0) { }
1917 
1918    ~DumperController() { delete _lock; }
1919 
1920    void dumper_complete(DumpWriter* local_writer, DumpWriter* global_writer) {
1921      MonitorLocker ml(_lock, Mutex::_no_safepoint_check_flag);
1922      _complete_number++;
1923      // propagate local error to global if any
1924      if (local_writer->has_error()) {
1925        global_writer->set_error(local_writer->error());
1926      }
1927      ml.notify();
1928    }
1929 
1930    void wait_all_dumpers_complete() {
1931      MonitorLocker ml(_lock, Mutex::_no_safepoint_check_flag);
1932      while (_complete_number != _dumper_number) {
1933         ml.wait();
1934      }
1935    }
1936 };
1937 
1938 // DumpMerger merges separate dump files into a complete one
1939 class DumpMerger : public StackObj {
1940 private:
1941   DumpWriter* _writer;
1942   const char* _path;
1943   bool _has_error;
1944   int _dump_seq;
1945 
1946 private:
1947   void merge_file(char* path);
1948   void merge_done();
1949   void set_error(const char* msg);
1950 
1951 public:
1952   DumpMerger(const char* path, DumpWriter* writer, int dump_seq) :
1953     _writer(writer),
1954     _path(path),
1955     _has_error(_writer->has_error()),
1956     _dump_seq(dump_seq) {}
1957 
1958   void do_merge();
1959 };
1960 
1961 void DumpMerger::merge_done() {
1962   // Writes the HPROF_HEAP_DUMP_END record.
1963   if (!_has_error) {
1964     DumperSupport::end_of_dump(_writer);
1965     _writer->flush();
1966   }
1967   _dump_seq = 0; //reset
1968 }
1969 
1970 void DumpMerger::set_error(const char* msg) {
1971   assert(msg != nullptr, "sanity check");
1972   log_error(heapdump)("%s (file: %s)", msg, _path);
1973   _writer->set_error(msg);
1974   _has_error = true;
1975 }
1976 
1977 #ifdef LINUX
1978 // Merge segmented heap files via sendfile, it's more efficient than the
1979 // read+write combination, which would require transferring data to and from
1980 // user space.
1981 void DumpMerger::merge_file(char* path) {
1982   assert(!SafepointSynchronize::is_at_safepoint(), "merging happens outside safepoint");
1983   TraceTime timer("Merge segmented heap file directly", TRACETIME_LOG(Info, heapdump));
1984 
1985   int segment_fd = os::open(path, O_RDONLY, 0);
1986   if (segment_fd == -1) {
1987     set_error("Can not open segmented heap file during merging");
1988     return;
1989   }
1990 
1991   struct stat st;
1992   if (os::stat(path, &st) != 0) {
1993     ::close(segment_fd);
1994     set_error("Can not get segmented heap file size during merging");
1995     return;
1996   }
1997 
1998   // A successful call to sendfile may write fewer bytes than requested; the
1999   // caller should be prepared to retry the call if there were unsent bytes.
2000   jlong offset = 0;
2001   while (offset < st.st_size) {
2002     int ret = os::Linux::sendfile(_writer->get_fd(), segment_fd, &offset, st.st_size);
2003     if (ret == -1) {
2004       ::close(segment_fd);
2005       set_error("Failed to merge segmented heap file");
2006       return;
2007     }
2008   }
2009 
2010   // As sendfile variant does not call the write method of the global writer,
2011   // bytes_written is also incorrect for this variant, we need to explicitly
2012   // accumulate bytes_written for the global writer in this case
2013   julong accum = _writer->bytes_written() + st.st_size;
2014   _writer->set_bytes_written(accum);
2015   ::close(segment_fd);
2016 }
2017 #else
2018 // Generic implementation using read+write
2019 void DumpMerger::merge_file(char* path) {
2020   assert(!SafepointSynchronize::is_at_safepoint(), "merging happens outside safepoint");
2021   TraceTime timer("Merge segmented heap file", TRACETIME_LOG(Info, heapdump));
2022 
2023   fileStream segment_fs(path, "rb");
2024   if (!segment_fs.is_open()) {
2025     set_error("Can not open segmented heap file during merging");
2026     return;
2027   }
2028 
2029   jlong total = 0;
2030   size_t cnt = 0;
2031   char read_buf[4096];
2032   while ((cnt = segment_fs.read(read_buf, 1, 4096)) != 0) {
2033     _writer->write_raw(read_buf, cnt);
2034     total += cnt;
2035   }
2036 
2037   _writer->flush();
2038   if (segment_fs.fileSize() != total) {
2039     set_error("Merged heap dump is incomplete");
2040   }
2041 }
2042 #endif
2043 
2044 void DumpMerger::do_merge() {
2045   assert(!SafepointSynchronize::is_at_safepoint(), "merging happens outside safepoint");
2046   TraceTime timer("Merge heap files complete", TRACETIME_LOG(Info, heapdump));
2047 
2048   // Since contents in segmented heap file were already zipped, we don't need to zip
2049   // them again during merging.
2050   AbstractCompressor* saved_compressor = _writer->compressor();
2051   _writer->set_compressor(nullptr);
2052 
2053   // Merge the content of the remaining files into base file. Regardless of whether
2054   // the merge process is successful or not, these segmented files will be deleted.
2055   char path[JVM_MAXPATHLEN];
2056   for (int i = 0; i < _dump_seq; i++) {
2057     memset(path, 0, JVM_MAXPATHLEN);
2058     os::snprintf(path, JVM_MAXPATHLEN, "%s.p%d", _path, i);
2059     if (!_has_error) {
2060       merge_file(path);
2061     }
2062     // Delete selected segmented heap file nevertheless
2063     if (remove(path) != 0) {
2064       log_info(heapdump)("Removal of segment file (%d) failed (%d)", i, errno);
2065     }
2066   }
2067 
2068   // restore compressor for further use
2069   _writer->set_compressor(saved_compressor);
2070   merge_done();
2071 }
2072 
2073 // The VM operation wraps DumpMerger so that it could be performed by VM thread
2074 class VM_HeapDumpMerge : public VM_Operation {
2075 private:
2076   DumpMerger* _merger;
2077 public:
2078   VM_HeapDumpMerge(DumpMerger* merger) : _merger(merger) {}
2079   VMOp_Type type() const { return VMOp_HeapDumpMerge; }
2080   // heap dump merge could happen outside safepoint
2081   virtual bool evaluate_at_safepoint() const { return false; }
2082   void doit() {
2083     _merger->do_merge();
2084   }
2085 };
2086 
2087 // The VM operation that performs the heap dump
2088 class VM_HeapDumper : public VM_GC_Operation, public WorkerTask {
2089  private:
2090   static VM_HeapDumper*   _global_dumper;
2091   static DumpWriter*      _global_writer;
2092   DumpWriter*             _local_writer;
2093   JavaThread*             _oome_thread;
2094   Method*                 _oome_constructor;
2095   bool                    _gc_before_heap_dump;
2096   GrowableArray<Klass*>*  _klass_map;
2097 
2098   ThreadDumper**          _thread_dumpers; // platform, carrier and mounted virtual threads
2099   int                     _thread_dumpers_count;
2100   volatile int            _thread_serial_num;
2101   volatile int            _frame_serial_num;
2102 
2103   volatile int            _dump_seq;
2104   // parallel heap dump support
2105   uint                    _num_dumper_threads;
2106   DumperController*       _dumper_controller;
2107   ParallelObjectIterator* _poi;
2108   // worker id of VMDumper thread.
2109   static const size_t VMDumperWorkerId = 0;
2110   // VM dumper dumps both heap and non-heap data, other dumpers dump heap-only data.
2111   static bool is_vm_dumper(uint worker_id) { return worker_id == VMDumperWorkerId; }
2112 
2113   // accessors and setters
2114   static VM_HeapDumper* dumper()         {  assert(_global_dumper != nullptr, "Error"); return _global_dumper; }
2115   static DumpWriter* writer()            {  assert(_global_writer != nullptr, "Error"); return _global_writer; }
2116 
2117   void set_global_dumper() {
2118     assert(_global_dumper == nullptr, "Error");
2119     _global_dumper = this;
2120   }
2121   void set_global_writer() {
2122     assert(_global_writer == nullptr, "Error");
2123     _global_writer = _local_writer;
2124   }
2125   void clear_global_dumper() { _global_dumper = nullptr; }
2126   void clear_global_writer() { _global_writer = nullptr; }
2127 
2128   bool skip_operation() const;
2129 
2130   // create dump writer for every parallel dump thread
2131   DumpWriter* create_local_writer();
2132 
2133   // writes a HPROF_LOAD_CLASS record
2134   static void do_load_class(Klass* k);
2135 
2136   // writes a HPROF_GC_CLASS_DUMP record for the given class
2137   static void do_class_dump(Klass* k);
2138 
2139   // HPROF_GC_ROOT_THREAD_OBJ records for platform and mounted virtual threads
2140   void dump_threads();
2141 
2142   void add_class_serial_number(Klass* k, int serial_num) {
2143     _klass_map->at_put_grow(serial_num, k);
2144   }
2145 
2146   bool is_oom_thread(JavaThread* thread) const {
2147     return thread == _oome_thread && _oome_constructor != nullptr;
2148   }
2149 
2150   // HPROF_TRACE and HPROF_FRAME records for platform and mounted virtual threads
2151   void dump_stack_traces();
2152 
2153  public:
2154   VM_HeapDumper(DumpWriter* writer, bool gc_before_heap_dump, bool oome, uint num_dump_threads) :
2155     VM_GC_Operation(0 /* total collections,      dummy, ignored */,
2156                     GCCause::_heap_dump /* GC Cause */,
2157                     0 /* total full collections, dummy, ignored */,
2158                     gc_before_heap_dump),
2159     WorkerTask("dump heap") {
2160     _local_writer = writer;
2161     _gc_before_heap_dump = gc_before_heap_dump;
2162     _klass_map = new (mtServiceability) GrowableArray<Klass*>(INITIAL_CLASS_COUNT, mtServiceability);
2163 
2164     _thread_dumpers = nullptr;
2165     _thread_dumpers_count = 0;
2166     _thread_serial_num = 1;
2167     _frame_serial_num = 1;
2168 
2169     _dump_seq = 0;
2170     _num_dumper_threads = num_dump_threads;
2171     _dumper_controller = nullptr;
2172     _poi = nullptr;
2173     if (oome) {
2174       assert(!Thread::current()->is_VM_thread(), "Dump from OutOfMemoryError cannot be called by the VMThread");
2175       // get OutOfMemoryError zero-parameter constructor
2176       InstanceKlass* oome_ik = vmClasses::OutOfMemoryError_klass();
2177       _oome_constructor = oome_ik->find_method(vmSymbols::object_initializer_name(),
2178                                                           vmSymbols::void_method_signature());
2179       // get thread throwing OOME when generating the heap dump at OOME
2180       _oome_thread = JavaThread::current();
2181     } else {
2182       _oome_thread = nullptr;
2183       _oome_constructor = nullptr;
2184     }
2185   }
2186 
2187   ~VM_HeapDumper() {
2188     if (_thread_dumpers != nullptr) {
2189       for (int i = 0; i < _thread_dumpers_count; i++) {
2190         delete _thread_dumpers[i];
2191       }
2192       FREE_C_HEAP_ARRAY(ThreadDumper*, _thread_dumpers);
2193     }
2194 
2195     if (_dumper_controller != nullptr) {
2196       delete _dumper_controller;
2197       _dumper_controller = nullptr;
2198     }
2199     delete _klass_map;
2200   }
2201   int dump_seq()           { return _dump_seq; }
2202   bool is_parallel_dump()  { return _num_dumper_threads > 1; }
2203   bool can_parallel_dump(WorkerThreads* workers);
2204 
2205   VMOp_Type type() const { return VMOp_HeapDumper; }
2206   virtual bool doit_prologue();
2207   void doit();
2208   void work(uint worker_id);
2209 };
2210 
2211 VM_HeapDumper* VM_HeapDumper::_global_dumper = nullptr;
2212 DumpWriter*    VM_HeapDumper::_global_writer = nullptr;
2213 
2214 bool VM_HeapDumper::skip_operation() const {
2215   return false;
2216 }
2217 
2218 // fixes up the current dump record and writes HPROF_HEAP_DUMP_END record
2219 void DumperSupport::end_of_dump(AbstractDumpWriter* writer) {
2220   writer->finish_dump_segment();
2221 
2222   writer->write_u1(HPROF_HEAP_DUMP_END);
2223   writer->write_u4(0);
2224   writer->write_u4(0);
2225 }
2226 
2227 // writes a HPROF_LOAD_CLASS record for the class
2228 void VM_HeapDumper::do_load_class(Klass* k) {
2229   static u4 class_serial_num = 0;
2230 
2231   // len of HPROF_LOAD_CLASS record
2232   u4 remaining = 2*oopSize + 2*sizeof(u4);
2233 
2234   DumperSupport::write_header(writer(), HPROF_LOAD_CLASS, remaining);
2235 
2236   // class serial number is just a number
2237   writer()->write_u4(++class_serial_num);
2238 
2239   // class ID
2240   writer()->write_classID(k);
2241 
2242   // add the Klass* and class serial number pair
2243   dumper()->add_class_serial_number(k, class_serial_num);
2244 
2245   writer()->write_u4(STACK_TRACE_ID);
2246 
2247   // class name ID
2248   Symbol* name = k->name();
2249   writer()->write_symbolID(name);
2250 }
2251 
2252 // writes a HPROF_GC_CLASS_DUMP record for the given class
2253 void VM_HeapDumper::do_class_dump(Klass* k) {
2254   if (k->is_instance_klass()) {
2255     DumperSupport::dump_instance_class(writer(), k);
2256   } else {
2257     DumperSupport::dump_array_class(writer(), k);
2258   }
2259 }
2260 
2261 // Write a HPROF_GC_ROOT_THREAD_OBJ record for platform/carrier and mounted virtual threads.
2262 // Then walk the stack so that locals and JNI locals are dumped.
2263 void VM_HeapDumper::dump_threads() {
2264     for (int i = 0; i < _thread_dumpers_count; i++) {
2265         _thread_dumpers[i]->dump_thread_obj(writer());
2266         _thread_dumpers[i]->dump_stack_refs(writer());
2267     }
2268 }
2269 
2270 bool VM_HeapDumper::doit_prologue() {
2271   if (_gc_before_heap_dump && UseZGC) {
2272     // ZGC cannot perform a synchronous GC cycle from within the VM thread.
2273     // So ZCollectedHeap::collect_as_vm_thread() is a noop. To respect the
2274     // _gc_before_heap_dump flag a synchronous GC cycle is performed from
2275     // the caller thread in the prologue.
2276     Universe::heap()->collect(GCCause::_heap_dump);
2277   }
2278   return VM_GC_Operation::doit_prologue();
2279 }
2280 
2281 bool VM_HeapDumper::can_parallel_dump(WorkerThreads* workers) {
2282   bool can_parallel = true;
2283   uint num_active_workers = workers != nullptr ? workers->active_workers() : 0;
2284   uint num_requested_dump_threads = _num_dumper_threads;
2285   // check if we can dump in parallel based on requested and active threads
2286   if (num_active_workers <= 1 || num_requested_dump_threads <= 1) {
2287     _num_dumper_threads = 1;
2288     can_parallel = false;
2289   } else {
2290     // check if we have extra path room to accommodate segmented heap files
2291     const char* base_path = writer()->get_file_path();
2292     assert(base_path != nullptr, "sanity check");
2293     if ((strlen(base_path) + 7/*.p\d\d\d\d\0*/) >= JVM_MAXPATHLEN) {
2294       _num_dumper_threads = 1;
2295       can_parallel = false;
2296     } else {
2297       _num_dumper_threads = clamp(num_requested_dump_threads, 2U, num_active_workers);
2298     }
2299   }
2300 
2301   log_info(heapdump)("Requested dump threads %u, active dump threads %u, "
2302                      "actual dump threads %u, parallelism %s",
2303                      num_requested_dump_threads, num_active_workers,
2304                      _num_dumper_threads, can_parallel ? "true" : "false");
2305   return can_parallel;
2306 }
2307 
2308 // The VM operation that dumps the heap. The dump consists of the following
2309 // records:
2310 //
2311 //  HPROF_HEADER
2312 //  [HPROF_UTF8]*
2313 //  [HPROF_LOAD_CLASS]*
2314 //  [[HPROF_FRAME]*|HPROF_TRACE]*
2315 //  [HPROF_GC_CLASS_DUMP]*
2316 //  [HPROF_HEAP_DUMP_SEGMENT]*
2317 //  HPROF_HEAP_DUMP_END
2318 //
2319 // The HPROF_TRACE records represent the stack traces where the heap dump
2320 // is generated and a "dummy trace" record which does not include
2321 // any frames. The dummy trace record is used to be referenced as the
2322 // unknown object alloc site.
2323 //
2324 // Each HPROF_HEAP_DUMP_SEGMENT record has a length followed by sub-records.
2325 // To allow the heap dump be generated in a single pass we remember the position
2326 // of the dump length and fix it up after all sub-records have been written.
2327 // To generate the sub-records we iterate over the heap, writing
2328 // HPROF_GC_INSTANCE_DUMP, HPROF_GC_OBJ_ARRAY_DUMP, and HPROF_GC_PRIM_ARRAY_DUMP
2329 // records as we go. Once that is done we write records for some of the GC
2330 // roots.
2331 
2332 void VM_HeapDumper::doit() {
2333 
2334   CollectedHeap* ch = Universe::heap();
2335 
2336   ch->ensure_parsability(false); // must happen, even if collection does
2337                                  // not happen (e.g. due to GCLocker)
2338 
2339   if (_gc_before_heap_dump) {
2340     if (GCLocker::is_active()) {
2341       warning("GC locker is held; pre-heapdump GC was skipped");
2342     } else {
2343       ch->collect_as_vm_thread(GCCause::_heap_dump);
2344     }
2345   }
2346 
2347   // At this point we should be the only dumper active, so
2348   // the following should be safe.
2349   set_global_dumper();
2350   set_global_writer();
2351 
2352   WorkerThreads* workers = ch->safepoint_workers();
2353   if (!can_parallel_dump(workers)) {
2354     work(VMDumperWorkerId);
2355   } else {
2356     uint heap_only_dumper_threads = _num_dumper_threads - 1 /* VMDumper thread */;
2357     _dumper_controller = new (std::nothrow) DumperController(heap_only_dumper_threads);
2358     ParallelObjectIterator poi(_num_dumper_threads);
2359     _poi = &poi;
2360     workers->run_task(this, _num_dumper_threads);
2361     _poi = nullptr;
2362   }
2363 
2364   // Now we clear the global variables, so that a future dumper can run.
2365   clear_global_dumper();
2366   clear_global_writer();
2367 }
2368 
2369 // prepare DumpWriter for every parallel dump thread
2370 DumpWriter* VM_HeapDumper::create_local_writer() {
2371   char* path = NEW_RESOURCE_ARRAY(char, JVM_MAXPATHLEN);
2372   memset(path, 0, JVM_MAXPATHLEN);
2373 
2374   // generate segmented heap file path
2375   const char* base_path = writer()->get_file_path();
2376   // share global compressor, local DumpWriter is not responsible for its life cycle
2377   AbstractCompressor* compressor = writer()->compressor();
2378   int seq = Atomic::fetch_then_add(&_dump_seq, 1);
2379   os::snprintf(path, JVM_MAXPATHLEN, "%s.p%d", base_path, seq);
2380 
2381   // create corresponding writer for that
2382   DumpWriter* local_writer = new DumpWriter(path, writer()->is_overwrite(), compressor);
2383   return local_writer;
2384 }
2385 
2386 void VM_HeapDumper::work(uint worker_id) {
2387   // VM Dumper works on all non-heap data dumping and part of heap iteration.
2388   if (is_vm_dumper(worker_id)) {
2389     TraceTime timer("Dump non-objects", TRACETIME_LOG(Info, heapdump));
2390     // Write the file header - we always use 1.0.2
2391     const char* header = "JAVA PROFILE 1.0.2";
2392 
2393     // header is few bytes long - no chance to overflow int
2394     writer()->write_raw(header, strlen(header) + 1); // NUL terminated
2395     writer()->write_u4(oopSize);
2396     // timestamp is current time in ms
2397     writer()->write_u8(os::javaTimeMillis());
2398     // HPROF_UTF8 records
2399     SymbolTableDumper sym_dumper(writer());
2400     SymbolTable::symbols_do(&sym_dumper);
2401 
2402     // write HPROF_LOAD_CLASS records
2403     {
2404       LockedClassesDo locked_load_classes(&do_load_class);
2405       ClassLoaderDataGraph::classes_do(&locked_load_classes);
2406     }
2407 
2408     // write HPROF_FRAME and HPROF_TRACE records
2409     // this must be called after _klass_map is built when iterating the classes above.
2410     dump_stack_traces();
2411 
2412     // HPROF_HEAP_DUMP/HPROF_HEAP_DUMP_SEGMENT starts here
2413 
2414     // Writes HPROF_GC_CLASS_DUMP records
2415     {
2416       LockedClassesDo locked_dump_class(&do_class_dump);
2417       ClassLoaderDataGraph::classes_do(&locked_dump_class);
2418     }
2419 
2420     // HPROF_GC_ROOT_THREAD_OBJ + frames + jni locals
2421     dump_threads();
2422 
2423     // HPROF_GC_ROOT_JNI_GLOBAL
2424     JNIGlobalsDumper jni_dumper(writer());
2425     JNIHandles::oops_do(&jni_dumper);
2426     // technically not jni roots, but global roots
2427     // for things like preallocated throwable backtraces
2428     Universe::vm_global()->oops_do(&jni_dumper);
2429     // HPROF_GC_ROOT_STICKY_CLASS
2430     // These should be classes in the null class loader data, and not all classes
2431     // if !ClassUnloading
2432     StickyClassDumper class_dumper(writer());
2433     ClassLoaderData::the_null_class_loader_data()->classes_do(&class_dumper);
2434   }
2435 
2436   // Heap iteration.
2437   // writes HPROF_GC_INSTANCE_DUMP records.
2438   // After each sub-record is written check_segment_length will be invoked
2439   // to check if the current segment exceeds a threshold. If so, a new
2440   // segment is started.
2441   // The HPROF_GC_CLASS_DUMP and HPROF_GC_INSTANCE_DUMP are the vast bulk
2442   // of the heap dump.
2443   if (!is_parallel_dump()) {
2444     assert(is_vm_dumper(worker_id), "must be");
2445     // == Serial dump
2446     ResourceMark rm;
2447     TraceTime timer("Dump heap objects", TRACETIME_LOG(Info, heapdump));
2448     HeapObjectDumper obj_dumper(writer());
2449     Universe::heap()->object_iterate(&obj_dumper);
2450     writer()->finish_dump_segment();
2451     // Writes the HPROF_HEAP_DUMP_END record because merge does not happen in serial dump
2452     DumperSupport::end_of_dump(writer());
2453     writer()->flush();
2454   } else {
2455     // == Parallel dump
2456     ResourceMark rm;
2457     TraceTime timer("Dump heap objects in parallel", TRACETIME_LOG(Info, heapdump));
2458     DumpWriter* local_writer = is_vm_dumper(worker_id) ? writer() : create_local_writer();
2459     if (!local_writer->has_error()) {
2460       HeapObjectDumper obj_dumper(local_writer);
2461       _poi->object_iterate(&obj_dumper, worker_id);
2462       local_writer->finish_dump_segment();
2463       local_writer->flush();
2464     }
2465     if (is_vm_dumper(worker_id)) {
2466       _dumper_controller->wait_all_dumpers_complete();
2467     } else {
2468       _dumper_controller->dumper_complete(local_writer, writer());
2469       delete local_writer;
2470       return;
2471     }
2472   }
2473   // At this point, all fragments of the heapdump have been written to separate files.
2474   // We need to merge them into a complete heapdump and write HPROF_HEAP_DUMP_END at that time.
2475 }
2476 
2477 void VM_HeapDumper::dump_stack_traces() {
2478   // write a HPROF_TRACE record without any frames to be referenced as object alloc sites
2479   DumperSupport::write_header(writer(), HPROF_TRACE, 3 * sizeof(u4));
2480   writer()->write_u4((u4)STACK_TRACE_ID);
2481   writer()->write_u4(0);                    // thread number
2482   writer()->write_u4(0);                    // frame count
2483 
2484   // max number if every platform thread is carrier with mounted virtual thread
2485   _thread_dumpers = NEW_C_HEAP_ARRAY(ThreadDumper*, Threads::number_of_threads() * 2, mtInternal);
2486 
2487   for (JavaThreadIteratorWithHandle jtiwh; JavaThread * thread = jtiwh.next(); ) {
2488     if (ThreadDumper::should_dump_pthread(thread)) {
2489       bool add_oom_frame = is_oom_thread(thread);
2490 
2491       oop mounted_vt = thread->is_vthread_mounted() ? thread->vthread() : nullptr;
2492       if (mounted_vt != nullptr && !ThreadDumper::should_dump_vthread(mounted_vt)) {
2493         mounted_vt = nullptr;
2494       }
2495 
2496       // mounted vthread (if any)
2497       if (mounted_vt != nullptr) {
2498         ThreadDumper* thread_dumper = new ThreadDumper(ThreadDumper::ThreadType::MountedVirtual, thread, mounted_vt);
2499         _thread_dumpers[_thread_dumpers_count++] = thread_dumper;
2500         if (add_oom_frame) {
2501           thread_dumper->add_oom_frame(_oome_constructor);
2502           // we add oom frame to the VT stack, don't add it to the carrier thread stack
2503           add_oom_frame = false;
2504         }
2505         thread_dumper->init_serial_nums(&_thread_serial_num, &_frame_serial_num);
2506         thread_dumper->dump_stack_traces(writer(), _klass_map);
2507       }
2508 
2509       // platform or carrier thread
2510       ThreadDumper* thread_dumper = new ThreadDumper(ThreadDumper::ThreadType::Platform, thread, thread->threadObj());
2511       _thread_dumpers[_thread_dumpers_count++] = thread_dumper;
2512       if (add_oom_frame) {
2513         thread_dumper->add_oom_frame(_oome_constructor);
2514       }
2515       thread_dumper->init_serial_nums(&_thread_serial_num, &_frame_serial_num);
2516       thread_dumper->dump_stack_traces(writer(), _klass_map);
2517     }
2518   }
2519 }
2520 
2521 // dump the heap to given path.
2522 int HeapDumper::dump(const char* path, outputStream* out, int compression, bool overwrite, uint num_dump_threads) {
2523   assert(path != nullptr && strlen(path) > 0, "path missing");
2524 
2525   // print message in interactive case
2526   if (out != nullptr) {
2527     out->print_cr("Dumping heap to %s ...", path);
2528     timer()->start();
2529   }
2530   // create JFR event
2531   EventHeapDump event;
2532 
2533   AbstractCompressor* compressor = nullptr;
2534 
2535   if (compression > 0) {
2536     compressor = new (std::nothrow) GZipCompressor(compression);
2537 
2538     if (compressor == nullptr) {
2539       set_error("Could not allocate gzip compressor");
2540       return -1;
2541     }
2542   }
2543 
2544   DumpWriter writer(path, overwrite, compressor);
2545 
2546   if (writer.error() != nullptr) {
2547     set_error(writer.error());
2548     if (out != nullptr) {
2549       out->print_cr("Unable to create %s: %s", path,
2550         (error() != nullptr) ? error() : "reason unknown");
2551     }
2552     return -1;
2553   }
2554 
2555   // generate the segmented heap dump into separate files
2556   VM_HeapDumper dumper(&writer, _gc_before_heap_dump, _oome, num_dump_threads);
2557   VMThread::execute(&dumper);
2558 
2559   // record any error that the writer may have encountered
2560   set_error(writer.error());
2561 
2562   // For serial dump, once VM_HeapDumper completes, the whole heap dump process
2563   // is done, no further phases needed. For parallel dump, the whole heap dump
2564   // process is done in two phases
2565   //
2566   // Phase 1: Concurrent threads directly write heap data to multiple heap files.
2567   //          This is done by VM_HeapDumper, which is performed within safepoint.
2568   //
2569   // Phase 2: Merge multiple heap files into one complete heap dump file.
2570   //          This is done by DumpMerger, which is performed outside safepoint
2571   if (dumper.is_parallel_dump()) {
2572     DumpMerger merger(path, &writer, dumper.dump_seq());
2573     Thread* current_thread = Thread::current();
2574     if (current_thread->is_AttachListener_thread()) {
2575       // perform heapdump file merge operation in the current thread prevents us
2576       // from occupying the VM Thread, which in turn affects the occurrence of
2577       // GC and other VM operations.
2578       merger.do_merge();
2579     } else {
2580       // otherwise, performs it by VM thread
2581       VM_HeapDumpMerge op(&merger);
2582       VMThread::execute(&op);
2583     }
2584     set_error(writer.error());
2585   }
2586 
2587   // emit JFR event
2588   if (error() == nullptr) {
2589     event.set_destination(path);
2590     event.set_gcBeforeDump(_gc_before_heap_dump);
2591     event.set_size(writer.bytes_written());
2592     event.set_onOutOfMemoryError(_oome);
2593     event.set_overwrite(overwrite);
2594     event.set_compression(compression);
2595     event.commit();
2596   } else {
2597     log_debug(cds, heap)("Error %s while dumping heap", error());
2598   }
2599 
2600   // print message in interactive case
2601   if (out != nullptr) {
2602     timer()->stop();
2603     if (error() == nullptr) {
2604       out->print_cr("Heap dump file created [" JULONG_FORMAT " bytes in %3.3f secs]",
2605                     writer.bytes_written(), timer()->seconds());
2606     } else {
2607       out->print_cr("Dump file is incomplete: %s", writer.error());
2608     }
2609   }
2610 
2611   if (compressor != nullptr) {
2612     delete compressor;
2613   }
2614   return (writer.error() == nullptr) ? 0 : -1;
2615 }
2616 
2617 // stop timer (if still active), and free any error string we might be holding
2618 HeapDumper::~HeapDumper() {
2619   if (timer()->is_active()) {
2620     timer()->stop();
2621   }
2622   set_error(nullptr);
2623 }
2624 
2625 
2626 // returns the error string (resource allocated), or null
2627 char* HeapDumper::error_as_C_string() const {
2628   if (error() != nullptr) {
2629     char* str = NEW_RESOURCE_ARRAY(char, strlen(error())+1);
2630     strcpy(str, error());
2631     return str;
2632   } else {
2633     return nullptr;
2634   }
2635 }
2636 
2637 // set the error string
2638 void HeapDumper::set_error(char const* error) {
2639   if (_error != nullptr) {
2640     os::free(_error);
2641   }
2642   if (error == nullptr) {
2643     _error = nullptr;
2644   } else {
2645     _error = os::strdup(error);
2646     assert(_error != nullptr, "allocation failure");
2647   }
2648 }
2649 
2650 // Called by out-of-memory error reporting by a single Java thread
2651 // outside of a JVM safepoint
2652 void HeapDumper::dump_heap_from_oome() {
2653   HeapDumper::dump_heap(true);
2654 }
2655 
2656 // Called by error reporting by a single Java thread outside of a JVM safepoint,
2657 // or by heap dumping by the VM thread during a (GC) safepoint. Thus, these various
2658 // callers are strictly serialized and guaranteed not to interfere below. For more
2659 // general use, however, this method will need modification to prevent
2660 // inteference when updating the static variables base_path and dump_file_seq below.
2661 void HeapDumper::dump_heap() {
2662   HeapDumper::dump_heap(false);
2663 }
2664 
2665 void HeapDumper::dump_heap(bool oome) {
2666   static char base_path[JVM_MAXPATHLEN] = {'\0'};
2667   static uint dump_file_seq = 0;
2668   char* my_path;
2669   const int max_digit_chars = 20;
2670 
2671   const char* dump_file_name = "java_pid";
2672   const char* dump_file_ext  = HeapDumpGzipLevel > 0 ? ".hprof.gz" : ".hprof";
2673 
2674   // The dump file defaults to java_pid<pid>.hprof in the current working
2675   // directory. HeapDumpPath=<file> can be used to specify an alternative
2676   // dump file name or a directory where dump file is created.
2677   if (dump_file_seq == 0) { // first time in, we initialize base_path
2678     // Calculate potentially longest base path and check if we have enough
2679     // allocated statically.
2680     const size_t total_length =
2681                       (HeapDumpPath == nullptr ? 0 : strlen(HeapDumpPath)) +
2682                       strlen(os::file_separator()) + max_digit_chars +
2683                       strlen(dump_file_name) + strlen(dump_file_ext) + 1;
2684     if (total_length > sizeof(base_path)) {
2685       warning("Cannot create heap dump file.  HeapDumpPath is too long.");
2686       return;
2687     }
2688 
2689     bool use_default_filename = true;
2690     if (HeapDumpPath == nullptr || HeapDumpPath[0] == '\0') {
2691       // HeapDumpPath=<file> not specified
2692     } else {
2693       strcpy(base_path, HeapDumpPath);
2694       // check if the path is a directory (must exist)
2695       DIR* dir = os::opendir(base_path);
2696       if (dir == nullptr) {
2697         use_default_filename = false;
2698       } else {
2699         // HeapDumpPath specified a directory. We append a file separator
2700         // (if needed).
2701         os::closedir(dir);
2702         size_t fs_len = strlen(os::file_separator());
2703         if (strlen(base_path) >= fs_len) {
2704           char* end = base_path;
2705           end += (strlen(base_path) - fs_len);
2706           if (strcmp(end, os::file_separator()) != 0) {
2707             strcat(base_path, os::file_separator());
2708           }
2709         }
2710       }
2711     }
2712     // If HeapDumpPath wasn't a file name then we append the default name
2713     if (use_default_filename) {
2714       const size_t dlen = strlen(base_path);  // if heap dump dir specified
2715       jio_snprintf(&base_path[dlen], sizeof(base_path)-dlen, "%s%d%s",
2716                    dump_file_name, os::current_process_id(), dump_file_ext);
2717     }
2718     const size_t len = strlen(base_path) + 1;
2719     my_path = (char*)os::malloc(len, mtInternal);
2720     if (my_path == nullptr) {
2721       warning("Cannot create heap dump file.  Out of system memory.");
2722       return;
2723     }
2724     strncpy(my_path, base_path, len);
2725   } else {
2726     // Append a sequence number id for dumps following the first
2727     const size_t len = strlen(base_path) + max_digit_chars + 2; // for '.' and \0
2728     my_path = (char*)os::malloc(len, mtInternal);
2729     if (my_path == nullptr) {
2730       warning("Cannot create heap dump file.  Out of system memory.");
2731       return;
2732     }
2733     jio_snprintf(my_path, len, "%s.%d", base_path, dump_file_seq);
2734   }
2735   dump_file_seq++;   // increment seq number for next time we dump
2736 
2737   HeapDumper dumper(false /* no GC before heap dump */,
2738                     oome  /* pass along out-of-memory-error flag */);
2739   dumper.dump(my_path, tty, HeapDumpGzipLevel);
2740   os::free(my_path);
2741 }