-
Notifications
You must be signed in to change notification settings - Fork 3
/
Pass1Parser.java
1282 lines (1162 loc) · 54.4 KB
/
Pass1Parser.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2008, 2023 SAP AG, IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* SAP AG - initial API and implementation
* IBM Corporation - additional debug information
* Netflix (Jason Koch) - refactors for increased performance and concurrency
*******************************************************************************/
package org.eclipse.mat.hprof;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.runtime.Platform;
import org.eclipse.mat.SnapshotException;
import org.eclipse.mat.collect.HashMapLongObject;
import org.eclipse.mat.hprof.ui.HprofPreferences;
import org.eclipse.mat.parser.model.ClassImpl;
import org.eclipse.mat.snapshot.MultipleSnapshotsException;
import org.eclipse.mat.snapshot.model.Field;
import org.eclipse.mat.snapshot.model.FieldDescriptor;
import org.eclipse.mat.snapshot.model.GCRootInfo;
import org.eclipse.mat.snapshot.model.IClass;
import org.eclipse.mat.snapshot.model.IObject;
import org.eclipse.mat.snapshot.model.IObject.Type;
import org.eclipse.mat.snapshot.model.IPrimitiveArray;
import org.eclipse.mat.snapshot.model.ObjectReference;
import org.eclipse.mat.util.IProgressListener;
import org.eclipse.mat.util.IProgressListener.Severity;
import org.eclipse.mat.util.MessageUtil;
import org.eclipse.mat.util.SimpleMonitor;
public class Pass1Parser extends AbstractParser
{
private static final Pattern PATTERN_OBJ_ARRAY = Pattern.compile("^(\\[+)L(.*);$"); //$NON-NLS-1$
private static final Pattern PATTERN_PRIMITIVE_ARRAY = Pattern.compile("^(\\[+)(.)$"); //$NON-NLS-1$
// New size of classes including per-instance fields
private final boolean NEWCLASSSIZE = HprofPreferences.useAdditionalClassReferences();
private final String METHODSASCLASSES = HprofPreferences.methodsAsClasses();
private HashMapLongObject<String> class2name = new HashMapLongObject<String>();
private HashMapLongObject<Long> thread2id = new HashMapLongObject<Long>();
private HashMapLongObject<StackFrame> id2frame = new HashMapLongObject<StackFrame>();
private HashMapLongObject<StackTrace> serNum2stackTrace = new HashMapLongObject<StackTrace>();
private HashMapLongObject<Long> classSerNum2id = new HashMapLongObject<Long>();
private HashMapLongObject<List<JavaLocal>> thread2locals = new HashMapLongObject<List<JavaLocal>>();
private HashMapLongObject<String> constantPool = new HashMapLongObject<String>();
private IHprofParserHandler handler;
private SimpleMonitor.Listener monitor;
private long previousArrayStart;
private long previousArrayUncompressedEnd;
private boolean foundCompressed;
private int biggestArrays[];
private long streamLength;
private final boolean verbose = Platform.inDebugMode() && HprofPlugin.getDefault().isDebugging()
&& Boolean.parseBoolean(Platform.getDebugOption("org.eclipse.mat.hprof/debug/parser")); //$NON-NLS-1$
private BufferingRafPositionInputStream in;
/** First stack frame address */
private static final long stackFrameBase = 0x100;
/** Alignment of stack frames - should not be stricter than rest of heap */
private static final long stackFrameAlign = 0x100;
public Pass1Parser(IHprofParserHandler handler, SimpleMonitor.Listener monitor,
HprofPreferences.HprofStrictness strictnessPreference)
{
super(strictnessPreference);
this.handler = handler;
this.monitor = monitor;
this.biggestArrays = new int[Runtime.getRuntime().availableProcessors()];
}
public void read(File file, String prefix, String dumpNrToRead, long estimatedLength) throws SnapshotException, IOException
{
// See http://java.net/downloads/heap-snapshot/hprof-binary-format.html
// or https://hg.openjdk.org/jdk8/jdk8/jdk/raw-file/tip/src/share/demo/jvmti/hprof/manual.html
in = new BufferingRafPositionInputStream(file, prefix, 0, 8*1024, 0);
int currentDumpNr = 0;
List<MultipleSnapshotsException.Context> ctxs = new ArrayList<MultipleSnapshotsException.Context>();
boolean foundDump = false;
try
{
// header & version
version = readVersion(in);
handler.addProperty(IHprofParserHandler.VERSION, version.toString());
// identifierSize (32 or 64 bit)
idSize = in.readInt();
if (idSize != 4 && idSize != 8)
throw new SnapshotException(Messages.Pass1Parser_Error_SupportedDumps);
handler.addProperty(IHprofParserHandler.IDENTIFIER_SIZE, String.valueOf(idSize));
// creation date
long date = in.readLong();
long prevTimeOffset = 0;
long timeWrap = 0;
// Actual file size
long fileSize0 = file.length();
// Estimated stream length
long fileSize = estimatedLength;
long curPos = in.position();
recordLoop: while (true)
{
if (monitor.isProbablyCanceled())
throw new IProgressListener.OperationCanceledException();
monitor.totalWorkDone(in.workPosition() / 1000);
/*
* Use this instead of
* record = in.readUnsignedByte();
* so that we can detect the end of a zipped stream.
*/
int r = in.read();
if (r == -1)
break;
int record = r & 0xff;
long timeOffset = in.readUnsignedInt(); // time stamp in microseconds
if (timeOffset < prevTimeOffset)
{
// Wrap after 4294 seconds
timeWrap += 1L << 32;
}
prevTimeOffset = timeOffset;
long length = in.readUnsignedInt();
if (verbose)
System.out.println("Read record type " + record + ", length " + length + " at position 0x" + Long.toHexString(curPos)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (curPos + 9 >= fileSize && fileSize > fileSize0 && curPos + 9 + length >= 0x100000000L)
{
/*
* Gzip has uncertain stream length though the lower 32-bits are correct,
* so make the estimated size grow.
*/
while (fileSize < curPos + 9)
{
fileSize += 0x100000000L;
}
}
length = updateLengthIfNecessary(fileSize, curPos, record, length, monitor);
if (length < 0)
throw new SnapshotException(MessageUtil.format(Messages.Pass1Parser_Error_IllegalRecordLength,
length, Long.toHexString(in.position() - 4), Integer.toHexString(record), Long.toHexString(curPos)));
if (curPos + 9 + length > fileSize)
{
switch (strictnessPreference)
{
case STRICTNESS_STOP:
// If we are sure about the file size
if (fileSize == fileSize0 || fileSize < 0x10000000L)
throw new SnapshotException(Messages.HPROFStrictness_Stopped, new SnapshotException(
MessageUtil.format(Messages.Pass1Parser_Error_invalidHPROFFile, length,
fileSize - curPos - 9, Integer.toHexString(record), Long.toHexString(curPos))));
case STRICTNESS_WARNING:
case STRICTNESS_PERMISSIVE:
monitor.sendUserMessage(Severity.WARNING,
MessageUtil.format(Messages.Pass1Parser_Error_invalidHPROFFile, length,
fileSize - curPos - 9, Integer.toHexString(record), Long.toHexString(curPos)), null);
break;
default:
throw new SnapshotException(Messages.HPROFStrictness_Unhandled_Preference);
}
}
switch (record)
{
case Constants.Record.STRING_IN_UTF8:
if (((int) (length - idSize) < 0))
throw new SnapshotException(MessageUtil.format(
Messages.Pass1Parser_Error_IllegalRecordLength, length, Long.toHexString(in.position() - 4),
Integer.toHexString(record), Long.toHexString(curPos)));
readString(length);
break;
case Constants.Record.LOAD_CLASS:
readLoadClass();
break;
case Constants.Record.UNLOAD_CLASS:
readUnloadClass();
break;
case Constants.Record.STACK_FRAME:
readStackFrame(curPos, length);
break;
case Constants.Record.STACK_TRACE:
readStackTrace(length);
break;
case Constants.Record.HEAP_DUMP:
case Constants.Record.HEAP_DUMP_SEGMENT:
long dumpTime = date + (timeWrap + timeOffset) / 1000;
if (dumpMatches(currentDumpNr, dumpNrToRead))
{
if (!foundDump)
{
handler.addProperty(IHprofParserHandler.CREATION_DATE, String.valueOf(dumpTime));
foundDump = true;
}
long posnext = readDumpSegments(length);
if (posnext < curPos + length)
{
// Truncated file, so could not read to end of segment
curPos = posnext;
break recordLoop;
}
}
else
checkSkipBytes(length);
if (ctxs.size() < currentDumpNr + 1)
{
MultipleSnapshotsException.Context ctx = new MultipleSnapshotsException.Context(dumpIdentifier(currentDumpNr));
ctx.setDescription(MessageUtil.format(Messages.Pass1Parser_HeapDumpCreated, new Date(dumpTime)));
ctxs.add(ctx);
}
if (record == Constants.Record.HEAP_DUMP)
currentDumpNr++;
break;
case Constants.Record.HEAP_DUMP_END:
currentDumpNr++;
checkSkipBytes(length);
break;
case Constants.Record.ALLOC_SITES:
case Constants.Record.HEAP_SUMMARY:
case Constants.Record.START_THREAD:
case Constants.Record.END_THREAD:
case Constants.Record.CPU_SAMPLES:
case Constants.Record.CONTROL_SETTINGS:
checkSkipBytes(length);
break;
default:
switch (strictnessPreference)
{
case STRICTNESS_STOP:
throw new SnapshotException(Messages.HPROFStrictness_Stopped, new SnapshotException(
MessageUtil.format(Messages.Pass1Parser_UnexpectedRecord,
Integer.toHexString(record), length, Long.toHexString(curPos))));
case STRICTNESS_WARNING:
case STRICTNESS_PERMISSIVE:
monitor.sendUserMessage(
Severity.WARNING,
MessageUtil.format(Messages.Pass1Parser_UnexpectedRecord,
Integer.toHexString(record), length, Long.toHexString(curPos)), null);
checkSkipBytes(length);
break;
default:
throw new SnapshotException(Messages.HPROFStrictness_Unhandled_Preference);
}
break;
}
curPos = in.position();
}
streamLength = curPos;
}
finally
{
try
{
in.close();
}
catch (IOException ignore)
{}
}
handler.addProperty(IHprofParserHandler.STREAM_LENGTH, Long.toString(streamLength()));
if (!foundDump)
throw new SnapshotException(MessageUtil.format(Messages.Pass1Parser_Error_NoHeapDumpIndexFound,
currentDumpNr, file.getName(), dumpNrToRead));
if (currentDumpNr > 1)
{
if (dumpNrToRead == null)
{
MultipleSnapshotsException mse = new MultipleSnapshotsException(MessageUtil.format(Messages.Pass1Parser_HeapDumpsFound, currentDumpNr));
for (MultipleSnapshotsException.Context runtime : ctxs)
{
mse.addContext(runtime);
}
throw mse;
}
monitor.sendUserMessage(IProgressListener.Severity.INFO, MessageUtil.format(
Messages.Pass1Parser_Info_UsingDumpIndex, currentDumpNr, file.getName(), dumpNrToRead),
null);
}
if (serNum2stackTrace.size() > 0)
dumpThreads();
}
/**
* Total of the size of the k biggest object arrays.
* k = number of processors
* Use to estimate how much more memory parallel parsing will use.
* @return size in bytes
*/
public long biggestArrays()
{
long total = 0;
for (int s : biggestArrays)
{
total += s;
}
return total;
}
/**
* Find the uncompressed stream length (in case the dump is compressed).
* @return the length in bytes
*/
public long streamLength()
{
return streamLength;
}
private void readString(long length) throws IOException
{
long id = in.readID(idSize);
byte[] chars = new byte[(int) (length - idSize)];
in.readFully(chars);
constantPool.put(id, new String(chars, "UTF-8")); //$NON-NLS-1$
}
private void readLoadClass() throws IOException
{
long classSerNum = in.readUnsignedInt(); // used in stacks frames
long classID = in.readID(idSize);
checkSkipBytes(4); // stack trace
long nameID = in.readID(idSize);
String className0 = getStringConstant(nameID);
int methodArgs = className0.indexOf('(');
String className;
if (methodArgs < 0)
className = className0.replace('/', '.');
else
className = className0.substring(0, methodArgs).replace('/', '.') + className0.substring(methodArgs);
class2name.put(classID, className);
classSerNum2id.put(classSerNum, classID);
}
private void readUnloadClass() throws IOException
{
long classSerNum = in.readUnsignedInt(); // used in stacks frames
if (classSerNum2id.containsKey(classSerNum))
{
long classID = classSerNum2id.get(classSerNum);
// class2name only holds active classes
class2name.remove(classID);
}
else
{
// For example: sun_jdk6_31_hprofagent_compressedOops.hprof
monitor.sendUserMessage(IProgressListener.Severity.WARNING, MessageUtil.format(Messages.Pass1Parser_UnloadClassNotFound, classSerNum, Long.toHexString(in.position() - 5)), null);
}
}
private void readStackFrame(long segmentStartPos, long length) throws IOException
{
long frameId = in.readID(idSize);
long methodName = in.readID(idSize);
long methodSig = in.readID(idSize);
long srcFile = in.readID(idSize);
long classSerNum = in.readUnsignedInt();
int lineNr = in.readInt(); // can be negative
StackFrame frame = new StackFrame(frameId, lineNr, getStringConstant(methodName), getStringConstant(methodSig),
getStringConstant(srcFile), classSerNum, segmentStartPos);
id2frame.put(frameId, frame);
}
private void readStackTrace(long length) throws IOException
{
long stackTraceNr = in.readUnsignedInt();
long threadNr = in.readUnsignedInt();
long frameCount = in.readUnsignedInt();
long[] frameIds = new long[(int) frameCount];
for (int i = 0; i < frameCount; i++)
{
frameIds[i] = in.readID(idSize);
}
StackTrace stackTrace = new StackTrace(stackTraceNr, threadNr, frameIds);
serNum2stackTrace.put(stackTraceNr, stackTrace);
}
private long readDumpSegments(long length) throws IOException, SnapshotException
{
long segmentStartPos = in.position();
long segmentsEndPos = segmentStartPos + length;
subrecordLoop: while (segmentStartPos < segmentsEndPos)
{
long workDone = segmentStartPos / 1000;
if (this.monitor.getWorkDone() < workDone)
{
if (this.monitor.isProbablyCanceled())
throw new IProgressListener.OperationCanceledException();
this.monitor.totalWorkDone(workDone);
}
int segmentType = -1;
try
{
segmentType = in.readUnsignedByte();
if (verbose)
System.out.println(" Read heap sub-record type " + segmentType + " at position 0x" + Long.toHexString(segmentStartPos)); //$NON-NLS-1$ //$NON-NLS-2$
switch (segmentType)
{
case Constants.DumpSegment.ROOT_UNKNOWN:
readGC(GCRootInfo.Type.UNKNOWN, 0);
break;
case Constants.DumpSegment.ROOT_THREAD_OBJECT:
readGCThreadObject(GCRootInfo.Type.THREAD_OBJ);
break;
case Constants.DumpSegment.ROOT_JNI_GLOBAL:
readGC(GCRootInfo.Type.NATIVE_STATIC, idSize);
break;
case Constants.DumpSegment.ROOT_JNI_LOCAL:
readGCWithThreadContext(GCRootInfo.Type.NATIVE_LOCAL, true);
break;
case Constants.DumpSegment.ROOT_JAVA_FRAME:
readGCWithThreadContext(GCRootInfo.Type.JAVA_LOCAL, true);
break;
case Constants.DumpSegment.ROOT_NATIVE_STACK:
readGCWithThreadContext(GCRootInfo.Type.NATIVE_STACK, false);
break;
case Constants.DumpSegment.ROOT_STICKY_CLASS:
readGC(GCRootInfo.Type.SYSTEM_CLASS, 0);
break;
case Constants.DumpSegment.ROOT_THREAD_BLOCK:
readGCWithThreadContext(GCRootInfo.Type.THREAD_BLOCK, false);
break;
case Constants.DumpSegment.ROOT_MONITOR_USED:
readGC(GCRootInfo.Type.BUSY_MONITOR, 0);
break;
case Constants.DumpSegment.CLASS_DUMP:
readClassDump(segmentStartPos);
break;
case Constants.DumpSegment.INSTANCE_DUMP:
readInstanceDump(segmentStartPos);
break;
case Constants.DumpSegment.OBJECT_ARRAY_DUMP:
readObjectArrayDump(segmentStartPos);
break;
case Constants.DumpSegment.PRIMITIVE_ARRAY_DUMP:
readPrimitiveArrayDump(segmentStartPos);
break;
default:
throw new SnapshotException(MessageUtil.format(Messages.Pass1Parser_Error_InvalidHeapDumpFile,
Integer.toHexString(segmentType), Long.toHexString(segmentStartPos)));
}
}
catch (EOFException e)
{
switch (strictnessPreference)
{
case STRICTNESS_STOP:
throw new SnapshotException(Messages.HPROFStrictness_Stopped, new SnapshotException(
MessageUtil.format(Messages.Pass1Parser_Error_invalidHPROFFile, segmentsEndPos - segmentStartPos,
in.position() - segmentStartPos, Integer.toHexString(segmentType), Long.toHexString(segmentStartPos)), e));
case STRICTNESS_WARNING:
case STRICTNESS_PERMISSIVE:
/*
* Recover from early end of file.
* The EOFException occurred in this record
* so the start of the record is an okay
* end point.
*/
monitor.sendUserMessage(Severity.WARNING, MessageUtil.format(
Messages.Pass1Parser_ExceptionReadingSubrecord,
Integer.toHexString(segmentType), Long.toHexString(in.position()), Long.toHexString(segmentStartPos), segmentStartPos - (segmentsEndPos - length)), e);
break subrecordLoop;
}
}
segmentStartPos = in.position();
}
if (verbose)
System.out.println(" Finished heap sub-records."); //$NON-NLS-1$
if (segmentStartPos != segmentsEndPos)
{
switch (strictnessPreference)
{
case STRICTNESS_STOP:
throw new SnapshotException(Messages.HPROFStrictness_Stopped,
new SnapshotException(
MessageUtil.format(Messages.Pass1Parser_UnexpectedEndPosition,
Long.toHexString(segmentsEndPos - length), length,
Long.toHexString(segmentStartPos),
Long.toHexString(segmentsEndPos))));
case STRICTNESS_WARNING:
case STRICTNESS_PERMISSIVE:
monitor.sendUserMessage(Severity.WARNING, MessageUtil.format(
Messages.Pass1Parser_UnexpectedEndPosition,
Long.toHexString(segmentsEndPos - length), length,
Long.toHexString(segmentStartPos), Long.toHexString(segmentsEndPos)), null);
break;
default:
throw new SnapshotException(Messages.HPROFStrictness_Unhandled_Preference);
}
}
return segmentStartPos;
}
/**
* Guaranteed skip of skips, and that
* we can read the last byte, so we haven't
* skipped beyond the end of the file
* @param s
* @return bytes skipped
* @throws IOException if unable to skip the bytes
* or read the last byte
*/
private long checkSkipBytes(long s) throws IOException
{
if (s > 0)
{
if (s > 1)
{
// Since skipBytes returns only an int, we might have to call
// it more than once.
long left = s - 1;
while (left > 0)
{
long toSkip = Math.min((long) Integer.MAX_VALUE, left);
int skipped = in.skipBytes(toSkip);
if (skipped < toSkip)
{
throw new EOFException();
}
left -= skipped;
}
}
in.readByte();
}
return s;
}
private void readGCThreadObject(int gcType) throws IOException
{
long id = in.readID(idSize);
int threadSerialNo = in.readInt();
thread2id.put(threadSerialNo, id);
handler.addGCRoot(id, 0, gcType);
checkSkipBytes(4);
}
private void readGC(int gcType, int skip) throws IOException
{
long id = in.readID(idSize);
handler.addGCRoot(id, 0, gcType);
if (skip > 0)
checkSkipBytes(skip);
}
private void readGCWithThreadContext(int gcType, boolean hasLineInfo) throws IOException
{
long id = in.readID(idSize);
int threadSerialNo = in.readInt();
Long tid = thread2id.get(threadSerialNo);
if (tid != null)
{
// With METHODSASCLASSES instead we add references from the stack
// frame to the local
if (!((HprofPreferences.FRAMES_ONLY.equals(METHODSASCLASSES)
|| HprofPreferences.RUNNING_METHODS_AS_CLASSES.equals(METHODSASCLASSES)) && hasLineInfo))
handler.addGCRoot(id, tid, gcType);
}
else
{
handler.addGCRoot(id, 0, gcType);
}
if (hasLineInfo)
{
int lineNumber = in.readInt();
List<JavaLocal> locals = thread2locals.get(threadSerialNo);
if (locals == null)
{
locals = new ArrayList<JavaLocal>();
thread2locals.put(threadSerialNo, locals);
}
locals.add(new JavaLocal(id, lineNumber, gcType));
}
}
private void readClassDump(long segmentStartPos) throws IOException
{
long address = in.readID(idSize);
checkSkipBytes(4); // stack trace serial number
long superClassObjectId = in.readID(idSize);
long classLoaderObjectId = in.readID(idSize);
// read signers, protection domain, reserved ids (2)
long signersId = in.readID(idSize);
long protectionDomainId = in.readID(idSize);
long reserved1Id = in.readID(idSize);
long reserved2Id = in.readID(idSize);
int extraDummyStatics = 0;
if (NEWCLASSSIZE)
{
// Always add signers / protectionDomain
extraDummyStatics += 2;
if (reserved1Id != 0)
++extraDummyStatics;
if (reserved2Id != 0)
++extraDummyStatics;
}
// instance size
int instsize = in.readInt();
// constant pool: u2 ( u2 u1 value )*
int constantPoolSize = in.readUnsignedShort();
Field[] constantPool = new Field[constantPoolSize];
for (int ii = 0; ii < constantPoolSize; ii++)
{
int index = in.readUnsignedShort(); // index
String name = "<constant pool["+index+"]>"; //$NON-NLS-1$ //$NON-NLS-2$
byte type = in.readByte();
Object value = readValue(in, null, type);
constantPool[ii] = new Field(name, type, value);
}
// static fields: u2 num ( name ID, u1 type, value)
int numStaticFields = in.readUnsignedShort();
Field[] statics = new Field[numStaticFields + extraDummyStatics];
for (int ii = 0; ii < numStaticFields; ii++)
{
long nameId = in.readID(idSize);
String name = getStringConstant(nameId);
byte type = in.readByte();
Object value = readValue(in, null, type);
statics[ii] = new Field(name, type, value);
}
if (NEWCLASSSIZE)
{
int si = numStaticFields;
statics[si++] = new Field("<signers>", Type.OBJECT, signersId == 0 ? null : new ObjectReference(null, signersId)); //$NON-NLS-1$
statics[si++] = new Field("<protectionDomain>", Type.OBJECT, protectionDomainId == 0 ? null : new ObjectReference(null, protectionDomainId)); //$NON-NLS-1$
if (reserved1Id != 0)
statics[si++] = new Field("<reserved1>", Type.OBJECT, reserved1Id == 0 ? null : new ObjectReference(null, reserved1Id)); //$NON-NLS-1$
if (reserved2Id != 0)
statics[si++] = new Field("<reserved2>", Type.OBJECT, reserved2Id == 0 ? null : new ObjectReference(null, reserved2Id)); //$NON-NLS-1$
Field all[] = new Field[statics.length + constantPool.length];
System.arraycopy(statics, 0, all, 0, statics.length);
System.arraycopy(constantPool, 0, all, statics.length, constantPool.length);
statics = all;
}
// instance fields: u2 num ( name ID, u1 type )
int numInstanceFields = in.readUnsignedShort();
FieldDescriptor[] fields = new FieldDescriptor[numInstanceFields];
for (int ii = 0; ii < numInstanceFields; ii++)
{
long nameId = in.readID(idSize);
String name = getStringConstant(nameId);
byte type = in.readByte();
fields[ii] = new FieldDescriptor(name, type);
}
// get name
String className = class2name.get(address);
if (className == null)
className = "unknown-name@0x" + Long.toHexString(address); //$NON-NLS-1$
if (className.charAt(0) == '[') // quick check if array at hand
{
// fix object class names
Matcher matcher = PATTERN_OBJ_ARRAY.matcher(className);
if (matcher.matches())
{
int l = matcher.group(1).length();
StringBuilder classNameBuilder = new StringBuilder(matcher.group(2));
for (int ii = 0; ii < l; ii++)
classNameBuilder.append("[]"); //$NON-NLS-1$
className = classNameBuilder.toString();
}
// primitive arrays
matcher = PATTERN_PRIMITIVE_ARRAY.matcher(className);
if (matcher.matches())
{
int count = matcher.group(1).length() - 1;
className = "unknown[]"; //$NON-NLS-1$
char signature = matcher.group(2).charAt(0);
for (int ii = 0; ii < IPrimitiveArray.SIGNATURES.length; ii++)
{
if (IPrimitiveArray.SIGNATURES[ii] == (byte) signature)
{
className = IPrimitiveArray.TYPE[ii];
break;
}
}
StringBuilder classNameBuilder = new StringBuilder(className);
for (int ii = 0; ii < count; ii++)
classNameBuilder.append("[]"); //$NON-NLS-1$
className = classNameBuilder.toString();
}
}
ClassImpl clazz = new ClassImpl(address, className, superClassObjectId, classLoaderObjectId, statics, fields);
// This will be replaced by a size calculated from the field sizes
clazz.setHeapSizePerInstance(instsize);
handler.addClass(clazz, segmentStartPos, idSize, instsize);
// TODO do we actually need this code?
// if so - move it to HprofParserHandlerImpl
// instanceaddress2classID was a HashMapLongObject<Long>
/*
// Just in case the superclass is missing
if (superClassObjectId != 0 && handler.lookupClass(superClassObjectId) == null)
{
// Try to calculate how big the superclass should be
int ownFieldsSize = 0;
for (FieldDescriptor field : clazz.getFieldDescriptors())
{
int type = field.getType();
if (type == IObject.Type.OBJECT)
ownFieldsSize += idSize;
else
ownFieldsSize += IPrimitiveArray.ELEMENT_SIZE[type];
}
int supersize = Math.max(instsize - ownFieldsSize, 0);
// A real size of an instance will override this
handler.reportRequiredClass(superClassObjectId, supersize);
}
// Check / set types of classes
if (instanceaddress2classID.containsKey(address))
{
// Already seen an instance dump for class type
long classId = instanceaddress2classID.get(address);
IClass type = handler.lookupClass(classId);
if (type instanceof ClassImpl)
{
clazz.setClassInstance((ClassImpl)type);
}
}
for (Iterator<Entry<Long>>it = instanceaddress2classID.entries(); it.hasNext(); )
{
Entry<Long>e = it.next();
if (e.getValue() == address)
{
// Existing class has this class as its type
IClass base = handler.lookupClass(e.getKey());
if (base instanceof ClassImpl)
{
ClassImpl baseCls = (ClassImpl)base;
baseCls.setClassInstance(clazz);
}
}
}
*/
}
private void readInstanceDump(long segmentStartPos) throws IOException
{
long address = in.readID(idSize);
checkSkipBytes(4); // stack trace serial
long classID = in.readID(idSize);
int payload = in.readInt();
checkSkipBytes(payload);
handler.reportInstanceWithClass(address, segmentStartPos, classID, payload);
}
private void readObjectArrayDump(long segmentStartPos) throws IOException
{
long address = in.readID(idSize);
if (!foundCompressed && idSize == 8 && address > previousArrayStart && address < previousArrayUncompressedEnd)
{
monitor.sendUserMessage(
Severity.INFO,
MessageUtil.format(Messages.Pass1Parser_DetectedCompressedReferences,
Long.toHexString(address), Long.toHexString(previousArrayStart)), null);
handler.addProperty(IHprofParserHandler.REFERENCE_SIZE, "4"); //$NON-NLS-1$
foundCompressed = true;
}
checkSkipBytes(4); // stack trace serial
int size = in.readInt();
long arrayClassObjectID = in.readID(idSize);
checkSkipBytes((long) size * idSize);
previousArrayStart = address;
previousArrayUncompressedEnd = address + 16 + (long)size * 8;
if (size > biggestArrays[0])
{
biggestArrays[0] = size;
Arrays.sort(biggestArrays);
}
handler.reportInstanceOfObjectArray(address, segmentStartPos, arrayClassObjectID);
}
private void readPrimitiveArrayDump(long segmentStartPos) throws SnapshotException, IOException
{
long address = in.readID(idSize);
checkSkipBytes(4);
int size = in.readInt();
byte elementType = in.readByte();
if ((elementType < IPrimitiveArray.Type.BOOLEAN) || (elementType > IPrimitiveArray.Type.LONG))
throw new SnapshotException(Messages.Pass1Parser_Error_IllegalType);
int elementSize = IPrimitiveArray.ELEMENT_SIZE[elementType];
checkSkipBytes((long) elementSize * size);
handler.reportInstanceOfPrimitiveArray(address, segmentStartPos, elementType);
}
private String getStringConstant(long address)
{
if (address == 0L)
return ""; //$NON-NLS-1$
String result = constantPool.get(address);
return result == null ? MessageUtil.format(Messages.Pass1Parser_Error_UnresolvedName, Long.toHexString(address)) : result;
}
private void dumpThreads() throws IOException
{
// noticed that one stack trace with empty stack is always reported,
// even if the dump has no call stacks info
if (serNum2stackTrace == null || serNum2stackTrace.size() <= 1)
return;
PrintWriter out = null;
String outputName = handler.getSnapshotInfo().getPrefix() + "threads"; //$NON-NLS-1$
try
{
out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputName), "UTF-8")); //$NON-NLS-1$
Iterator<StackTrace> it = serNum2stackTrace.values();
while (it.hasNext())
{
StackTrace stack = it.next();
Long tid = thread2id.get(stack.threadSerialNr);
if (tid == null)
continue;
String threadId = tid == null ? "<unknown>" : "0x" + Long.toHexString(tid); //$NON-NLS-1$ //$NON-NLS-2$
out.println("Thread " + threadId); //$NON-NLS-1$
out.println(stack);
out.println(" locals:"); //$NON-NLS-1$
List<JavaLocal> locals = thread2locals.get(stack.threadSerialNr);
if (locals != null)
{
for (JavaLocal javaLocal : locals)
{
out.println(" objectId=0x" + Long.toHexString(javaLocal.objectId) + ", line=" + javaLocal.lineNumber); //$NON-NLS-1$ //$NON-NLS-2$
}
}
if (HprofPreferences.FRAMES_ONLY.equals(METHODSASCLASSES)
|| HprofPreferences.RUNNING_METHODS_AS_CLASSES.equals(METHODSASCLASSES))
{
// Add the stack frames as extra locals
for (int i = 0; i < stack.frameIds.length; ++i)
{
long frameI = stack.frameIds[i];
StackFrame frame = id2frame.get(frameI);
{
long frameAddress = stackFrameBase + frame.frameId * stackFrameAlign;
out.println(" objectId=0x" + Long.toHexString(frameAddress) + ", line=" + (i)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
out.println();
}
out.flush();
this.monitor.sendUserMessage(Severity.INFO,
MessageUtil.format(Messages.Pass1Parser_Info_WroteThreadsTo, outputName), null);
}
catch (IOException e)
{
this.monitor.sendUserMessage(Severity.WARNING,
MessageUtil.format(Messages.Pass1Parser_Error_WritingThreadsInformation), e);
}
finally
{
if (out != null)
{
try
{
out.close();
}
catch (Exception ignore)
{
// $JL-EXC$
}
}
}
if (HprofPreferences.FRAMES_ONLY.equals(METHODSASCLASSES)
|| HprofPreferences.RUNNING_METHODS_AS_CLASSES.equals(METHODSASCLASSES))
{
stackFramesAsObjects();
}
else
{
fixupNativeClasses();
}
}
/**
* Fix up any special classes introduced in an exported HPROF file.
*/
private void fixupNativeClasses()
{
IClass nm = handler.lookupClassByName(NATIVE_MEMORY, false);
IClass nt = handler.lookupClassByName(NATIVE_MEMORY_TYPE, false);
IClass mt = handler.lookupClassByName(METHOD_TYPE, false);
IClass m = handler.lookupClassByName(METHOD, false);
IClass s = handler.lookupClassByName(STACK_FRAME, false);
if (nm instanceof ClassImpl && nt instanceof ClassImpl && (m instanceof ClassImpl || s instanceof ClassImpl))
{
((ClassImpl) nm).setClassInstance((ClassImpl) nt);
((ClassImpl) nt).setClassInstance((ClassImpl) nt);
if (mt instanceof ClassImpl)
{
((ClassImpl) mt).setClassInstance((ClassImpl) nt);
if (m instanceof ClassImpl)
((ClassImpl) m).setClassInstance((ClassImpl) mt);
}
if (s instanceof ClassImpl)
((ClassImpl) s).setClassInstance((ClassImpl) nt);
}
}
private ClassImpl genClass(long nextAddress, String className, long superClass, long classLoader,
Field flds[], FieldDescriptor desc[], IClass clsType) throws IOException
{
IClass existing = handler.lookupClassByName(className, false);
if (existing instanceof ClassImpl)
return (ClassImpl)existing;
ClassImpl newClass = new ClassImpl(nextAddress, className, superClass, classLoader, flds, desc);
class2name.put(nextAddress, className);
// This will be replaced by a size calculated from the field sizes
newClass.setHeapSizePerInstance(0);
if (clsType instanceof ClassImpl)
newClass.setClassInstance((ClassImpl) clsType);
handler.addClass(newClass, -1, idSize, 0);
return newClass;
}
private long nextFreeAddr(long addr)
{
while (class2name.containsKey(addr))
{
addr += stackFrameAlign;
}
return addr;
}
private void stackFramesAsObjects() throws IOException
{
final long rootLoader = 0;