1 /*
   2  * Copyright (c) 2004, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 package sun.jvm.hotspot.utilities;
  26 
  27 import java.io.*;
  28 import java.nio.ByteBuffer;
  29 import java.nio.ByteOrder;
  30 import java.nio.channels.*;
  31 import java.util.*;
  32 import java.util.zip.*;
  33 import sun.jvm.hotspot.debugger.*;
  34 import sun.jvm.hotspot.memory.*;
  35 import sun.jvm.hotspot.oops.*;
  36 import sun.jvm.hotspot.runtime.*;
  37 import sun.jvm.hotspot.classfile.*;
  38 
  39 import static java.nio.charset.StandardCharsets.UTF_8;
  40 
  41 /*
  42  * This class writes Java heap in hprof binary format. This format is
  43  * used by Heap Analysis Tool (HAT). The class is heavily influenced
  44  * by 'hprof_io.c' of 1.5 new hprof implementation.
  45  */
  46 
  47 /* hprof binary format: (result either written to a file or sent over
  48  * the network).
  49  *
  50  * WARNING: This format is still under development, and is subject to
  51  * change without notice.
  52  *
  53  * header     "JAVA PROFILE 1.0.2" (0-terminated)
  54  * u4         size of identifiers. Identifiers are used to represent
  55  *            UTF8 strings, objects, stack traces, etc. They usually
  56  *            have the same size as host pointers. For example, on
  57  *            Solaris and Win32, the size is 4.
  58  * u4         high word
  59  * u4         low word    number of milliseconds since 0:00 GMT, 1/1/70
  60  * [record]*  a sequence of records.
  61  *
  62  */
  63 
  64 /*
  65  *
  66  * Record format:
  67  *
  68  * u1         a TAG denoting the type of the record
  69  * u4         number of *microseconds* since the time stamp in the
  70  *            header. (wraps around in a little more than an hour)
  71  * u4         number of bytes *remaining* in the record. Note that
  72  *            this number excludes the tag and the length field itself.
  73  * [u1]*      BODY of the record (a sequence of bytes)
  74  */
  75 
  76 /*
  77  * The following TAGs are supported:
  78  *
  79  * TAG           BODY       notes
  80  *----------------------------------------------------------
  81  * HPROF_UTF8               a UTF8-encoded name
  82  *
  83  *               id         name ID
  84  *               [u1]*      UTF8 characters (no trailing zero)
  85  *
  86  * HPROF_LOAD_CLASS         a newly loaded class
  87  *
  88  *                u4        class serial number (> 0)
  89  *                id        class object ID
  90  *                u4        stack trace serial number
  91  *                id        class name ID
  92  *
  93  * HPROF_UNLOAD_CLASS       an unloading class
  94  *
  95  *                u4        class serial_number
  96  *
  97  * HPROF_FRAME              a Java stack frame
  98  *
  99  *                id        stack frame ID
 100  *                id        method name ID
 101  *                id        method signature ID
 102  *                id        source file name ID
 103  *                u4        class serial number
 104  *                i4        line number. >0: normal
 105  *                                       -1: unknown
 106  *                                       -2: compiled method
 107  *                                       -3: native method
 108  *
 109  * HPROF_TRACE              a Java stack trace
 110  *
 111  *               u4         stack trace serial number
 112  *               u4         thread serial number
 113  *               u4         number of frames
 114  *               [id]*      stack frame IDs
 115  *
 116  *
 117  * HPROF_ALLOC_SITES        a set of heap allocation sites, obtained after GC
 118  *
 119  *               u2         flags 0x0001: incremental vs. complete
 120  *                                0x0002: sorted by allocation vs. live
 121  *                                0x0004: whether to force a GC
 122  *               u4         cutoff ratio
 123  *               u4         total live bytes
 124  *               u4         total live instances
 125  *               u8         total bytes allocated
 126  *               u8         total instances allocated
 127  *               u4         number of sites that follow
 128  *               [u1        is_array: 0:  normal object
 129  *                                    2:  object array
 130  *                                    4:  boolean array
 131  *                                    5:  char array
 132  *                                    6:  float array
 133  *                                    7:  double array
 134  *                                    8:  byte array
 135  *                                    9:  short array
 136  *                                    10: int array
 137  *                                    11: long array
 138  *                u4        class serial number (may be zero during startup)
 139  *                u4        stack trace serial number
 140  *                u4        number of bytes alive
 141  *                u4        number of instances alive
 142  *                u4        number of bytes allocated
 143  *                u4]*      number of instance allocated
 144  *
 145  * HPROF_START_THREAD       a newly started thread.
 146  *
 147  *               u4         thread serial number (> 0)
 148  *               id         thread object ID
 149  *               u4         stack trace serial number
 150  *               id         thread name ID
 151  *               id         thread group name ID
 152  *               id         thread group parent name ID
 153  *
 154  * HPROF_END_THREAD         a terminating thread.
 155  *
 156  *               u4         thread serial number
 157  *
 158  * HPROF_HEAP_SUMMARY       heap summary
 159  *
 160  *               u4         total live bytes
 161  *               u4         total live instances
 162  *               u8         total bytes allocated
 163  *               u8         total instances allocated
 164  *
 165  * HPROF_HEAP_DUMP          denote a heap dump
 166  *
 167  *               [heap dump sub-records]*
 168  *
 169  *                          There are four kinds of heap dump sub-records:
 170  *
 171  *               u1         sub-record type
 172  *
 173  *               HPROF_GC_ROOT_UNKNOWN         unknown root
 174  *
 175  *                          id         object ID
 176  *
 177  *               HPROF_GC_ROOT_THREAD_OBJ      thread object
 178  *
 179  *                          id         thread object ID  (may be 0 for a
 180  *                                     thread newly attached through JNI)
 181  *                          u4         thread sequence number
 182  *                          u4         stack trace sequence number
 183  *
 184  *               HPROF_GC_ROOT_JNI_GLOBAL      JNI global ref root
 185  *
 186  *                          id         object ID
 187  *                          id         JNI global ref ID
 188  *
 189  *               HPROF_GC_ROOT_JNI_LOCAL       JNI local ref
 190  *
 191  *                          id         object ID
 192  *                          u4         thread serial number
 193  *                          u4         frame # in stack trace (-1 for empty)
 194  *
 195  *               HPROF_GC_ROOT_JAVA_FRAME      Java stack frame
 196  *
 197  *                          id         object ID
 198  *                          u4         thread serial number
 199  *                          u4         frame # in stack trace (-1 for empty)
 200  *
 201  *               HPROF_GC_ROOT_NATIVE_STACK    Native stack
 202  *
 203  *                          id         object ID
 204  *                          u4         thread serial number
 205  *
 206  *               HPROF_GC_ROOT_STICKY_CLASS    System class
 207  *
 208  *                          id         object ID
 209  *
 210  *               HPROF_GC_ROOT_THREAD_BLOCK    Reference from thread block
 211  *
 212  *                          id         object ID
 213  *                          u4         thread serial number
 214  *
 215  *               HPROF_GC_ROOT_MONITOR_USED    Busy monitor
 216  *
 217  *                          id         object ID
 218  *
 219  *               HPROF_GC_CLASS_DUMP           dump of a class object
 220  *
 221  *                          id         class object ID
 222  *                          u4         stack trace serial number
 223  *                          id         super class object ID
 224  *                          id         class loader object ID
 225  *                          id         signers object ID
 226  *                          id         protection domain object ID
 227  *                          id         reserved
 228  *                          id         reserved
 229  *
 230  *                          u4         instance size (in bytes)
 231  *
 232  *                          u2         size of constant pool
 233  *                          [u2,       constant pool index,
 234  *                           ty,       type
 235  *                                     2:  object
 236  *                                     4:  boolean
 237  *                                     5:  char
 238  *                                     6:  float
 239  *                                     7:  double
 240  *                                     8:  byte
 241  *                                     9:  short
 242  *                                     10: int
 243  *                                     11: long
 244  *                           vl]*      and value
 245  *
 246  *                          u2         number of static fields
 247  *                          [id,       static field name,
 248  *                           ty,       type,
 249  *                           vl]*      and value
 250  *
 251  *                          u2         number of inst. fields (not inc. super)
 252  *                          [id,       instance field name,
 253  *                           ty]*      type
 254  *
 255  *               HPROF_GC_INSTANCE_DUMP        dump of a normal object
 256  *
 257  *                          id         object ID
 258  *                          u4         stack trace serial number
 259  *                          id         class object ID
 260  *                          u4         number of bytes that follow
 261  *                          [vl]*      instance field values (class, followed
 262  *                                     by super, super's super ...)
 263  *
 264  *               HPROF_GC_OBJ_ARRAY_DUMP       dump of an object array
 265  *
 266  *                          id         array object ID
 267  *                          u4         stack trace serial number
 268  *                          u4         number of elements
 269  *                          id         array class ID
 270  *                          [id]*      elements
 271  *
 272  *               HPROF_GC_PRIM_ARRAY_DUMP      dump of a primitive array
 273  *
 274  *                          id         array object ID
 275  *                          u4         stack trace serial number
 276  *                          u4         number of elements
 277  *                          u1         element type
 278  *                                     4:  boolean array
 279  *                                     5:  char array
 280  *                                     6:  float array
 281  *                                     7:  double array
 282  *                                     8:  byte array
 283  *                                     9:  short array
 284  *                                     10: int array
 285  *                                     11: long array
 286  *                          [u1]*      elements
 287  *
 288  * HPROF_CPU_SAMPLES        a set of sample traces of running threads
 289  *
 290  *                u4        total number of samples
 291  *                u4        # of traces
 292  *               [u4        # of samples
 293  *                u4]*      stack trace serial number
 294  *
 295  * HPROF_CONTROL_SETTINGS   the settings of on/off switches
 296  *
 297  *                u4        0x00000001: alloc traces on/off
 298  *                          0x00000002: cpu sampling on/off
 299  *                u2        stack trace depth
 300  *
 301  *
 302  * A heap dump can optionally be generated as a sequence of heap dump
 303  * segments. This sequence is terminated by an end record. The additional
 304  * tags allowed by format "JAVA PROFILE 1.0.2" are:
 305  *
 306  * HPROF_HEAP_DUMP_SEGMENT  denote a heap dump segment
 307  *
 308  *               [heap dump sub-records]*
 309  *               The same sub-record types allowed by HPROF_HEAP_DUMP
 310  *
 311  * HPROF_HEAP_DUMP_END      denotes the end of a heap dump
 312  *
 313  */
 314 
 315 public class HeapHprofBinWriter extends AbstractHeapGraphWriter {
 316 
 317     // Record which Symbol names have been dumped already.
 318     private HashSet<Symbol> names;
 319 
 320     private static final long HPROF_SEGMENTED_HEAP_DUMP_THRESHOLD = 2L * 0x40000000;
 321 
 322     // The approximate size of a heap segment. Used to calculate when to create
 323     // a new segment.
 324     private static final long HPROF_SEGMENTED_HEAP_DUMP_SEGMENT_SIZE = 1L * 0x40000000;
 325 
 326     // hprof binary file header
 327     private static final String HPROF_HEADER_1_0_2 = "JAVA PROFILE 1.0.2";
 328 
 329     // constants in enum HprofTag
 330     private static final int HPROF_UTF8             = 0x01;
 331     private static final int HPROF_LOAD_CLASS       = 0x02;
 332     private static final int HPROF_UNLOAD_CLASS     = 0x03;
 333     private static final int HPROF_FRAME            = 0x04;
 334     private static final int HPROF_TRACE            = 0x05;
 335     private static final int HPROF_ALLOC_SITES      = 0x06;
 336     private static final int HPROF_HEAP_SUMMARY     = 0x07;
 337     private static final int HPROF_START_THREAD     = 0x0A;
 338     private static final int HPROF_END_THREAD       = 0x0B;
 339     private static final int HPROF_HEAP_DUMP        = 0x0C;
 340     private static final int HPROF_CPU_SAMPLES      = 0x0D;
 341     private static final int HPROF_CONTROL_SETTINGS = 0x0E;
 342 
 343     // 1.0.2 record types
 344     private static final int HPROF_HEAP_DUMP_SEGMENT = 0x1C;
 345     private static final int HPROF_HEAP_DUMP_END     = 0x2C;
 346 
 347     // Heap dump constants
 348     // constants in enum HprofGcTag
 349     private static final int HPROF_GC_ROOT_UNKNOWN       = 0xFF;
 350     private static final int HPROF_GC_ROOT_JNI_GLOBAL    = 0x01;
 351     private static final int HPROF_GC_ROOT_JNI_LOCAL     = 0x02;
 352     private static final int HPROF_GC_ROOT_JAVA_FRAME    = 0x03;
 353     private static final int HPROF_GC_ROOT_NATIVE_STACK  = 0x04;
 354     private static final int HPROF_GC_ROOT_STICKY_CLASS  = 0x05;
 355     private static final int HPROF_GC_ROOT_THREAD_BLOCK  = 0x06;
 356     private static final int HPROF_GC_ROOT_MONITOR_USED  = 0x07;
 357     private static final int HPROF_GC_ROOT_THREAD_OBJ    = 0x08;
 358     private static final int HPROF_GC_CLASS_DUMP         = 0x20;
 359     private static final int HPROF_GC_INSTANCE_DUMP      = 0x21;
 360     private static final int HPROF_GC_OBJ_ARRAY_DUMP     = 0x22;
 361     private static final int HPROF_GC_PRIM_ARRAY_DUMP    = 0x23;
 362 
 363     // constants in enum HprofType
 364     private static final int HPROF_ARRAY_OBJECT  = 1;
 365     private static final int HPROF_NORMAL_OBJECT = 2;
 366     private static final int HPROF_BOOLEAN       = 4;
 367     private static final int HPROF_CHAR          = 5;
 368     private static final int HPROF_FLOAT         = 6;
 369     private static final int HPROF_DOUBLE        = 7;
 370     private static final int HPROF_BYTE          = 8;
 371     private static final int HPROF_SHORT         = 9;
 372     private static final int HPROF_INT           = 10;
 373     private static final int HPROF_LONG          = 11;
 374 
 375     // Java type codes
 376     private static final int JVM_SIGNATURE_BOOLEAN = 'Z';
 377     private static final int JVM_SIGNATURE_CHAR    = 'C';
 378     private static final int JVM_SIGNATURE_BYTE    = 'B';
 379     private static final int JVM_SIGNATURE_SHORT   = 'S';
 380     private static final int JVM_SIGNATURE_INT     = 'I';
 381     private static final int JVM_SIGNATURE_LONG    = 'J';
 382     private static final int JVM_SIGNATURE_FLOAT   = 'F';
 383     private static final int JVM_SIGNATURE_DOUBLE  = 'D';
 384     private static final int JVM_SIGNATURE_ARRAY   = '[';
 385     private static final int JVM_SIGNATURE_CLASS   = 'L';
 386 
 387     private static final long MAX_U4_VALUE = 0xFFFFFFFFL;
 388     int serialNum = 1;
 389 
 390     public HeapHprofBinWriter() {
 391         this.KlassMap = new ArrayList<Klass>();
 392         this.names = new HashSet<Symbol>();
 393         this.gzLevel = 0;
 394     }
 395 
 396     public HeapHprofBinWriter(int gzLevel) {
 397         this.KlassMap = new ArrayList<Klass>();
 398         this.names = new HashSet<Symbol>();
 399         this.gzLevel = gzLevel;
 400     }
 401 
 402     public synchronized void write(String fileName) throws IOException {
 403         VM vm = VM.getVM();
 404 
 405         // Check whether we should dump the heap as segments
 406         useSegmentedHeapDump = isCompression() ||
 407                 (vm.getUniverse().heap().used() > HPROF_SEGMENTED_HEAP_DUMP_THRESHOLD);
 408 
 409         // open file stream and create buffered data output stream
 410         fos = new FileOutputStream(fileName);
 411         hprofBufferedOut = new BufferedOutputStream(fos);
 412         if (useSegmentedHeapDump) {
 413             if (isCompression()) {
 414                 hprofBufferedOut = new GZIPOutputStream(hprofBufferedOut) {
 415                     {
 416                         this.def.setLevel(gzLevel);
 417                     }
 418                 };
 419             }
 420         }
 421         out = new DataOutputStream(hprofBufferedOut);
 422         dbg = vm.getDebugger();
 423         objectHeap = vm.getObjectHeap();
 424 
 425         OBJ_ID_SIZE = (int) vm.getOopSize();
 426 
 427         BOOLEAN_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_BOOLEAN);
 428         BYTE_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_BYTE);
 429         CHAR_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_CHAR);
 430         SHORT_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_SHORT);
 431         INT_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_INT);
 432         LONG_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_LONG);
 433         FLOAT_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_FLOAT);
 434         DOUBLE_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_DOUBLE);
 435         OBJECT_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_OBJECT);
 436 
 437         BOOLEAN_SIZE = objectHeap.getBooleanSize();
 438         BYTE_SIZE = objectHeap.getByteSize();
 439         CHAR_SIZE = objectHeap.getCharSize();
 440         SHORT_SIZE = objectHeap.getShortSize();
 441         INT_SIZE = objectHeap.getIntSize();
 442         LONG_SIZE = objectHeap.getLongSize();
 443         FLOAT_SIZE = objectHeap.getFloatSize();
 444         DOUBLE_SIZE = objectHeap.getDoubleSize();
 445 
 446         // hprof bin format header
 447         writeFileHeader();
 448 
 449         // dummy stack trace without any frames so that
 450         // HAT can be run without -stack false option
 451         writeDummyTrace();
 452 
 453         // hprof UTF-8 symbols section
 454         writeSymbols();
 455 
 456         // HPROF_LOAD_CLASS records for all classes
 457         writeClasses();
 458 
 459         // write HPROF_FRAME and HPROF_TRACE records
 460         dumpStackTraces();
 461 
 462         // write CLASS_DUMP records
 463         writeClassDumpRecords();
 464 
 465         // this will write heap data into the buffer stream
 466         super.write();
 467 
 468         // flush buffer stream.
 469         out.flush();
 470         if (!useSegmentedHeapDump) {
 471             fillInHeapRecordLength();
 472         } else {
 473             // Write heap segment-end record
 474             out.writeByte((byte) HPROF_HEAP_DUMP_END);
 475             out.writeInt(0);
 476             out.writeInt(0);
 477         }
 478         // flush buffer stream and throw it.
 479         out.flush();
 480         out.close();
 481         out = null;
 482         hprofBufferedOut = null;
 483         currentSegmentStart = 0;
 484     }
 485 
 486     protected int calculateOopDumpRecordSize(Oop oop) throws IOException {
 487         if (oop instanceof TypeArray taOop) {
 488             return calculatePrimitiveArrayDumpRecordSize(taOop);
 489         } else if (oop instanceof ObjArray oaOop) {
 490             Klass klass = oop.getKlass();
 491             ObjArrayKlass oak = (ObjArrayKlass) klass;
 492             Klass bottomType = oak.getBottomKlass();
 493             if (bottomType instanceof InstanceKlass ||
 494                 bottomType instanceof TypeArrayKlass) {
 495                 return calculateObjectArrayDumpRecordSize(oaOop);
 496             } else {
 497                 // Internal object, nothing to write.
 498                 return 0;
 499             }
 500         } else if (oop instanceof Instance instance) {
 501             Klass klass = instance.getKlass();
 502             Symbol name = klass.getName();
 503             if (name.equals(javaLangClass)) {
 504                 return calculateClassInstanceDumpRecordSize(instance);
 505             }
 506             return calculateInstanceDumpRecordSize(instance);
 507         } else {
 508             // not-a-Java-visible oop
 509             return 0;
 510         }
 511     }
 512 
 513     private int calculateInstanceDumpRecordSize(Instance instance) {
 514         Klass klass = instance.getKlass();
 515         if (klass.getClassLoaderData() == null) {
 516             // Ignoring this object since the corresponding Klass is not loaded.
 517             // Might be a dormant archive object.
 518             return 0;
 519         }
 520 
 521         ClassData cd = classDataCache.get(klass);
 522         if (Assert.ASSERTS_ENABLED) {
 523             Assert.that(cd != null, "can not get class data for " + klass.getName().asString() + klass.getAddress());
 524         }
 525         List<Field> fields = cd.fields;
 526         return BYTE_SIZE + OBJ_ID_SIZE * 2 + INT_SIZE * 2 + getSizeForFields(fields);
 527     }
 528 
 529     private int calculateClassDumpRecordSize(Klass k) {
 530         // tag + javaMirror + DUMMY_STACK_TRACE_ID + super
 531         int size = BYTE_SIZE + INT_SIZE + OBJ_ID_SIZE * 2;
 532         if (k instanceof InstanceKlass ik) {
 533             List<Field> fields = getInstanceFields(ik);
 534             List<Field> declaredFields = ik.getImmediateFields();
 535             List<Field> staticFields = new ArrayList<>();
 536             List<Field> instanceFields = new ArrayList<>();
 537             Iterator<Field> itr = null;
 538             // loader + signer + protectionDomain + 2 reserved + fieldSize + cpool entris number
 539             size += OBJ_ID_SIZE * 5 + INT_SIZE + SHORT_SIZE;
 540             for (itr = declaredFields.iterator(); itr.hasNext();) {
 541                 Field field = itr.next();
 542                 if (field.isStatic()) {
 543                     staticFields.add(field);
 544                 } else {
 545                     instanceFields.add(field);
 546                 }
 547             }
 548             // size of static field descriptors
 549             size += calculateFieldDescriptorsDumpRecordSize(staticFields, ik);
 550             // size of instance field descriptors
 551             size += calculateFieldDescriptorsDumpRecordSize(instanceFields, null);
 552         } else {
 553             size += OBJ_ID_SIZE * 5  + INT_SIZE + SHORT_SIZE * 3;
 554         }
 555         return size;
 556     }
 557 
 558     private int calculateFieldDescriptorsDumpRecordSize(List<Field> fields, InstanceKlass ik) {
 559         int size = 0;
 560         size += SHORT_SIZE;
 561         for (Field field : fields) {
 562             size += OBJ_ID_SIZE + BYTE_SIZE;
 563             // ik == null for instance fields
 564             if (ik != null) {
 565                 // static field
 566                 size += getSizeForField(field);
 567             }
 568         }
 569         return size;
 570     }
 571 
 572     private int calculateClassInstanceDumpRecordSize(Instance instance) {
 573         Klass reflectedKlass = java_lang_Class.asKlass(instance);
 574         // Dump instance record only for primitive type Class objects.
 575         // All other Class objects are covered by writeClassDumpRecords.
 576         if (reflectedKlass == null) {
 577             return calculateInstanceDumpRecordSize(instance);
 578         }
 579         return 0;
 580     }
 581 
 582     private int calculateObjectArrayDumpRecordSize(ObjArray array) {
 583         int headerSize = getArrayHeaderSize(true);
 584         final int length = calculateArrayMaxLength(array.getLength(),
 585                 headerSize,
 586                 OBJ_ID_SIZE,
 587                 "Object");
 588         return headerSize + length * OBJ_ID_SIZE;
 589     }
 590 
 591     private int calculatePrimitiveArrayDumpRecordSize(TypeArray array) throws IOException {
 592         int headerSize = getArrayHeaderSize(false);
 593         TypeArrayKlass tak = (TypeArrayKlass) array.getKlass();
 594         final int type = tak.getElementType();
 595         final String typeName = tak.getElementTypeName();
 596         final long typeSize = getSizeForType(type);
 597         final int length = calculateArrayMaxLength(array.getLength(),
 598                                                    headerSize,
 599                                                    typeSize,
 600                                                    typeName);
 601         return headerSize + (int)typeSize * length;
 602     }
 603 
 604     @Override
 605     protected void writeHeapRecordPrologue(int size) throws IOException {
 606         if (size == 0 || currentSegmentStart > 0) {
 607             return;
 608         }
 609         // write heap data header
 610         if (useSegmentedHeapDump) {
 611             out.writeByte((byte)HPROF_HEAP_DUMP_SEGMENT);
 612             out.writeInt(0);
 613             out.writeInt(size);
 614         } else {
 615             out.writeByte((byte)HPROF_HEAP_DUMP);
 616             out.writeInt(0);
 617             // We must flush all data to the file before reading the current file position.
 618             out.flush();
 619             // record the current position in file, it will be use for calculating the size of written data
 620             currentSegmentStart = fos.getChannel().position();
 621             // write dummy zero for length
 622             out.writeInt(0);
 623         }
 624     }
 625 
 626     private void fillInHeapRecordLength() throws IOException {
 627         assert !useSegmentedHeapDump : "fillInHeapRecordLength is not supported for segmented heap dump";
 628 
 629         // now get the current position to calculate length
 630         long dumpEnd = fos.getChannel().position();
 631 
 632         // calculate the length of heap data
 633         long dumpLenLong = (dumpEnd - currentSegmentStart - 4L);
 634 
 635         // Check length boundary, overflow could happen but is _very_ unlikely
 636         if (dumpLenLong >= (4L * 0x40000000)) {
 637             throw new RuntimeException("Heap segment size overflow.");
 638         }
 639 
 640         // Save the current position
 641         long currentPosition = fos.getChannel().position();
 642 
 643         // seek the position to write length
 644         fos.getChannel().position(currentSegmentStart);
 645 
 646         // write length
 647         int dumpLen = (int) dumpLenLong;
 648         byte[] lenBytes = genByteArrayFromInt(dumpLen);
 649         fos.write(lenBytes);
 650 
 651         //Reset to previous current position
 652         fos.getChannel().position(currentPosition);
 653     }
 654 
 655     // get the size in bytes for the requested type
 656     private int getSizeForType(int type) throws IOException {
 657         switch (type) {
 658             case TypeArrayKlass.T_BOOLEAN:
 659                 return BOOLEAN_SIZE;
 660             case TypeArrayKlass.T_INT:
 661                 return INT_SIZE;
 662             case TypeArrayKlass.T_CHAR:
 663                 return CHAR_SIZE;
 664             case TypeArrayKlass.T_SHORT:
 665                 return SHORT_SIZE;
 666             case TypeArrayKlass.T_BYTE:
 667                 return BYTE_SIZE;
 668             case TypeArrayKlass.T_LONG:
 669                 return LONG_SIZE;
 670             case TypeArrayKlass.T_FLOAT:
 671                 return FLOAT_SIZE;
 672             case TypeArrayKlass.T_DOUBLE:
 673                 return DOUBLE_SIZE;
 674             default:
 675                 throw new RuntimeException(
 676                     "Should not reach here: Unknown type: " + type);
 677          }
 678     }
 679 
 680     private int getArrayHeaderSize(boolean isObjectAarray) {
 681         return isObjectAarray?
 682             (BYTE_SIZE + 2 * INT_SIZE + 2 * OBJ_ID_SIZE):
 683             (2 * BYTE_SIZE + 2 * INT_SIZE + OBJ_ID_SIZE);
 684     }
 685 
 686     // Check if we need to truncate an array.
 687     // The limitation is that the size of "heap dump" or "heap dump segment" must be <= MAX_U4_VALUE.
 688     private int calculateArrayMaxLength(long originalArrayLength,
 689                                         int headerSize,
 690                                         long typeSize,
 691                                         String typeName) {
 692 
 693         long length = originalArrayLength;
 694 
 695         long originalLengthInBytes = originalArrayLength * typeSize;
 696 
 697         // Calculate the max bytes we can use.
 698         long maxBytes = MAX_U4_VALUE - headerSize;
 699 
 700         if (originalLengthInBytes > maxBytes) {
 701             length = maxBytes/typeSize;
 702             System.err.println("WARNING: Cannot dump array of type " + typeName
 703                                + " with length " + originalArrayLength
 704                                + "; truncating to length " + length);
 705         }
 706         return (int) length;
 707     }
 708 
 709     private void writeClassDumpRecords() throws IOException {
 710         ClassLoaderDataGraph cldGraph = VM.getVM().getClassLoaderDataGraph();
 711         try {
 712              cldGraph.classesDo(new ClassLoaderDataGraph.ClassVisitor() {
 713                             public void visit(Klass k) {
 714                                 try {
 715                                     writeHeapRecordPrologue(calculateClassDumpRecordSize(k));
 716                                     writeClassDumpRecord(k);
 717                                     writeHeapRecordEpilogue();
 718                                 } catch (IOException e) {
 719                                     throw new RuntimeException(e);
 720                                 }
 721                             }
 722                         });
 723         } catch (RuntimeException re) {
 724             handleRuntimeException(re);
 725         }
 726     }
 727 
 728     protected void writeClass(Instance instance) throws IOException {
 729         Klass reflectedKlass = java_lang_Class.asKlass(instance);
 730         // dump instance record only for primitive type Class objects.
 731         // all other Class objects are covered by writeClassDumpRecords.
 732         if (reflectedKlass == null) {
 733             writeInstance(instance);
 734         }
 735     }
 736 
 737     private void writeClassDumpRecord(Klass k) throws IOException {
 738         out.writeByte((byte)HPROF_GC_CLASS_DUMP);
 739         writeObjectID(k.getJavaMirror());
 740         out.writeInt(DUMMY_STACK_TRACE_ID);
 741         Klass superKlass = k.getJavaSuper();
 742         if (superKlass != null) {
 743             writeObjectID(superKlass.getJavaMirror());
 744         } else {
 745             writeObjectID(null);
 746         }
 747 
 748         if (k instanceof InstanceKlass) {
 749             InstanceKlass ik = (InstanceKlass) k;
 750             writeObjectID(ik.getClassLoader());
 751             writeObjectID(null);  // ik.getJavaMirror().getSigners());
 752             writeObjectID(null);  // ik.getJavaMirror().getProtectionDomain());
 753             // two reserved id fields
 754             writeObjectID(null);
 755             writeObjectID(null);
 756             List<Field> fields = getInstanceFields(ik);
 757             int instSize = getSizeForFields(fields);
 758             classDataCache.put(ik, new ClassData(instSize, fields));
 759             out.writeInt(instSize);
 760 
 761             // For now, ignore constant pool - HAT ignores too!
 762             // output number of cp entries as zero.
 763             out.writeShort((short) 0);
 764 
 765             List<Field> declaredFields = ik.getImmediateFields();
 766             List<Field> staticFields = new ArrayList<>();
 767             List<Field> instanceFields = new ArrayList<>();
 768             Iterator<Field> itr = null;
 769             for (itr = declaredFields.iterator(); itr.hasNext();) {
 770                 Field field = itr.next();
 771                 if (field.isStatic()) {
 772                     staticFields.add(field);
 773                 } else {
 774                     instanceFields.add(field);
 775                 }
 776             }
 777 
 778             // dump static field descriptors
 779             writeFieldDescriptors(staticFields, ik);
 780 
 781             // dump instance field descriptors
 782             writeFieldDescriptors(instanceFields, null);
 783         } else {
 784             if (k instanceof ObjArrayKlass) {
 785                 ObjArrayKlass oak = (ObjArrayKlass) k;
 786                 Klass bottomKlass = oak.getBottomKlass();
 787                 if (bottomKlass instanceof InstanceKlass) {
 788                     InstanceKlass ik = (InstanceKlass) bottomKlass;
 789                     writeObjectID(ik.getClassLoader());
 790                     writeObjectID(null); // ik.getJavaMirror().getSigners());
 791                     writeObjectID(null); // ik.getJavaMirror().getProtectionDomain());
 792                 } else {
 793                     writeObjectID(null);
 794                     writeObjectID(null);
 795                     writeObjectID(null);
 796                 }
 797             } else {
 798                 writeObjectID(null);
 799                 writeObjectID(null);
 800                 writeObjectID(null);
 801             }
 802             // two reserved id fields
 803             writeObjectID(null);
 804             writeObjectID(null);
 805             // write zero instance size -- as instance size
 806             // is variable for arrays.
 807             out.writeInt(0);
 808             // no constant pool for array klasses
 809             out.writeShort((short) 0);
 810             // no static fields for array klasses
 811             out.writeShort((short) 0);
 812             // no instance fields for array klasses
 813             out.writeShort((short) 0);
 814         }
 815     }
 816 
 817     private void dumpStackTraces() throws IOException {
 818         // write a HPROF_TRACE record without any frames to be referenced as object alloc sites
 819         writeHeader(HPROF_TRACE, 3 * INT_SIZE );
 820         out.writeInt(DUMMY_STACK_TRACE_ID);
 821         out.writeInt(0);                    // thread number
 822         out.writeInt(0);                    // frame count
 823 
 824         int frameSerialNum = 0;
 825         int numThreads = 0;
 826         Threads threads = VM.getVM().getThreads();
 827         for (int i = 0; i < threads.getNumberOfThreads(); i++) {
 828             JavaThread thread = threads.getJavaThreadAt(i);
 829             Oop threadObj = thread.getThreadObj();
 830             if (threadObj != null && !thread.isExiting() && !thread.isHiddenFromExternalView()) {
 831 
 832                 // dump thread stack trace
 833                 ThreadStackTrace st = new ThreadStackTrace(thread);
 834                 st.dumpStack(-1);
 835                 numThreads++;
 836 
 837                 // write HPROF_FRAME records for this thread's stack trace
 838                 int depth = st.getStackDepth();
 839                 int threadFrameStart = frameSerialNum;
 840                 for (int j=0; j < depth; j++) {
 841                     StackFrameInfo frame = st.stackFrameAt(j);
 842                     Method m = frame.getMethod();
 843                     int classSerialNum = KlassMap.indexOf(m.getMethodHolder()) + 1;
 844                     // the class serial number starts from 1
 845                     assert classSerialNum > 0:"class not found";
 846                     dumpStackFrame(++frameSerialNum, classSerialNum, m, frame.getBCI());
 847                 }
 848 
 849                 // write HPROF_TRACE record for one thread
 850                 writeHeader(HPROF_TRACE, 3 * INT_SIZE + depth * OBJ_ID_SIZE);
 851                 int stackSerialNum = numThreads + DUMMY_STACK_TRACE_ID;
 852                 out.writeInt(stackSerialNum);      // stack trace serial number
 853                 out.writeInt(numThreads);          // thread serial number
 854                 out.writeInt(depth);               // frame count
 855                 for (int j=1; j <= depth; j++) {
 856                     writeObjectID(threadFrameStart + j);
 857                 }
 858             }
 859         }
 860     }
 861 
 862     private void dumpStackFrame(int frameSN, int classSN, Method m, int bci) throws IOException {
 863         int lineNumber;
 864         if (m.isNative()) {
 865             lineNumber = -3; // native frame
 866         } else {
 867             lineNumber = m.getLineNumberFromBCI(bci);
 868         }
 869         // First dump UTF8 if needed
 870         writeSymbol(m.getName());                              // method's name
 871         writeSymbol(m.getSignature());                         // method's signature
 872         writeSymbol(m.getMethodHolder().getSourceFileName());  // source file name
 873         // Then write FRAME descriptor
 874         writeHeader(HPROF_FRAME, 4 * OBJ_ID_SIZE + 2 * INT_SIZE);
 875         writeObjectID(frameSN);                                  // frame serial number
 876         writeSymbolID(m.getName());                              // method's name
 877         writeSymbolID(m.getSignature());                         // method's signature
 878         writeSymbolID(m.getMethodHolder().getSourceFileName());  // source file name
 879         out.writeInt(classSN);                                   // class serial number
 880         out.writeInt(lineNumber);                                // line number
 881     }
 882 
 883     protected void writeJavaThread(JavaThread jt, int index) throws IOException {
 884         int size = BYTE_SIZE + OBJ_ID_SIZE + INT_SIZE * 2;
 885         writeHeapRecordPrologue(size);
 886         out.writeByte((byte) HPROF_GC_ROOT_THREAD_OBJ);
 887         writeObjectID(jt.getThreadObj());
 888         out.writeInt(index);
 889         out.writeInt(DUMMY_STACK_TRACE_ID);
 890         writeLocalJNIHandles(jt, index);
 891 
 892         int depth = 0;
 893         var jvf = jt.getLastJavaVFrameDbg();
 894         while (jvf != null) {
 895             writeStackRefs(index, depth, jvf.getLocals());
 896             writeStackRefs(index, depth, jvf.getExpressions());
 897 
 898             depth++;
 899             jvf = jvf.javaSender();
 900         }
 901     }
 902 
 903     protected void writeLocalJNIHandles(JavaThread jt, int index) throws IOException {
 904         final int threadIndex = index;
 905         JNIHandleBlock blk = jt.activeHandles();
 906         if (blk != null) {
 907             try {
 908                 blk.oopsDo(new AddressVisitor() {
 909                            public void visitAddress(Address handleAddr) {
 910                                try {
 911                                    if (handleAddr != null) {
 912                                        OopHandle oopHandle = handleAddr.getOopHandleAt(0);
 913                                        Oop oop = objectHeap.newOop(oopHandle);
 914                                        // exclude JNI handles hotspot internal objects
 915                                        if (oop != null && isJavaVisible(oop)) {
 916                                            int size = BYTE_SIZE + OBJ_ID_SIZE + INT_SIZE * 2;
 917                                            writeHeapRecordPrologue(size);
 918                                            out.writeByte((byte) HPROF_GC_ROOT_JNI_LOCAL);
 919                                            writeObjectID(oop);
 920                                            out.writeInt(threadIndex);
 921                                            out.writeInt(EMPTY_FRAME_DEPTH);
 922                                        }
 923                                    }
 924                                } catch (IOException exp) {
 925                                    throw new RuntimeException(exp);
 926                                }
 927                            }
 928                            public void visitCompOopAddress(Address handleAddr) {
 929                              throw new RuntimeException(
 930                                    " Should not reach here. JNIHandles are not compressed \n");
 931                            }
 932                        });
 933             } catch (RuntimeException re) {
 934                 handleRuntimeException(re);
 935             }
 936         }
 937     }
 938 
 939     protected void writeStackRefs(int threadIndex, int frameIndex, StackValueCollection values) throws IOException {
 940         for (int index = 0; index < values.size(); index++) {
 941             if (values.get(index).getType() == BasicType.getTObject()) {
 942                 OopHandle oopHandle = values.oopHandleAt(index);
 943                 Oop oop = objectHeap.newOop(oopHandle);
 944                 if (oop != null) {
 945                     int size = BYTE_SIZE + OBJ_ID_SIZE + INT_SIZE * 2;
 946                     writeHeapRecordPrologue(size);
 947                     out.writeByte((byte) HPROF_GC_ROOT_JAVA_FRAME);
 948                     writeObjectID(oop);
 949                     out.writeInt(threadIndex);
 950                     out.writeInt(frameIndex);
 951                 }
 952             }
 953         }
 954     }
 955 
 956     protected void writeGlobalJNIHandle(Address handleAddr) throws IOException {
 957         OopHandle oopHandle = handleAddr.getOopHandleAt(0);
 958         Oop oop = objectHeap.newOop(oopHandle);
 959         // exclude JNI handles of hotspot internal objects
 960         if (oop != null && isJavaVisible(oop)) {
 961             int size = BYTE_SIZE + OBJ_ID_SIZE * 2;
 962             writeHeapRecordPrologue(size);
 963             out.writeByte((byte) HPROF_GC_ROOT_JNI_GLOBAL);
 964             writeObjectID(oop);
 965             // use JNIHandle address as ID
 966             writeObjectID(getAddressValue(handleAddr));
 967         }
 968     }
 969 
 970     @Override
 971     protected void writeStickyClasses() throws IOException {
 972         ClassLoaderData.theNullClassLoaderData().classesDo(k -> {
 973             if (k instanceof InstanceKlass) {
 974                 try {
 975                     int size = 1 + (int)VM.getVM().getAddressSize();
 976                     writeHeapRecordPrologue(size);
 977                     out.writeByte((byte)HPROF_GC_ROOT_STICKY_CLASS);
 978                     writeClassID(k);
 979                 } catch (IOException e) {
 980                     throw new UncheckedIOException(e);
 981                 }
 982             }
 983         });
 984     }
 985 
 986     protected void writeObjectArray(ObjArray array) throws IOException {
 987         int headerSize = getArrayHeaderSize(true);
 988         final int length = calculateArrayMaxLength(array.getLength(),
 989                                                    headerSize,
 990                                                    OBJ_ID_SIZE,
 991                                                    "Object");
 992         out.writeByte((byte) HPROF_GC_OBJ_ARRAY_DUMP);
 993         writeObjectID(array);
 994         out.writeInt(DUMMY_STACK_TRACE_ID);
 995         out.writeInt(length);
 996         writeObjectID(array.getKlass().getJavaMirror());
 997         for (int index = 0; index < length; index++) {
 998             OopHandle handle = array.getOopHandleAt(index);
 999             writeObjectID(getAddressValue(handle));
1000         }
1001     }
1002 
1003     protected void writePrimitiveArray(TypeArray array) throws IOException {
1004         int headerSize = getArrayHeaderSize(false);
1005         TypeArrayKlass tak = (TypeArrayKlass) array.getKlass();
1006         final int type = tak.getElementType();
1007         final String typeName = tak.getElementTypeName();
1008         final long typeSize = getSizeForType(type);
1009         final int length = calculateArrayMaxLength(array.getLength(),
1010                                                    headerSize,
1011                                                    typeSize,
1012                                                    typeName);
1013         out.writeByte((byte) HPROF_GC_PRIM_ARRAY_DUMP);
1014         writeObjectID(array);
1015         out.writeInt(DUMMY_STACK_TRACE_ID);
1016         out.writeInt(length);
1017         out.writeByte((byte) type);
1018         switch (type) {
1019             case TypeArrayKlass.T_BOOLEAN:
1020                 writeBooleanArray(array, length);
1021                 break;
1022             case TypeArrayKlass.T_CHAR:
1023                 writeCharArray(array, length);
1024                 break;
1025             case TypeArrayKlass.T_FLOAT:
1026                 writeFloatArray(array, length);
1027                 break;
1028             case TypeArrayKlass.T_DOUBLE:
1029                 writeDoubleArray(array, length);
1030                 break;
1031             case TypeArrayKlass.T_BYTE:
1032                 writeByteArray(array, length);
1033                 break;
1034             case TypeArrayKlass.T_SHORT:
1035                 writeShortArray(array, length);
1036                 break;
1037             case TypeArrayKlass.T_INT:
1038                 writeIntArray(array, length);
1039                 break;
1040             case TypeArrayKlass.T_LONG:
1041                 writeLongArray(array, length);
1042                 break;
1043             default:
1044                 throw new RuntimeException(
1045                     "Should not reach here: Unknown type: " + type);
1046         }
1047     }
1048 
1049     private void writeBooleanArray(TypeArray array, int length) throws IOException {
1050         for (int index = 0; index < length; index++) {
1051              long offset = (long) BOOLEAN_BASE_OFFSET + index * BOOLEAN_SIZE;
1052              out.writeBoolean(array.getHandle().getJBooleanAt(offset));
1053         }
1054     }
1055 
1056     private void writeByteArray(TypeArray array, int length) throws IOException {
1057         for (int index = 0; index < length; index++) {
1058              long offset = (long) BYTE_BASE_OFFSET + index * BYTE_SIZE;
1059              out.writeByte(array.getHandle().getJByteAt(offset));
1060         }
1061     }
1062 
1063     private void writeShortArray(TypeArray array, int length) throws IOException {
1064         for (int index = 0; index < length; index++) {
1065              long offset = (long) SHORT_BASE_OFFSET + index * SHORT_SIZE;
1066              out.writeShort(array.getHandle().getJShortAt(offset));
1067         }
1068     }
1069 
1070     private void writeIntArray(TypeArray array, int length) throws IOException {
1071         for (int index = 0; index < length; index++) {
1072              long offset = (long) INT_BASE_OFFSET + index * INT_SIZE;
1073              out.writeInt(array.getHandle().getJIntAt(offset));
1074         }
1075     }
1076 
1077     private void writeLongArray(TypeArray array, int length) throws IOException {
1078         for (int index = 0; index < length; index++) {
1079              long offset = (long) LONG_BASE_OFFSET + index * LONG_SIZE;
1080              out.writeLong(array.getHandle().getJLongAt(offset));
1081         }
1082     }
1083 
1084     private void writeCharArray(TypeArray array, int length) throws IOException {
1085         for (int index = 0; index < length; index++) {
1086              long offset = (long) CHAR_BASE_OFFSET + index * CHAR_SIZE;
1087              out.writeChar(array.getHandle().getJCharAt(offset));
1088         }
1089     }
1090 
1091     private void writeFloatArray(TypeArray array, int length) throws IOException {
1092         for (int index = 0; index < length; index++) {
1093              long offset = (long) FLOAT_BASE_OFFSET + index * FLOAT_SIZE;
1094              out.writeFloat(array.getHandle().getJFloatAt(offset));
1095         }
1096     }
1097 
1098     private void writeDoubleArray(TypeArray array, int length) throws IOException {
1099         for (int index = 0; index < length; index++) {
1100              long offset = (long) DOUBLE_BASE_OFFSET + index * DOUBLE_SIZE;
1101              out.writeDouble(array.getHandle().getJDoubleAt(offset));
1102         }
1103     }
1104 
1105     protected void writeInstance(Instance instance) throws IOException {
1106         Klass klass = instance.getKlass();
1107         if (klass.getClassLoaderData() == null) {
1108             // Ignoring this object since the corresponding Klass is not loaded.
1109             // Might be a dormant archive object.
1110             return;
1111         }
1112 
1113         out.writeByte((byte) HPROF_GC_INSTANCE_DUMP);
1114         writeObjectID(instance);
1115         out.writeInt(DUMMY_STACK_TRACE_ID);
1116         writeObjectID(klass.getJavaMirror());
1117 
1118         ClassData cd = classDataCache.get(klass);
1119 
1120         if (Assert.ASSERTS_ENABLED) {
1121             Assert.that(cd != null, "can not get class data for " + klass.getName().asString() + klass.getAddress());
1122         }
1123         List<Field> fields = cd.fields;
1124         int size = cd.instSize;
1125         out.writeInt(size);
1126         for (Iterator<Field> itr = fields.iterator(); itr.hasNext();) {
1127             writeField(itr.next(), instance);
1128         }
1129     }
1130 
1131     //-- Internals only below this point
1132 
1133     private void writeFieldDescriptors(List<Field> fields, InstanceKlass ik)
1134         throws IOException {
1135         // ik == null for instance fields.
1136         out.writeShort((short) fields.size());
1137         for (Iterator<Field> itr = fields.iterator(); itr.hasNext();) {
1138             Field field = itr.next();
1139             Symbol name = field.getName();
1140             writeSymbolID(name);
1141             char typeCode = (char) field.getSignature().getByteAt(0);
1142             int kind = signatureToHprofKind(typeCode);
1143             out.writeByte((byte)kind);
1144             if (ik != null) {
1145                 // static field
1146                 writeField(field, ik.getJavaMirror());
1147             }
1148         }
1149     }
1150 
1151     public static int signatureToHprofKind(char ch) {
1152         switch (ch) {
1153         case JVM_SIGNATURE_CLASS:
1154         case JVM_SIGNATURE_ARRAY:
1155             return HPROF_NORMAL_OBJECT;
1156         case JVM_SIGNATURE_BOOLEAN:
1157             return HPROF_BOOLEAN;
1158         case JVM_SIGNATURE_CHAR:
1159             return HPROF_CHAR;
1160         case JVM_SIGNATURE_FLOAT:
1161             return HPROF_FLOAT;
1162         case JVM_SIGNATURE_DOUBLE:
1163             return HPROF_DOUBLE;
1164         case JVM_SIGNATURE_BYTE:
1165             return HPROF_BYTE;
1166         case JVM_SIGNATURE_SHORT:
1167             return HPROF_SHORT;
1168         case JVM_SIGNATURE_INT:
1169             return HPROF_INT;
1170         case JVM_SIGNATURE_LONG:
1171             return HPROF_LONG;
1172         default:
1173             throw new RuntimeException("should not reach here");
1174         }
1175     }
1176 
1177     private void writeField(Field field, Oop oop) throws IOException {
1178         char typeCode = (char) field.getSignature().getByteAt(0);
1179         switch (typeCode) {
1180         case JVM_SIGNATURE_BOOLEAN:
1181             out.writeBoolean(((BooleanField)field).getValue(oop));
1182             break;
1183         case JVM_SIGNATURE_CHAR:
1184             out.writeChar(((CharField)field).getValue(oop));
1185             break;
1186         case JVM_SIGNATURE_BYTE:
1187             out.writeByte(((ByteField)field).getValue(oop));
1188             break;
1189         case JVM_SIGNATURE_SHORT:
1190             out.writeShort(((ShortField)field).getValue(oop));
1191             break;
1192         case JVM_SIGNATURE_INT:
1193             out.writeInt(((IntField)field).getValue(oop));
1194             break;
1195         case JVM_SIGNATURE_LONG:
1196             out.writeLong(((LongField)field).getValue(oop));
1197             break;
1198         case JVM_SIGNATURE_FLOAT:
1199             out.writeFloat(((FloatField)field).getValue(oop));
1200             break;
1201         case JVM_SIGNATURE_DOUBLE:
1202             out.writeDouble(((DoubleField)field).getValue(oop));
1203             break;
1204         case JVM_SIGNATURE_CLASS:
1205         case JVM_SIGNATURE_ARRAY: {
1206             if (field.isFlat()) {
1207               // FIXME - we don't handle flattened fields yet. Just treat them
1208               // as a null reference. See JDK-8381370.
1209               writeObjectID(null);
1210             } else if (VM.getVM().isCompressedOopsEnabled()) {
1211               OopHandle handle = ((NarrowOopField)field).getValueAsOopHandle(oop);
1212               writeObjectID(getAddressValue(handle));
1213             } else {
1214               OopHandle handle = ((OopField)field).getValueAsOopHandle(oop);
1215               writeObjectID(getAddressValue(handle));
1216             }
1217             break;
1218         }
1219         default:
1220             throw new RuntimeException("should not reach here");
1221         }
1222     }
1223 
1224     private void writeHeader(int tag, int len) throws IOException {
1225         out.writeByte((byte)tag);
1226         out.writeInt(0); // current ticks
1227         out.writeInt(len);
1228     }
1229 
1230     private void writeDummyTrace() throws IOException {
1231         writeHeader(HPROF_TRACE, 3 * 4);
1232         out.writeInt(DUMMY_STACK_TRACE_ID);
1233         out.writeInt(0);
1234         out.writeInt(0);
1235     }
1236 
1237     private void writeClassSymbols(Klass k) throws IOException {
1238         writeSymbol(k.getName());
1239         if (k instanceof InstanceKlass) {
1240             InstanceKlass ik = (InstanceKlass) k;
1241             List<Field> declaredFields = ik.getImmediateFields();
1242             for (Iterator<Field> itr = declaredFields.iterator(); itr.hasNext();) {
1243                 Field field = itr.next();
1244                 writeSymbol(field.getName());
1245             }
1246         }
1247     }
1248 
1249     private void writeSymbols() throws IOException {
1250         // Write all the symbols that are used by the classes
1251         ClassLoaderDataGraph cldGraph = VM.getVM().getClassLoaderDataGraph();
1252         try {
1253              cldGraph.classesDo(new ClassLoaderDataGraph.ClassVisitor() {
1254                             public void visit(Klass k) {
1255                                 try {
1256                                     writeClassSymbols(k);
1257                                 } catch (IOException e) {
1258                                     throw new RuntimeException(e);
1259                                 }
1260                             }
1261                         });
1262         } catch (RuntimeException re) {
1263             handleRuntimeException(re);
1264         }
1265     }
1266 
1267     private void writeSymbol(Symbol sym) throws IOException {
1268         // If name is already written don't write it again.
1269         if (names.add(sym)) {
1270             if(sym != null) {
1271               byte[] buf = sym.asString().getBytes(UTF_8);
1272               writeHeader(HPROF_UTF8, buf.length + OBJ_ID_SIZE);
1273               writeSymbolID(sym);
1274               out.write(buf);
1275            } else {
1276               writeHeader(HPROF_UTF8, 0 + OBJ_ID_SIZE);
1277               writeSymbolID(null);
1278            }
1279         }
1280     }
1281 
1282     private void writeClasses() throws IOException {
1283         // write class list (id, name) association
1284         ClassLoaderDataGraph cldGraph = VM.getVM().getClassLoaderDataGraph();
1285         try {
1286             cldGraph.classesDo(new ClassLoaderDataGraph.ClassVisitor() {
1287                 public void visit(Klass k) {
1288                     try {
1289                         Instance clazz = k.getJavaMirror();
1290                         writeHeader(HPROF_LOAD_CLASS, 2 * (OBJ_ID_SIZE + 4));
1291                         out.writeInt(serialNum);
1292                         writeObjectID(clazz);
1293                         KlassMap.add(serialNum - 1, k);
1294                         out.writeInt(DUMMY_STACK_TRACE_ID);
1295                         writeSymbolID(k.getName());
1296                         serialNum++;
1297                     } catch (IOException exp) {
1298                         throw new RuntimeException(exp);
1299                     }
1300                 }
1301             });
1302         } catch (RuntimeException re) {
1303             handleRuntimeException(re);
1304         }
1305     }
1306 
1307     // writes hprof binary file header
1308     private void writeFileHeader() throws IOException {
1309         // version string
1310         out.writeBytes(HPROF_HEADER_1_0_2);
1311         out.writeByte((byte)'\0');
1312 
1313         // write identifier size. we use pointers as identifiers.
1314         out.writeInt(OBJ_ID_SIZE);
1315 
1316         // timestamp -- file creation time.
1317         out.writeLong(System.currentTimeMillis());
1318     }
1319 
1320     // writes unique ID for an object
1321     private void writeObjectID(Oop oop) throws IOException {
1322         OopHandle handle = (oop != null)? oop.getHandle() : null;
1323         long address = getAddressValue(handle);
1324         writeObjectID(address);
1325     }
1326 
1327     private void writeClassID(Klass k) throws IOException {
1328         writeObjectID(k.getJavaMirror());
1329     }
1330 
1331     private void writeSymbolID(Symbol sym) throws IOException {
1332         assert names.contains(sym);
1333         long address = (sym != null) ? getAddressValue(sym.getAddress()) : getAddressValue(null);
1334         writeObjectID(address);
1335     }
1336 
1337     private void writeObjectID(long address) throws IOException {
1338         if (OBJ_ID_SIZE == 4) {
1339             out.writeInt((int) address);
1340         } else {
1341             out.writeLong(address);
1342         }
1343     }
1344 
1345     private long getAddressValue(Address addr) {
1346         return (addr == null)? 0L : dbg.getAddressValue(addr);
1347     }
1348 
1349     // get all declared as well as inherited (directly/indirectly) fields
1350     private static List<Field> getInstanceFields(InstanceKlass ik) {
1351         InstanceKlass klass = ik;
1352         List<Field> res = new ArrayList<>();
1353         while (klass != null) {
1354             List<Field> curFields = klass.getImmediateFields();
1355             for (Iterator<Field> itr = curFields.iterator(); itr.hasNext();) {
1356                 Field f = itr.next();
1357                 if (! f.isStatic()) {
1358                     res.add(f);
1359                 }
1360             }
1361             klass = (InstanceKlass) klass.getSuper();
1362         }
1363         return res;
1364     }
1365 
1366     // get size in bytes (in stream) required for given field.
1367     private int getSizeForField(Field field) {
1368         char typeCode = (char)field.getSignature().getByteAt(0);
1369         switch (typeCode) {
1370         case JVM_SIGNATURE_BOOLEAN:
1371         case JVM_SIGNATURE_BYTE:
1372             return 1;
1373         case JVM_SIGNATURE_CHAR:
1374         case JVM_SIGNATURE_SHORT:
1375             return 2;
1376         case JVM_SIGNATURE_INT:
1377         case JVM_SIGNATURE_FLOAT:
1378             return 4;
1379         case JVM_SIGNATURE_CLASS:
1380         case JVM_SIGNATURE_ARRAY:
1381             return OBJ_ID_SIZE;
1382         case JVM_SIGNATURE_LONG:
1383         case JVM_SIGNATURE_DOUBLE:
1384             return 8;
1385         default:
1386             throw new RuntimeException("should not reach here");
1387         }
1388     }
1389 
1390     // get size in bytes (in stream) required for given fields.  Note
1391     // that this is not the same as object size in heap. The size in
1392     // heap will include size of padding/alignment bytes as well.
1393     private int getSizeForFields(List<Field> fields) {
1394         int size = 0;
1395         for (Field field : fields) {
1396             size += getSizeForField(field);
1397         }
1398         return size;
1399     }
1400 
1401     private boolean isCompression() {
1402         return (gzLevel >= 1 && gzLevel <= 9);
1403     }
1404 
1405     // Convert integer to byte array with BIG_ENDIAN byte order.
1406     private static byte[] genByteArrayFromInt(int value) {
1407         ByteBuffer intBuffer = ByteBuffer.allocate(4);
1408         intBuffer.order(ByteOrder.BIG_ENDIAN);
1409         intBuffer.putInt(value);
1410         return intBuffer.array();
1411     }
1412 
1413     // We don't have allocation site info. We write a dummy
1414     // stack trace with this id.
1415     private static final int DUMMY_STACK_TRACE_ID = 1;
1416     private static final int EMPTY_FRAME_DEPTH = -1;
1417 
1418     private DataOutputStream out;
1419     private FileOutputStream fos;
1420     private OutputStream hprofBufferedOut;
1421     private Debugger dbg;
1422     private ObjectHeap objectHeap;
1423     private ArrayList<Klass> KlassMap;
1424     private int gzLevel;
1425 
1426     // oopSize of the debuggee
1427     private int OBJ_ID_SIZE;
1428 
1429     // Added for hprof file format 1.0.2 support
1430     private boolean useSegmentedHeapDump;
1431     private long currentSegmentStart;
1432 
1433     private long BOOLEAN_BASE_OFFSET;
1434     private long BYTE_BASE_OFFSET;
1435     private long CHAR_BASE_OFFSET;
1436     private long SHORT_BASE_OFFSET;
1437     private long INT_BASE_OFFSET;
1438     private long LONG_BASE_OFFSET;
1439     private long FLOAT_BASE_OFFSET;
1440     private long DOUBLE_BASE_OFFSET;
1441     private long OBJECT_BASE_OFFSET;
1442 
1443     private int BOOLEAN_SIZE;
1444     private int BYTE_SIZE;
1445     private int CHAR_SIZE;
1446     private int SHORT_SIZE;
1447     private int INT_SIZE;
1448     private int LONG_SIZE;
1449     private int FLOAT_SIZE;
1450     private int DOUBLE_SIZE;
1451 
1452     private static class ClassData {
1453         int instSize;
1454         List<Field> fields;
1455 
1456         ClassData(int instSize, List<Field> fields) {
1457             this.instSize = instSize;
1458             this.fields = fields;
1459         }
1460     }
1461 
1462     private Map<InstanceKlass, ClassData> classDataCache = new HashMap<>();
1463 }