1/*
2 * Copyright (c) 2004, 2017, 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
25package sun.jvm.hotspot.utilities;
26
27import java.io.*;
28import java.nio.channels.*;
29import java.util.*;
30import sun.jvm.hotspot.debugger.*;
31import sun.jvm.hotspot.memory.*;
32import sun.jvm.hotspot.oops.*;
33import sun.jvm.hotspot.runtime.*;
34import sun.jvm.hotspot.classfile.*;
35
36/*
37 * This class writes Java heap in hprof binary format. This format is
38 * used by Heap Analysis Tool (HAT). The class is heavily influenced
39 * by 'hprof_io.c' of 1.5 new hprof implementation.
40 */
41
42/* hprof binary format: (result either written to a file or sent over
43 * the network).
44 *
45 * WARNING: This format is still under development, and is subject to
46 * change without notice.
47 *
48 * header     "JAVA PROFILE 1.0.2" (0-terminated)
49 * u4         size of identifiers. Identifiers are used to represent
50 *            UTF8 strings, objects, stack traces, etc. They usually
51 *            have the same size as host pointers. For example, on
52 *            Solaris and Win32, the size is 4.
53 * u4         high word
54 * u4         low word    number of milliseconds since 0:00 GMT, 1/1/70
55 * [record]*  a sequence of records.
56 *
57 */
58
59/*
60 *
61 * Record format:
62 *
63 * u1         a TAG denoting the type of the record
64 * u4         number of *microseconds* since the time stamp in the
65 *            header. (wraps around in a little more than an hour)
66 * u4         number of bytes *remaining* in the record. Note that
67 *            this number excludes the tag and the length field itself.
68 * [u1]*      BODY of the record (a sequence of bytes)
69 */
70
71/*
72 * The following TAGs are supported:
73 *
74 * TAG           BODY       notes
75 *----------------------------------------------------------
76 * HPROF_UTF8               a UTF8-encoded name
77 *
78 *               id         name ID
79 *               [u1]*      UTF8 characters (no trailing zero)
80 *
81 * HPROF_LOAD_CLASS         a newly loaded class
82 *
83 *                u4        class serial number (> 0)
84 *                id        class object ID
85 *                u4        stack trace serial number
86 *                id        class name ID
87 *
88 * HPROF_UNLOAD_CLASS       an unloading class
89 *
90 *                u4        class serial_number
91 *
92 * HPROF_FRAME              a Java stack frame
93 *
94 *                id        stack frame ID
95 *                id        method name ID
96 *                id        method signature ID
97 *                id        source file name ID
98 *                u4        class serial number
99 *                i4        line number. >0: normal
100 *                                       -1: unknown
101 *                                       -2: compiled method
102 *                                       -3: native method
103 *
104 * HPROF_TRACE              a Java stack trace
105 *
106 *               u4         stack trace serial number
107 *               u4         thread serial number
108 *               u4         number of frames
109 *               [id]*      stack frame IDs
110 *
111 *
112 * HPROF_ALLOC_SITES        a set of heap allocation sites, obtained after GC
113 *
114 *               u2         flags 0x0001: incremental vs. complete
115 *                                0x0002: sorted by allocation vs. live
116 *                                0x0004: whether to force a GC
117 *               u4         cutoff ratio
118 *               u4         total live bytes
119 *               u4         total live instances
120 *               u8         total bytes allocated
121 *               u8         total instances allocated
122 *               u4         number of sites that follow
123 *               [u1        is_array: 0:  normal object
124 *                                    2:  object array
125 *                                    4:  boolean array
126 *                                    5:  char array
127 *                                    6:  float array
128 *                                    7:  double array
129 *                                    8:  byte array
130 *                                    9:  short array
131 *                                    10: int array
132 *                                    11: long array
133 *                u4        class serial number (may be zero during startup)
134 *                u4        stack trace serial number
135 *                u4        number of bytes alive
136 *                u4        number of instances alive
137 *                u4        number of bytes allocated
138 *                u4]*      number of instance allocated
139 *
140 * HPROF_START_THREAD       a newly started thread.
141 *
142 *               u4         thread serial number (> 0)
143 *               id         thread object ID
144 *               u4         stack trace serial number
145 *               id         thread name ID
146 *               id         thread group name ID
147 *               id         thread group parent name ID
148 *
149 * HPROF_END_THREAD         a terminating thread.
150 *
151 *               u4         thread serial number
152 *
153 * HPROF_HEAP_SUMMARY       heap summary
154 *
155 *               u4         total live bytes
156 *               u4         total live instances
157 *               u8         total bytes allocated
158 *               u8         total instances allocated
159 *
160 * HPROF_HEAP_DUMP          denote a heap dump
161 *
162 *               [heap dump sub-records]*
163 *
164 *                          There are four kinds of heap dump sub-records:
165 *
166 *               u1         sub-record type
167 *
168 *               HPROF_GC_ROOT_UNKNOWN         unknown root
169 *
170 *                          id         object ID
171 *
172 *               HPROF_GC_ROOT_THREAD_OBJ      thread object
173 *
174 *                          id         thread object ID  (may be 0 for a
175 *                                     thread newly attached through JNI)
176 *                          u4         thread sequence number
177 *                          u4         stack trace sequence number
178 *
179 *               HPROF_GC_ROOT_JNI_GLOBAL      JNI global ref root
180 *
181 *                          id         object ID
182 *                          id         JNI global ref ID
183 *
184 *               HPROF_GC_ROOT_JNI_LOCAL       JNI local ref
185 *
186 *                          id         object ID
187 *                          u4         thread serial number
188 *                          u4         frame # in stack trace (-1 for empty)
189 *
190 *               HPROF_GC_ROOT_JAVA_FRAME      Java stack frame
191 *
192 *                          id         object ID
193 *                          u4         thread serial number
194 *                          u4         frame # in stack trace (-1 for empty)
195 *
196 *               HPROF_GC_ROOT_NATIVE_STACK    Native stack
197 *
198 *                          id         object ID
199 *                          u4         thread serial number
200 *
201 *               HPROF_GC_ROOT_STICKY_CLASS    System class
202 *
203 *                          id         object ID
204 *
205 *               HPROF_GC_ROOT_THREAD_BLOCK    Reference from thread block
206 *
207 *                          id         object ID
208 *                          u4         thread serial number
209 *
210 *               HPROF_GC_ROOT_MONITOR_USED    Busy monitor
211 *
212 *                          id         object ID
213 *
214 *               HPROF_GC_CLASS_DUMP           dump of a class object
215 *
216 *                          id         class object ID
217 *                          u4         stack trace serial number
218 *                          id         super class object ID
219 *                          id         class loader object ID
220 *                          id         signers object ID
221 *                          id         protection domain object ID
222 *                          id         reserved
223 *                          id         reserved
224 *
225 *                          u4         instance size (in bytes)
226 *
227 *                          u2         size of constant pool
228 *                          [u2,       constant pool index,
229 *                           ty,       type
230 *                                     2:  object
231 *                                     4:  boolean
232 *                                     5:  char
233 *                                     6:  float
234 *                                     7:  double
235 *                                     8:  byte
236 *                                     9:  short
237 *                                     10: int
238 *                                     11: long
239 *                           vl]*      and value
240 *
241 *                          u2         number of static fields
242 *                          [id,       static field name,
243 *                           ty,       type,
244 *                           vl]*      and value
245 *
246 *                          u2         number of inst. fields (not inc. super)
247 *                          [id,       instance field name,
248 *                           ty]*      type
249 *
250 *               HPROF_GC_INSTANCE_DUMP        dump of a normal object
251 *
252 *                          id         object ID
253 *                          u4         stack trace serial number
254 *                          id         class object ID
255 *                          u4         number of bytes that follow
256 *                          [vl]*      instance field values (class, followed
257 *                                     by super, super's super ...)
258 *
259 *               HPROF_GC_OBJ_ARRAY_DUMP       dump of an object array
260 *
261 *                          id         array object ID
262 *                          u4         stack trace serial number
263 *                          u4         number of elements
264 *                          id         array class ID
265 *                          [id]*      elements
266 *
267 *               HPROF_GC_PRIM_ARRAY_DUMP      dump of a primitive array
268 *
269 *                          id         array object ID
270 *                          u4         stack trace serial number
271 *                          u4         number of elements
272 *                          u1         element type
273 *                                     4:  boolean array
274 *                                     5:  char array
275 *                                     6:  float array
276 *                                     7:  double array
277 *                                     8:  byte array
278 *                                     9:  short array
279 *                                     10: int array
280 *                                     11: long array
281 *                          [u1]*      elements
282 *
283 * HPROF_CPU_SAMPLES        a set of sample traces of running threads
284 *
285 *                u4        total number of samples
286 *                u4        # of traces
287 *               [u4        # of samples
288 *                u4]*      stack trace serial number
289 *
290 * HPROF_CONTROL_SETTINGS   the settings of on/off switches
291 *
292 *                u4        0x00000001: alloc traces on/off
293 *                          0x00000002: cpu sampling on/off
294 *                u2        stack trace depth
295 *
296 *
297 * A heap dump can optionally be generated as a sequence of heap dump
298 * segments. This sequence is terminated by an end record. The additional
299 * tags allowed by format "JAVA PROFILE 1.0.2" are:
300 *
301 * HPROF_HEAP_DUMP_SEGMENT  denote a heap dump segment
302 *
303 *               [heap dump sub-records]*
304 *               The same sub-record types allowed by HPROF_HEAP_DUMP
305 *
306 * HPROF_HEAP_DUMP_END      denotes the end of a heap dump
307 *
308 */
309
310public class HeapHprofBinWriter extends AbstractHeapGraphWriter {
311
312    private static final long HPROF_SEGMENTED_HEAP_DUMP_THRESHOLD = 2L * 0x40000000;
313
314    // The approximate size of a heap segment. Used to calculate when to create
315    // a new segment.
316    private static final long HPROF_SEGMENTED_HEAP_DUMP_SEGMENT_SIZE = 1L * 0x40000000;
317
318    // hprof binary file header
319    private static final String HPROF_HEADER_1_0_2 = "JAVA PROFILE 1.0.2";
320
321    // constants in enum HprofTag
322    private static final int HPROF_UTF8             = 0x01;
323    private static final int HPROF_LOAD_CLASS       = 0x02;
324    private static final int HPROF_UNLOAD_CLASS     = 0x03;
325    private static final int HPROF_FRAME            = 0x04;
326    private static final int HPROF_TRACE            = 0x05;
327    private static final int HPROF_ALLOC_SITES      = 0x06;
328    private static final int HPROF_HEAP_SUMMARY     = 0x07;
329    private static final int HPROF_START_THREAD     = 0x0A;
330    private static final int HPROF_END_THREAD       = 0x0B;
331    private static final int HPROF_HEAP_DUMP        = 0x0C;
332    private static final int HPROF_CPU_SAMPLES      = 0x0D;
333    private static final int HPROF_CONTROL_SETTINGS = 0x0E;
334
335    // 1.0.2 record types
336    private static final int HPROF_HEAP_DUMP_SEGMENT = 0x1C;
337    private static final int HPROF_HEAP_DUMP_END     = 0x2C;
338
339    // Heap dump constants
340    // constants in enum HprofGcTag
341    private static final int HPROF_GC_ROOT_UNKNOWN       = 0xFF;
342    private static final int HPROF_GC_ROOT_JNI_GLOBAL    = 0x01;
343    private static final int HPROF_GC_ROOT_JNI_LOCAL     = 0x02;
344    private static final int HPROF_GC_ROOT_JAVA_FRAME    = 0x03;
345    private static final int HPROF_GC_ROOT_NATIVE_STACK  = 0x04;
346    private static final int HPROF_GC_ROOT_STICKY_CLASS  = 0x05;
347    private static final int HPROF_GC_ROOT_THREAD_BLOCK  = 0x06;
348    private static final int HPROF_GC_ROOT_MONITOR_USED  = 0x07;
349    private static final int HPROF_GC_ROOT_THREAD_OBJ    = 0x08;
350    private static final int HPROF_GC_CLASS_DUMP         = 0x20;
351    private static final int HPROF_GC_INSTANCE_DUMP      = 0x21;
352    private static final int HPROF_GC_OBJ_ARRAY_DUMP     = 0x22;
353    private static final int HPROF_GC_PRIM_ARRAY_DUMP    = 0x23;
354
355    // constants in enum HprofType
356    private static final int HPROF_ARRAY_OBJECT  = 1;
357    private static final int HPROF_NORMAL_OBJECT = 2;
358    private static final int HPROF_BOOLEAN       = 4;
359    private static final int HPROF_CHAR          = 5;
360    private static final int HPROF_FLOAT         = 6;
361    private static final int HPROF_DOUBLE        = 7;
362    private static final int HPROF_BYTE          = 8;
363    private static final int HPROF_SHORT         = 9;
364    private static final int HPROF_INT           = 10;
365    private static final int HPROF_LONG          = 11;
366
367    // Java type codes
368    private static final int JVM_SIGNATURE_BOOLEAN = 'Z';
369    private static final int JVM_SIGNATURE_CHAR    = 'C';
370    private static final int JVM_SIGNATURE_BYTE    = 'B';
371    private static final int JVM_SIGNATURE_SHORT   = 'S';
372    private static final int JVM_SIGNATURE_INT     = 'I';
373    private static final int JVM_SIGNATURE_LONG    = 'J';
374    private static final int JVM_SIGNATURE_FLOAT   = 'F';
375    private static final int JVM_SIGNATURE_DOUBLE  = 'D';
376    private static final int JVM_SIGNATURE_ARRAY   = '[';
377    private static final int JVM_SIGNATURE_CLASS   = 'L';
378
379    private static final long MAX_U4_VALUE = 0xFFFFFFFFL;
380    int serialNum = 1;
381
382    public synchronized void write(String fileName) throws IOException {
383        // open file stream and create buffered data output stream
384        fos = new FileOutputStream(fileName);
385        out = new DataOutputStream(new BufferedOutputStream(fos));
386
387        VM vm = VM.getVM();
388        dbg = vm.getDebugger();
389        objectHeap = vm.getObjectHeap();
390        symTbl = vm.getSymbolTable();
391
392        OBJ_ID_SIZE = (int) vm.getOopSize();
393
394        BOOLEAN_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_BOOLEAN);
395        BYTE_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_BYTE);
396        CHAR_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_CHAR);
397        SHORT_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_SHORT);
398        INT_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_INT);
399        LONG_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_LONG);
400        FLOAT_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_FLOAT);
401        DOUBLE_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_DOUBLE);
402        OBJECT_BASE_OFFSET = TypeArray.baseOffsetInBytes(BasicType.T_OBJECT);
403
404        BOOLEAN_SIZE = objectHeap.getBooleanSize();
405        BYTE_SIZE = objectHeap.getByteSize();
406        CHAR_SIZE = objectHeap.getCharSize();
407        SHORT_SIZE = objectHeap.getShortSize();
408        INT_SIZE = objectHeap.getIntSize();
409        LONG_SIZE = objectHeap.getLongSize();
410        FLOAT_SIZE = objectHeap.getFloatSize();
411        DOUBLE_SIZE = objectHeap.getDoubleSize();
412
413        // Check weather we should dump the heap as segments
414        useSegmentedHeapDump = vm.getUniverse().heap().used() > HPROF_SEGMENTED_HEAP_DUMP_THRESHOLD;
415
416        // hprof bin format header
417        writeFileHeader();
418
419        // dummy stack trace without any frames so that
420        // HAT can be run without -stack false option
421        writeDummyTrace();
422
423        // hprof UTF-8 symbols section
424        writeSymbols();
425
426        // HPROF_LOAD_CLASS records for all classes
427        writeClasses();
428
429        // write CLASS_DUMP records
430        writeClassDumpRecords();
431
432        // this will write heap data into the buffer stream
433        super.write();
434
435        // flush buffer stream.
436        out.flush();
437
438        // Fill in final length
439        fillInHeapRecordLength();
440
441        if (useSegmentedHeapDump) {
442            // Write heap segment-end record
443            out.writeByte((byte) HPROF_HEAP_DUMP_END);
444            out.writeInt(0);
445            out.writeInt(0);
446        }
447
448        // flush buffer stream and throw it.
449        out.flush();
450        out = null;
451
452        // close the file stream
453        fos.close();
454    }
455
456    @Override
457    protected void writeHeapRecordPrologue() throws IOException {
458        if (currentSegmentStart == 0) {
459            // write heap data header, depending on heap size use segmented heap
460            // format
461            out.writeByte((byte) (useSegmentedHeapDump ? HPROF_HEAP_DUMP_SEGMENT
462                    : HPROF_HEAP_DUMP));
463            out.writeInt(0);
464
465            // remember position of dump length, we will fixup
466            // length later - hprof format requires length.
467            out.flush();
468            currentSegmentStart = fos.getChannel().position();
469            // write dummy length of 0 and we'll fix it later.
470            out.writeInt(0);
471        }
472    }
473
474    @Override
475    protected void writeHeapRecordEpilogue() throws IOException {
476        if (useSegmentedHeapDump) {
477            out.flush();
478            if ((fos.getChannel().position() - currentSegmentStart - 4L) >= HPROF_SEGMENTED_HEAP_DUMP_SEGMENT_SIZE) {
479                fillInHeapRecordLength();
480                currentSegmentStart = 0;
481            }
482        }
483    }
484
485    private void fillInHeapRecordLength() throws IOException {
486
487        // now get the current position to calculate length
488        long dumpEnd = fos.getChannel().position();
489
490        // calculate the length of heap data
491        long dumpLenLong = (dumpEnd - currentSegmentStart - 4L);
492
493        // Check length boundary, overflow could happen but is _very_ unlikely
494        if (dumpLenLong >= (4L * 0x40000000)) {
495            throw new RuntimeException("Heap segment size overflow.");
496        }
497
498        // Save the current position
499        long currentPosition = fos.getChannel().position();
500
501        // seek the position to write length
502        fos.getChannel().position(currentSegmentStart);
503
504        int dumpLen = (int) dumpLenLong;
505
506        // write length as integer
507        fos.write((dumpLen >>> 24) & 0xFF);
508        fos.write((dumpLen >>> 16) & 0xFF);
509        fos.write((dumpLen >>> 8) & 0xFF);
510        fos.write((dumpLen >>> 0) & 0xFF);
511
512        //Reset to previous current position
513        fos.getChannel().position(currentPosition);
514    }
515
516    // get the size in bytes for the requested type
517    private long getSizeForType(int type) throws IOException {
518        switch (type) {
519            case TypeArrayKlass.T_BOOLEAN:
520                return BOOLEAN_SIZE;
521            case TypeArrayKlass.T_INT:
522                return INT_SIZE;
523            case TypeArrayKlass.T_CHAR:
524                return CHAR_SIZE;
525            case TypeArrayKlass.T_SHORT:
526                return SHORT_SIZE;
527            case TypeArrayKlass.T_BYTE:
528                return BYTE_SIZE;
529            case TypeArrayKlass.T_LONG:
530                return LONG_SIZE;
531            case TypeArrayKlass.T_FLOAT:
532                return FLOAT_SIZE;
533            case TypeArrayKlass.T_DOUBLE:
534                return DOUBLE_SIZE;
535            default:
536                throw new RuntimeException(
537                    "Should not reach here: Unknown type: " + type);
538         }
539    }
540
541    private int getArrayHeaderSize(boolean isObjectAarray) {
542        return isObjectAarray?
543            ((int) BYTE_SIZE + 2 * (int) INT_SIZE + 2 * (int) OBJ_ID_SIZE):
544            (2 * (int) BYTE_SIZE + 2 * (int) INT_SIZE + (int) OBJ_ID_SIZE);
545    }
546
547    // Check if we need to truncate an array
548    private int calculateArrayMaxLength(long originalArrayLength,
549                                        int headerSize,
550                                        long typeSize,
551                                        String typeName) throws IOException {
552
553        long length = originalArrayLength;
554
555        // now get the current position to calculate length
556        long dumpEnd = fos.getChannel().position();
557        long originalLengthInBytes = originalArrayLength * typeSize;
558
559        // calculate the length of heap data
560        long currentRecordLength = (dumpEnd - currentSegmentStart - 4L);
561        if (currentRecordLength > 0 &&
562            (currentRecordLength + headerSize + originalLengthInBytes) > MAX_U4_VALUE) {
563            fillInHeapRecordLength();
564            currentSegmentStart = 0;
565            writeHeapRecordPrologue();
566            currentRecordLength = 0;
567        }
568
569        // Calculate the max bytes we can use.
570        long maxBytes = (MAX_U4_VALUE - (headerSize + currentRecordLength));
571
572        if (originalLengthInBytes > maxBytes) {
573            length = maxBytes/typeSize;
574            System.err.println("WARNING: Cannot dump array of type " + typeName
575                               + " with length " + originalArrayLength
576                               + "; truncating to length " + length);
577        }
578        return (int) length;
579    }
580
581    private void writeClassDumpRecords() throws IOException {
582        SystemDictionary sysDict = VM.getVM().getSystemDictionary();
583        ClassLoaderDataGraph cldGraph = VM.getVM().getClassLoaderDataGraph();
584        try {
585            sysDict.allClassesDo(new SystemDictionary.ClassVisitor() {
586                            public void visit(Klass k) {
587                                try {
588                                    writeHeapRecordPrologue();
589                                    writeClassDumpRecord(k);
590                                    writeHeapRecordEpilogue();
591                                } catch (IOException e) {
592                                    throw new RuntimeException(e);
593                                }
594                            }
595                        });
596             // Add the anonymous classes also which are not present in the
597             // System Dictionary
598             cldGraph.allAnonymousKlassesDo(new ClassLoaderDataGraph.KlassVisitor() {
599                            public void visit(Klass k) {
600                                try {
601                                    writeHeapRecordPrologue();
602                                    writeClassDumpRecord(k);
603                                    writeHeapRecordEpilogue();
604                                } catch (IOException e) {
605                                    throw new RuntimeException(e);
606                                }
607                            }
608                        });
609        } catch (RuntimeException re) {
610            handleRuntimeException(re);
611        }
612    }
613
614    protected void writeClass(Instance instance) throws IOException {
615        Klass reflectedKlass = java_lang_Class.asKlass(instance);
616        // dump instance record only for primitive type Class objects.
617        // all other Class objects are covered by writeClassDumpRecords.
618        if (reflectedKlass == null) {
619            writeInstance(instance);
620        }
621    }
622
623    private void writeClassDumpRecord(Klass k) throws IOException {
624        out.writeByte((byte)HPROF_GC_CLASS_DUMP);
625        writeObjectID(k.getJavaMirror());
626        out.writeInt(DUMMY_STACK_TRACE_ID);
627        Klass superKlass = k.getJavaSuper();
628        if (superKlass != null) {
629            writeObjectID(superKlass.getJavaMirror());
630        } else {
631            writeObjectID(null);
632        }
633
634        if (k instanceof InstanceKlass) {
635            InstanceKlass ik = (InstanceKlass) k;
636            writeObjectID(ik.getClassLoader());
637            writeObjectID(null);  // ik.getJavaMirror().getSigners());
638            writeObjectID(null);  // ik.getJavaMirror().getProtectionDomain());
639            // two reserved id fields
640            writeObjectID(null);
641            writeObjectID(null);
642            List fields = getInstanceFields(ik);
643            int instSize = getSizeForFields(fields);
644            classDataCache.put(ik, new ClassData(instSize, fields));
645            out.writeInt(instSize);
646
647            // For now, ignore constant pool - HAT ignores too!
648            // output number of cp entries as zero.
649            out.writeShort((short) 0);
650
651            List declaredFields = ik.getImmediateFields();
652            List staticFields = new ArrayList();
653            List instanceFields = new ArrayList();
654            Iterator itr = null;
655            for (itr = declaredFields.iterator(); itr.hasNext();) {
656                Field field = (Field) itr.next();
657                if (field.isStatic()) {
658                    staticFields.add(field);
659                } else {
660                    instanceFields.add(field);
661                }
662            }
663
664            // dump static field descriptors
665            writeFieldDescriptors(staticFields, ik);
666
667            // dump instance field descriptors
668            writeFieldDescriptors(instanceFields, null);
669        } else {
670            if (k instanceof ObjArrayKlass) {
671                ObjArrayKlass oak = (ObjArrayKlass) k;
672                Klass bottomKlass = oak.getBottomKlass();
673                if (bottomKlass instanceof InstanceKlass) {
674                    InstanceKlass ik = (InstanceKlass) bottomKlass;
675                    writeObjectID(ik.getClassLoader());
676                    writeObjectID(null); // ik.getJavaMirror().getSigners());
677                    writeObjectID(null); // ik.getJavaMirror().getProtectionDomain());
678                } else {
679                    writeObjectID(null);
680                    writeObjectID(null);
681                    writeObjectID(null);
682                }
683            } else {
684                writeObjectID(null);
685                writeObjectID(null);
686                writeObjectID(null);
687            }
688            // two reserved id fields
689            writeObjectID(null);
690            writeObjectID(null);
691            // write zero instance size -- as instance size
692            // is variable for arrays.
693            out.writeInt(0);
694            // no constant pool for array klasses
695            out.writeShort((short) 0);
696            // no static fields for array klasses
697            out.writeShort((short) 0);
698            // no instance fields for array klasses
699            out.writeShort((short) 0);
700        }
701    }
702
703    protected void writeJavaThread(JavaThread jt, int index) throws IOException {
704        out.writeByte((byte) HPROF_GC_ROOT_THREAD_OBJ);
705        writeObjectID(jt.getThreadObj());
706        out.writeInt(index);
707        out.writeInt(DUMMY_STACK_TRACE_ID);
708        writeLocalJNIHandles(jt, index);
709    }
710
711    protected void writeLocalJNIHandles(JavaThread jt, int index) throws IOException {
712        final int threadIndex = index;
713        JNIHandleBlock blk = jt.activeHandles();
714        if (blk != null) {
715            try {
716                blk.oopsDo(new AddressVisitor() {
717                           public void visitAddress(Address handleAddr) {
718                               try {
719                                   if (handleAddr != null) {
720                                       OopHandle oopHandle = handleAddr.getOopHandleAt(0);
721                                       Oop oop = objectHeap.newOop(oopHandle);
722                                       // exclude JNI handles hotspot internal objects
723                                       if (oop != null && isJavaVisible(oop)) {
724                                           out.writeByte((byte) HPROF_GC_ROOT_JNI_LOCAL);
725                                           writeObjectID(oop);
726                                           out.writeInt(threadIndex);
727                                           out.writeInt(EMPTY_FRAME_DEPTH);
728                                       }
729                                   }
730                               } catch (IOException exp) {
731                                   throw new RuntimeException(exp);
732                               }
733                           }
734                           public void visitCompOopAddress(Address handleAddr) {
735                             throw new RuntimeException(
736                                   " Should not reach here. JNIHandles are not compressed \n");
737                           }
738                       });
739            } catch (RuntimeException re) {
740                handleRuntimeException(re);
741            }
742        }
743    }
744
745    protected void writeGlobalJNIHandle(Address handleAddr) throws IOException {
746        OopHandle oopHandle = handleAddr.getOopHandleAt(0);
747        Oop oop = objectHeap.newOop(oopHandle);
748        // exclude JNI handles of hotspot internal objects
749        if (oop != null && isJavaVisible(oop)) {
750            out.writeByte((byte) HPROF_GC_ROOT_JNI_GLOBAL);
751            writeObjectID(oop);
752            // use JNIHandle address as ID
753            writeObjectID(getAddressValue(handleAddr));
754        }
755    }
756
757    protected void writeObjectArray(ObjArray array) throws IOException {
758        int headerSize = getArrayHeaderSize(true);
759        final int length = calculateArrayMaxLength(array.getLength(),
760                                                   headerSize,
761                                                   OBJ_ID_SIZE,
762                                                   "Object");
763        out.writeByte((byte) HPROF_GC_OBJ_ARRAY_DUMP);
764        writeObjectID(array);
765        out.writeInt(DUMMY_STACK_TRACE_ID);
766        out.writeInt(length);
767        writeObjectID(array.getKlass().getJavaMirror());
768        for (int index = 0; index < length; index++) {
769            OopHandle handle = array.getOopHandleAt(index);
770            writeObjectID(getAddressValue(handle));
771        }
772    }
773
774    protected void writePrimitiveArray(TypeArray array) throws IOException {
775        int headerSize = getArrayHeaderSize(false);
776        TypeArrayKlass tak = (TypeArrayKlass) array.getKlass();
777        final int type = (int) tak.getElementType();
778        final String typeName = tak.getElementTypeName();
779        final long typeSize = getSizeForType(type);
780        final int length = calculateArrayMaxLength(array.getLength(),
781                                                   headerSize,
782                                                   typeSize,
783                                                   typeName);
784        out.writeByte((byte) HPROF_GC_PRIM_ARRAY_DUMP);
785        writeObjectID(array);
786        out.writeInt(DUMMY_STACK_TRACE_ID);
787        out.writeInt(length);
788        out.writeByte((byte) type);
789        switch (type) {
790            case TypeArrayKlass.T_BOOLEAN:
791                writeBooleanArray(array, length);
792                break;
793            case TypeArrayKlass.T_CHAR:
794                writeCharArray(array, length);
795                break;
796            case TypeArrayKlass.T_FLOAT:
797                writeFloatArray(array, length);
798                break;
799            case TypeArrayKlass.T_DOUBLE:
800                writeDoubleArray(array, length);
801                break;
802            case TypeArrayKlass.T_BYTE:
803                writeByteArray(array, length);
804                break;
805            case TypeArrayKlass.T_SHORT:
806                writeShortArray(array, length);
807                break;
808            case TypeArrayKlass.T_INT:
809                writeIntArray(array, length);
810                break;
811            case TypeArrayKlass.T_LONG:
812                writeLongArray(array, length);
813                break;
814            default:
815                throw new RuntimeException(
816                    "Should not reach here: Unknown type: " + type);
817        }
818    }
819
820    private void writeBooleanArray(TypeArray array, int length) throws IOException {
821        for (int index = 0; index < length; index++) {
822             long offset = BOOLEAN_BASE_OFFSET + index * BOOLEAN_SIZE;
823             out.writeBoolean(array.getHandle().getJBooleanAt(offset));
824        }
825    }
826
827    private void writeByteArray(TypeArray array, int length) throws IOException {
828        for (int index = 0; index < length; index++) {
829             long offset = BYTE_BASE_OFFSET + index * BYTE_SIZE;
830             out.writeByte(array.getHandle().getJByteAt(offset));
831        }
832    }
833
834    private void writeShortArray(TypeArray array, int length) throws IOException {
835        for (int index = 0; index < length; index++) {
836             long offset = SHORT_BASE_OFFSET + index * SHORT_SIZE;
837             out.writeShort(array.getHandle().getJShortAt(offset));
838        }
839    }
840
841    private void writeIntArray(TypeArray array, int length) throws IOException {
842        for (int index = 0; index < length; index++) {
843             long offset = INT_BASE_OFFSET + index * INT_SIZE;
844             out.writeInt(array.getHandle().getJIntAt(offset));
845        }
846    }
847
848    private void writeLongArray(TypeArray array, int length) throws IOException {
849        for (int index = 0; index < length; index++) {
850             long offset = LONG_BASE_OFFSET + index * LONG_SIZE;
851             out.writeLong(array.getHandle().getJLongAt(offset));
852        }
853    }
854
855    private void writeCharArray(TypeArray array, int length) throws IOException {
856        for (int index = 0; index < length; index++) {
857             long offset = CHAR_BASE_OFFSET + index * CHAR_SIZE;
858             out.writeChar(array.getHandle().getJCharAt(offset));
859        }
860    }
861
862    private void writeFloatArray(TypeArray array, int length) throws IOException {
863        for (int index = 0; index < length; index++) {
864             long offset = FLOAT_BASE_OFFSET + index * FLOAT_SIZE;
865             out.writeFloat(array.getHandle().getJFloatAt(offset));
866        }
867    }
868
869    private void writeDoubleArray(TypeArray array, int length) throws IOException {
870        for (int index = 0; index < length; index++) {
871             long offset = DOUBLE_BASE_OFFSET + index * DOUBLE_SIZE;
872             out.writeDouble(array.getHandle().getJDoubleAt(offset));
873        }
874    }
875
876    protected void writeInstance(Instance instance) throws IOException {
877        out.writeByte((byte) HPROF_GC_INSTANCE_DUMP);
878        writeObjectID(instance);
879        out.writeInt(DUMMY_STACK_TRACE_ID);
880        Klass klass = instance.getKlass();
881        writeObjectID(klass.getJavaMirror());
882
883        ClassData cd = (ClassData) classDataCache.get(klass);
884
885        if (Assert.ASSERTS_ENABLED) {
886            Assert.that(cd != null, "can not get class data for " + klass.getName().asString() + klass.getAddress());
887        }
888        List fields = cd.fields;
889        int size = cd.instSize;
890        out.writeInt(size);
891        for (Iterator itr = fields.iterator(); itr.hasNext();) {
892            writeField((Field) itr.next(), instance);
893        }
894    }
895
896    //-- Internals only below this point
897
898    private void writeFieldDescriptors(List fields, InstanceKlass ik)
899        throws IOException {
900        // ik == null for instance fields.
901        out.writeShort((short) fields.size());
902        for (Iterator itr = fields.iterator(); itr.hasNext();) {
903            Field field = (Field) itr.next();
904            Symbol name = symTbl.probe(field.getID().getName());
905            writeSymbolID(name);
906            char typeCode = (char) field.getSignature().getByteAt(0);
907            int kind = signatureToHprofKind(typeCode);
908            out.writeByte((byte)kind);
909            if (ik != null) {
910                // static field
911                writeField(field, ik.getJavaMirror());
912            }
913        }
914    }
915
916    public static int signatureToHprofKind(char ch) {
917        switch (ch) {
918        case JVM_SIGNATURE_CLASS:
919        case JVM_SIGNATURE_ARRAY:
920            return HPROF_NORMAL_OBJECT;
921        case JVM_SIGNATURE_BOOLEAN:
922            return HPROF_BOOLEAN;
923        case JVM_SIGNATURE_CHAR:
924            return HPROF_CHAR;
925        case JVM_SIGNATURE_FLOAT:
926            return HPROF_FLOAT;
927        case JVM_SIGNATURE_DOUBLE:
928            return HPROF_DOUBLE;
929        case JVM_SIGNATURE_BYTE:
930            return HPROF_BYTE;
931        case JVM_SIGNATURE_SHORT:
932            return HPROF_SHORT;
933        case JVM_SIGNATURE_INT:
934            return HPROF_INT;
935        case JVM_SIGNATURE_LONG:
936            return HPROF_LONG;
937        default:
938            throw new RuntimeException("should not reach here");
939        }
940    }
941
942    private void writeField(Field field, Oop oop) throws IOException {
943        char typeCode = (char) field.getSignature().getByteAt(0);
944        switch (typeCode) {
945        case JVM_SIGNATURE_BOOLEAN:
946            out.writeBoolean(((BooleanField)field).getValue(oop));
947            break;
948        case JVM_SIGNATURE_CHAR:
949            out.writeChar(((CharField)field).getValue(oop));
950            break;
951        case JVM_SIGNATURE_BYTE:
952            out.writeByte(((ByteField)field).getValue(oop));
953            break;
954        case JVM_SIGNATURE_SHORT:
955            out.writeShort(((ShortField)field).getValue(oop));
956            break;
957        case JVM_SIGNATURE_INT:
958            out.writeInt(((IntField)field).getValue(oop));
959            break;
960        case JVM_SIGNATURE_LONG:
961            out.writeLong(((LongField)field).getValue(oop));
962            break;
963        case JVM_SIGNATURE_FLOAT:
964            out.writeFloat(((FloatField)field).getValue(oop));
965            break;
966        case JVM_SIGNATURE_DOUBLE:
967            out.writeDouble(((DoubleField)field).getValue(oop));
968            break;
969        case JVM_SIGNATURE_CLASS:
970        case JVM_SIGNATURE_ARRAY: {
971            if (VM.getVM().isCompressedOopsEnabled()) {
972              OopHandle handle = ((NarrowOopField)field).getValueAsOopHandle(oop);
973              writeObjectID(getAddressValue(handle));
974            } else {
975              OopHandle handle = ((OopField)field).getValueAsOopHandle(oop);
976              writeObjectID(getAddressValue(handle));
977            }
978            break;
979        }
980        default:
981            throw new RuntimeException("should not reach here");
982        }
983    }
984
985    private void writeHeader(int tag, int len) throws IOException {
986        out.writeByte((byte)tag);
987        out.writeInt(0); // current ticks
988        out.writeInt(len);
989    }
990
991    private void writeDummyTrace() throws IOException {
992        writeHeader(HPROF_TRACE, 3 * 4);
993        out.writeInt(DUMMY_STACK_TRACE_ID);
994        out.writeInt(0);
995        out.writeInt(0);
996    }
997
998    private void writeSymbols() throws IOException {
999        try {
1000            symTbl.symbolsDo(new SymbolTable.SymbolVisitor() {
1001                    public void visit(Symbol sym) {
1002                        try {
1003                            writeSymbol(sym);
1004                        } catch (IOException exp) {
1005                            throw new RuntimeException(exp);
1006                        }
1007                    }
1008                });
1009        } catch (RuntimeException re) {
1010            handleRuntimeException(re);
1011        }
1012    }
1013
1014    private void writeSymbol(Symbol sym) throws IOException {
1015        byte[] buf = sym.asString().getBytes("UTF-8");
1016        writeHeader(HPROF_UTF8, buf.length + OBJ_ID_SIZE);
1017        writeSymbolID(sym);
1018        out.write(buf);
1019    }
1020
1021    private void writeClasses() throws IOException {
1022        // write class list (id, name) association
1023        SystemDictionary sysDict = VM.getVM().getSystemDictionary();
1024        ClassLoaderDataGraph cldGraph = VM.getVM().getClassLoaderDataGraph();
1025        try {
1026            sysDict.allClassesDo(new SystemDictionary.ClassVisitor() {
1027                public void visit(Klass k) {
1028                    try {
1029                        Instance clazz = k.getJavaMirror();
1030                        writeHeader(HPROF_LOAD_CLASS, 2 * (OBJ_ID_SIZE + 4));
1031                        out.writeInt(serialNum);
1032                        writeObjectID(clazz);
1033                        out.writeInt(DUMMY_STACK_TRACE_ID);
1034                        writeSymbolID(k.getName());
1035                        serialNum++;
1036                    } catch (IOException exp) {
1037                        throw new RuntimeException(exp);
1038                    }
1039                }
1040            });
1041            cldGraph.allAnonymousKlassesDo(new ClassLoaderDataGraph.KlassVisitor() {
1042                public void visit(Klass k) {
1043                    try {
1044                        Instance clazz = k.getJavaMirror();
1045                        writeHeader(HPROF_LOAD_CLASS, 2 * (OBJ_ID_SIZE + 4));
1046                        out.writeInt(serialNum);
1047                        writeObjectID(clazz);
1048                        out.writeInt(DUMMY_STACK_TRACE_ID);
1049                        writeSymbolID(k.getName());
1050                        serialNum++;
1051                    } catch (IOException exp) {
1052                        throw new RuntimeException(exp);
1053                    }
1054                }
1055            });
1056        } catch (RuntimeException re) {
1057            handleRuntimeException(re);
1058        }
1059    }
1060
1061    // writes hprof binary file header
1062    private void writeFileHeader() throws IOException {
1063        // version string
1064        out.writeBytes(HPROF_HEADER_1_0_2);
1065        out.writeByte((byte)'\0');
1066
1067        // write identifier size. we use pointers as identifiers.
1068        out.writeInt(OBJ_ID_SIZE);
1069
1070        // timestamp -- file creation time.
1071        out.writeLong(System.currentTimeMillis());
1072    }
1073
1074    // writes unique ID for an object
1075    private void writeObjectID(Oop oop) throws IOException {
1076        OopHandle handle = (oop != null)? oop.getHandle() : null;
1077        long address = getAddressValue(handle);
1078        writeObjectID(address);
1079    }
1080
1081    private void writeSymbolID(Symbol sym) throws IOException {
1082        writeObjectID(getAddressValue(sym.getAddress()));
1083    }
1084
1085    private void writeObjectID(long address) throws IOException {
1086        if (OBJ_ID_SIZE == 4) {
1087            out.writeInt((int) address);
1088        } else {
1089            out.writeLong(address);
1090        }
1091    }
1092
1093    private long getAddressValue(Address addr) {
1094        return (addr == null)? 0L : dbg.getAddressValue(addr);
1095    }
1096
1097    // get all declared as well as inherited (directly/indirectly) fields
1098    private static List/*<Field>*/ getInstanceFields(InstanceKlass ik) {
1099        InstanceKlass klass = ik;
1100        List res = new ArrayList();
1101        while (klass != null) {
1102            List curFields = klass.getImmediateFields();
1103            for (Iterator itr = curFields.iterator(); itr.hasNext();) {
1104                Field f = (Field) itr.next();
1105                if (! f.isStatic()) {
1106                    res.add(f);
1107                }
1108            }
1109            klass = (InstanceKlass) klass.getSuper();
1110        }
1111        return res;
1112    }
1113
1114    // get size in bytes (in stream) required for given fields.  Note
1115    // that this is not the same as object size in heap. The size in
1116    // heap will include size of padding/alignment bytes as well.
1117    private int getSizeForFields(List fields) {
1118        int size = 0;
1119        for (Iterator itr = fields.iterator(); itr.hasNext();) {
1120            Field field = (Field) itr.next();
1121            char typeCode = (char) field.getSignature().getByteAt(0);
1122            switch (typeCode) {
1123            case JVM_SIGNATURE_BOOLEAN:
1124            case JVM_SIGNATURE_BYTE:
1125                size++;
1126                break;
1127            case JVM_SIGNATURE_CHAR:
1128            case JVM_SIGNATURE_SHORT:
1129                size += 2;
1130                break;
1131            case JVM_SIGNATURE_INT:
1132            case JVM_SIGNATURE_FLOAT:
1133                size += 4;
1134                break;
1135            case JVM_SIGNATURE_CLASS:
1136            case JVM_SIGNATURE_ARRAY:
1137                size += OBJ_ID_SIZE;
1138                break;
1139            case JVM_SIGNATURE_LONG:
1140            case JVM_SIGNATURE_DOUBLE:
1141                size += 8;
1142                break;
1143            default:
1144                throw new RuntimeException("should not reach here");
1145            }
1146        }
1147        return size;
1148    }
1149
1150    // We don't have allocation site info. We write a dummy
1151    // stack trace with this id.
1152    private static final int DUMMY_STACK_TRACE_ID = 1;
1153    private static final int EMPTY_FRAME_DEPTH = -1;
1154
1155    private DataOutputStream out;
1156    private FileOutputStream fos;
1157    private Debugger dbg;
1158    private ObjectHeap objectHeap;
1159    private SymbolTable symTbl;
1160
1161    // oopSize of the debuggee
1162    private int OBJ_ID_SIZE;
1163
1164    // Added for hprof file format 1.0.2 support
1165    private boolean useSegmentedHeapDump;
1166    private long currentSegmentStart;
1167
1168    private long BOOLEAN_BASE_OFFSET;
1169    private long BYTE_BASE_OFFSET;
1170    private long CHAR_BASE_OFFSET;
1171    private long SHORT_BASE_OFFSET;
1172    private long INT_BASE_OFFSET;
1173    private long LONG_BASE_OFFSET;
1174    private long FLOAT_BASE_OFFSET;
1175    private long DOUBLE_BASE_OFFSET;
1176    private long OBJECT_BASE_OFFSET;
1177
1178    private long BOOLEAN_SIZE;
1179    private long BYTE_SIZE;
1180    private long CHAR_SIZE;
1181    private long SHORT_SIZE;
1182    private long INT_SIZE;
1183    private long LONG_SIZE;
1184    private long FLOAT_SIZE;
1185    private long DOUBLE_SIZE;
1186
1187    private static class ClassData {
1188        int instSize;
1189        List fields;
1190
1191        ClassData(int instSize, List fields) {
1192            this.instSize = instSize;
1193            this.fields = fields;
1194        }
1195    }
1196
1197    private Map classDataCache = new HashMap(); // <InstanceKlass, ClassData>
1198}
1199