-
Notifications
You must be signed in to change notification settings - Fork 3
/
ExportHprof.java
2765 lines (2595 loc) · 101 KB
/
ExportHprof.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) 2018, 2023 IBM Corporation
* 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:
* Andrew Johnson/IBM Corporation - initial API and implementation
*******************************************************************************/
/**
* Create a HPROF format file from a snapshot, whatever the original dump format.
*
* Problems with current snapshot API:
* finding thread to GCroots linkage
* - have to presume a ROOT_THREAD_OBJECT and getOutboundReferences and use
* ThreadToLocalReference
* parsing stackframes to classes, methods
* - have to parse out string format
* converting class name in stackframe to class
* - could be multiple classes with the same name, information loss
* converting object and stack frame to GC root with type
* - If JNI local reference and Java local reference to same object in different frame, could get the type swapped.
*
*/
package org.eclipse.mat.hprof;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.mat.SnapshotException;
import org.eclipse.mat.collect.ArrayLong;
import org.eclipse.mat.collect.BitField;
import org.eclipse.mat.collect.SetInt;
import org.eclipse.mat.hprof.AbstractParser.Constants;
import org.eclipse.mat.hprof.describer.HprofContentDescriber;
import org.eclipse.mat.hprof.describer.Version;
import org.eclipse.mat.hprof.ui.HprofPreferences;
import org.eclipse.mat.query.IQuery;
import org.eclipse.mat.query.IResult;
import org.eclipse.mat.query.annotations.Argument;
import org.eclipse.mat.query.annotations.Argument.Advice;
import org.eclipse.mat.query.annotations.CommandName;
import org.eclipse.mat.query.annotations.HelpUrl;
import org.eclipse.mat.query.annotations.Icon;
import org.eclipse.mat.snapshot.ISnapshot;
import org.eclipse.mat.snapshot.SnapshotInfo;
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.GCRootInfo.Type;
import org.eclipse.mat.snapshot.model.IClass;
import org.eclipse.mat.snapshot.model.IInstance;
import org.eclipse.mat.snapshot.model.IObject;
import org.eclipse.mat.snapshot.model.IObjectArray;
import org.eclipse.mat.snapshot.model.IPrimitiveArray;
import org.eclipse.mat.snapshot.model.IStackFrame;
import org.eclipse.mat.snapshot.model.IThreadStack;
import org.eclipse.mat.snapshot.model.NamedReference;
import org.eclipse.mat.snapshot.model.ObjectReference;
import org.eclipse.mat.snapshot.model.ThreadToLocalReference;
import org.eclipse.mat.snapshot.query.IHeapObjectArgument;
import org.eclipse.mat.snapshot.query.SnapshotQuery;
import org.eclipse.mat.util.IProgressListener;
import org.eclipse.mat.util.MessageUtil;
import org.eclipse.mat.util.SilentProgressListener;
@CommandName("export_hprof")
@Icon("/icons/export_hprof.gif")
@HelpUrl("/org.eclipse.mat.ui.help/tasks/exportdump.html")
public class ExportHprof implements IQuery
{
/** A dummy stack trace */
private static final int UNKNOWN_STACK_TRACE_SERIAL = 1;
/** No stack frame available */
private static final int UNKNOWN_STACK_FRAME_SERIAL = -1;
private static final Charset UTF8 = Charset.forName("UTF-8"); //$NON-NLS-1$
@Argument
public ISnapshot snapshot;
@Argument(advice = Advice.SAVE)
public File output;
@Argument(isMandatory = false)
public boolean compress;
@Argument(isMandatory = false)
public boolean chunked;
public enum RedactType
{
NONE("none"), //$NON-NLS-1$
NAMES("names"), //$NON-NLS-1$
BASIC("basic"), //$NON-NLS-1$
FULL("full"); //$NON-NLS-1$
String type;
private RedactType(String s)
{
type = s;
}
}
@Argument(isMandatory = false)
public RedactType redact = RedactType.NONE;
@Argument(isMandatory = false, advice = Advice.SAVE, flag = "map")
public File mapFile;
@Argument(isMandatory = false, advice = Advice.CLASS_NAME_PATTERN, flag = "skip")
public Pattern skipPattern = Pattern.compile("java\\..*|boolean|byte|char|short|int|long|float|double|void|<[a-z ]+>"); //$NON-NLS-1$
@Argument(isMandatory = false, advice = Advice.CLASS_NAME_PATTERN, flag = "avoid")
public Pattern avoidPattern = Pattern.compile(Messages.ExportHprof_AvoidExample);
@Argument(isMandatory = false)
public boolean undo;
@Argument(flag = Argument.UNFLAGGED, isMandatory = false)
public IHeapObjectArgument objects;
/** Dump class fields as a instance dump */
@Argument(isMandatory = false, flag = "classInstance")
public boolean classesAsInstances = false;
@Argument(isMandatory = false)
/** How big a heap dump segment can grow before it needs to be split */
public long segsize = 0xffffffffL;
/** Strings to HPROF ID */
HashMap<String, Integer> stringToID = new HashMap<String, Integer>();
int nextStringID = 1;
/** Thread object ID to HPROF thread serial number */
HashMap<Integer, Integer> threadToSerial = new HashMap<Integer, Integer>();
/** Thread object ID to HPROF stack serial number */
HashMap<Integer, Integer> threadToStack = new HashMap<Integer, Integer>();
/** Whether to include this object in the dump */
BitField include;
/** Keep count for a final result */
int totalClasses;
/** Keep count for a final result */
int totalObjects;
/** Keep count for a final result */
int totalRoots;
/** Keep count for a final result */
int totalClassloaders;
/** Keep count for a final result */
long totalBytes;
/** keep track for totals */
SetInt classloaders = new SetInt();
/** Speed up first pass */
boolean skipData = false;
/**
* Stream which discards the output.
*/
static class NullStream extends OutputStream
{
@Override
public void write(int b) throws IOException
{
}
}
/**
* DataOutputStream which can have a long size.
*/
static class DataOutputStream3 implements DataOutput, Closeable
{
final DataOutputStream2 out;
protected long written = 0;
public DataOutputStream3(OutputStream out)
{
this.out = new DataOutputStream2(out);
}
public void write(int b) throws IOException
{
out.write(b);
written += 1;
}
public void write(byte[] b) throws IOException
{
out.write(b);
written += b.length;
}
public void write(byte[] b, int off, int len) throws IOException
{
out.write(b, off, len);
written += len;
}
public void writeBoolean(boolean v) throws IOException
{
out.writeBoolean(v);
written += 1;
}
public void writeByte(int v) throws IOException
{
out.writeByte(v);
written += 1;
}
public void writeShort(int v) throws IOException
{
out.writeShort(v);
written += 2;
}
public void writeChar(int v) throws IOException
{
out.writeChar(v);
written += 2;
}
public void writeInt(int v) throws IOException
{
out.writeInt(v);
written += 4;
}
public void writeLong(long v) throws IOException
{
out.writeLong(v);
written += 8;
}
public void writeFloat(float v) throws IOException
{
out.writeFloat(v);
written += 4;
}
public void writeDouble(double v) throws IOException
{
out.writeDouble(v);
written += 8;
}
public void writeBytes(String s) throws IOException
{
out.writeBytes(s);
written += s.length();
}
public void writeChars(String s) throws IOException
{
out.writeChars(s);
written += 2 * s.length();
}
public void writeUTF(String s) throws IOException
{
out.reset();
int m1 = out.size();
out.writeUTF(s);
int m2 = out.size();
written += m2 - m1;
}
public long size()
{
return written;
}
public void close() throws IOException
{
out.close();
}
}
/**
* DataOutputStream which can have bytes written reset
*/
static class DataOutputStream2 extends DataOutputStream {
public DataOutputStream2(OutputStream out)
{
super(out);
}
public void reset()
{
written = 0;
}
}
/** The size of the ID fields in the HPROF file */
int idsize = 8;
/** Progress monitor work per class for dumping objects */
private static final int WORK_OBJECT = 3;
/** Ready for new way of reading classes */
private final boolean NEWCLASSSIZE = HprofPreferences.useAdditionalClassReferences();
Remap remap;
public IResult execute(IProgressListener listener) throws Exception
{
int ct = snapshot.getSnapshotInfo().getNumberOfClasses();
/*
* Stages and work items per class
* load classes 1 11%
* prepare classes 1 22%
* dump classes 1 33%
* prepare objects 3 67%
* dump objects 3 100%
* Won't work so well for objects argument.
*/
int ct2 = initObjs();
if (ct2 <= 0)
ct2 = ct;
int totalWork = 3 * ct + 2 * WORK_OBJECT * ct2;
listener.beginTask(MessageUtil.format(Messages.ExportHprof_ExportTo, output.getName()), totalWork);
remap = new Remap(skipPattern, avoidPattern, redact == RedactType.NAMES, undo || mapFile == null);
remap.loadMapping(mapFile, undo);
long startTime;
OutputStream outstream = new BufferedOutputStream(new FileOutputStream(output), 1024 * 64);
if (compress)
{
if (chunked)
outstream = new ChunkedGZIPRandomAccessFile.ChunkedGZIPOutputStream(outstream);
else
outstream = new GZIPOutputStream(outstream);
// Speeds up compression
outstream = new BufferedOutputStream(outstream);
}
DataOutputStream3 os = new DataOutputStream3(outstream);
try
{
os.writeBytes(Version.JDK6.getLabel()+"\0"); //$NON-NLS-1$
idsize = snapshot.getSnapshotInfo().getIdentifierSize();
os.writeInt(idsize);
startTime = System.currentTimeMillis();
os.writeLong(startTime);
// os.writeByte(Constants.Record.HEAP_SUMMARY);
DataOutputStream3 os2 = new DataOutputStream3(new NullStream());
loadClasses(os, os2, startTime, listener);
// Keep track of new strings
int firstId = nextStringID;
long mark1 = os2.size();
listener.subTask(Messages.ExportHprof_PrepareClasses);
dumpClasses(os2, listener);
listener.subTask(Messages.ExportHprof_PrepareGCRoots);
gcRoots(os2);
dumpThreadRoots(os2);
long mark2 = os2.size();
long sizeseg1 = mark2 - mark1;
listener.subTask(Messages.ExportHprof_PrepareThreadStacks);
// Find all the strings
dumpThreadStacks(os2, startTime);
// Write out new Strings from the classes etc.
listener.subTask(Messages.ExportHprof_DumpStrings);
for (Map.Entry<String, Integer> e : stringToID.entrySet())
{
String ss = e.getKey();
int id = e.getValue();
if (id < firstId)
continue;
writeStringUTF(os, os2, startTime, ss, id);
}
listener.subTask(Messages.ExportHprof_DumpThreadStacks);
dumpThreadStacks(os, startTime);
int segnum = 1;
long seg1Start = os.size();
os.writeByte(Constants.Record.HEAP_DUMP_SEGMENT);
os.writeInt((int) (System.currentTimeMillis() - startTime));
os.writeInt((int)sizeseg1);
long markseg1a = os.size();
listener.subTask(MessageUtil.format(Messages.ExportHprof_DumpClasses, segnum));
dumpClasses(os, listener);
listener.subTask(MessageUtil.format(Messages.ExportHprof_DumpGCRoots, segnum));
gcRoots(os);
dumpThreadRoots(os);
long markseg1b = os.size();
long sizeseg1_a = markseg1b - markseg1a;
if (sizeseg1_a != sizeseg1)
{
listener.sendUserMessage(IProgressListener.Severity.WARNING,
MessageUtil.format(Messages.ExportHprof_SegmentSizeMismatch, segnum, sizeseg1, sizeseg1_a, Long.toHexString(seg1Start)), null);
}
/*
* Possibly multiple segments needed for objects
*/
int maxObjects = Integer.MAX_VALUE;
int st = 0;
do
{
++segnum;
// Segment length measurer
os2 = new DataOutputStream3(new NullStream());
// Object measurer
DataOutputStream3 os3 = new DataOutputStream3(new NullStream());
long m1 = os2.size();
listener.subTask(MessageUtil.format(Messages.ExportHprof_PrepareObjects, segnum));
boolean saveSkip = skipData;
skipData = true;
int end = dumpObjects(os2, os3, st, maxObjects, true, listener);
skipData = saveSkip;
long m2 = os2.size();
long s2 = m2 - m1;
os3.close();
long sizel = s2;
long segStart = os.size();
if (sizel > 0xffffffffL || sizel > segsize)
{
// Too big, but carry on
listener.sendUserMessage(IProgressListener.Severity.WARNING,
MessageUtil.format(Messages.ExportHprof_SegmentTooLong, segnum, Long.toHexString(segStart), sizel), null);
}
os.writeByte(Constants.Record.HEAP_DUMP_SEGMENT);
os.writeInt((int) (System.currentTimeMillis() - startTime));
os.writeInt((int)sizel);
long checkmark1 = os.size();
listener.subTask(MessageUtil.format(Messages.ExportHprof_DumpObjects, segnum));
st = dumpObjects(os, os2, st, end, false, listener);
long checkmark2 = os.size();
long size2 = checkmark2 - checkmark1;
if (size2 != sizel)
{
listener.sendUserMessage(IProgressListener.Severity.WARNING,
MessageUtil.format(Messages.ExportHprof_SegmentSizeMismatch, segnum, sizel, size2, Long.toHexString(segStart)), null);
}
} while (st > 0 && st < maxObjects);
os.writeByte(Constants.Record.HEAP_DUMP_END);
os.writeInt((int) (System.currentTimeMillis() - startTime));
os.writeInt(0);
os2.close();
}
finally
{
os.close();
}
String comments = MessageUtil.format(Messages.ExportHprof_RemapProperties, output.getName(), new File(snapshot.getSnapshotInfo().getPath()).getName());
remap.saveMapping(mapFile, undo, comments);
listener.done();
/*
* Report the result as a heap dump overview.
* Handle integer overflow as we count everything twice, once for sizing, once for output.
*/
int nclasses = totalClasses >>> 1;
int nobjects = totalObjects >>> 1;
int nroots = totalRoots >>> 1;
int nclassloaders = totalClassloaders >>> 1;
long nused = totalBytes >>> 1;
SnapshotQuery sq = SnapshotQuery.lookup("heap_dump_overview", snapshot); //$NON-NLS-1$
String name = output.getName();
int dot = name.lastIndexOf('.');
if (dot >= 0)
{
name = name.substring(0, dot);
}
String prefix = (new File(output.getParentFile(), name)).getPath();
SnapshotInfo si = new SnapshotInfo(output.getAbsolutePath(), prefix, null, idsize, new Date(startTime), nobjects, nroots, nclasses, nclassloaders, nused);
String format = (new HprofContentDescriber()).getSupportedOptions()[0].getLocalName();
si.setProperty("$heapFormat", format); //$NON-NLS-1$
if (Boolean.TRUE.equals(snapshot.getSnapshotInfo().getProperty("$useCompressedOops"))) //$NON-NLS-1$
{
si.setProperty("$useCompressedOops", true); //$NON-NLS-1$
}
sq.setArgument("info", si); //$NON-NLS-1$
IResult ret = sq.execute(new SilentProgressListener(listener));
return ret;
}
/**
* Include an object in the output dump?
* @param obj
* @return
*/
boolean includeObject(int obj)
{
return include == null || include.get(obj);
}
/**
* Set up the tests for whether to include objects.
*/
int initObjs()
{
int n = 0;
if (objects != null)
{
include = new BitField(snapshot.getSnapshotInfo().getNumberOfObjects());
for (int ia[] : objects)
{
++n;
for (int i : ia)
{
include.set(i);
}
}
}
return n;
}
/**
* Generate a dummy stack trace for when objects/classes
* etc. were allocated. Needed for jhat.
*/
private int dummyStackTrace(DataOutput os, int dummyThread, long startTime) throws IOException
{
os.writeByte(Constants.Record.STACK_TRACE);
os.writeInt((int) (System.currentTimeMillis() - startTime));
os.writeInt(3 * 4);
os.writeInt(UNKNOWN_STACK_TRACE_SERIAL);
os.writeInt(dummyThread);
os.writeInt(0); // No frames
return UNKNOWN_STACK_TRACE_SERIAL;
}
/**
* Dump the GC roots
*
* @param os
* @throws SnapshotException
* @throws IOException
*/
private void gcRoots(DataOutput os) throws SnapshotException, IOException
{
int nextThreadSerial = 1;
++nextThreadSerial;
for (int i : snapshot.getGCRoots())
{
int roots = 0;
if (!includeObject(i))
continue;
GCRootInfo gi[] = snapshot.getGCRootInfo(i);
for (GCRootInfo gri : gi)
{
int tp;
long contextAddr;
switch (gri.getType())
{
case Type.BUSY_MONITOR:
tp = Constants.DumpSegment.ROOT_MONITOR_USED;
os.writeByte(tp);
writeID(os, gri.getObjectAddress());
++roots;
break;
case Type.THREAD_OBJ:
tp = Constants.DumpSegment.ROOT_THREAD_OBJECT;
os.writeByte(tp);
writeID(os, gri.getObjectAddress());
os.writeInt(nextThreadSerial);
threadToSerial.put(gri.getObjectId(), nextThreadSerial);
// System.out.println("Thread "+gri.getObjectId()+"
// "+nextThreadSerial);
++nextThreadSerial;
Integer stackserial = threadToStack.get(gri.getObjectId());
if (stackserial == null)
stackserial = UNKNOWN_STACK_TRACE_SERIAL;
os.writeInt(stackserial); // Stack trace
++roots;
break;
case Type.JAVA_LOCAL:
contextAddr = gri.getContextAddress();
if (contextAddr == 0)
{
tp = Constants.DumpSegment.ROOT_JAVA_FRAME;
os.writeByte(tp);
writeID(os, gri.getObjectAddress());
os.writeInt(0); // thread serial
os.writeInt(UNKNOWN_STACK_FRAME_SERIAL); // stack frame number
++roots;
}
break;
case Type.NATIVE_LOCAL:
case Type.NATIVE_STATIC:
case Type.NATIVE_STACK:
contextAddr = gri.getContextAddress();
// Currently DTFJ parser generates some roots with context address == object address
// when no context address
if (contextAddr == 0 || contextAddr == gri.getObjectAddress())
{
tp = Constants.DumpSegment.ROOT_JNI_GLOBAL;
os.writeByte(tp);
writeID(os, gri.getObjectAddress());
writeID(os, 0); // JNI global ref ID
++roots;
}
break;
case Type.SYSTEM_CLASS:
tp = Constants.DumpSegment.ROOT_STICKY_CLASS;
os.writeByte(tp);
writeID(os, gri.getObjectAddress());
++roots;
break;
case Type.THREAD_BLOCK:
contextAddr = gri.getContextAddress();
if (contextAddr == 0)
{
tp = Constants.DumpSegment.ROOT_THREAD_BLOCK;
os.writeByte(tp);
writeID(os, gri.getObjectAddress());
os.writeInt(0); // thread serial
++roots;
}
break;
case Type.UNREACHABLE:
case Type.FINALIZABLE:
case Type.UNKNOWN:
default:
tp = Constants.DumpSegment.ROOT_UNKNOWN;
os.writeByte(tp);
writeID(os, gri.getObjectAddress());
++roots;
break;
}
}
if (roots > 0)
{
++totalRoots;
}
}
}
/**
* Class to hold results of parsing stack frames.
*/
static class Frame
{
String clazz;
String method;
String signature;
String sourceFile;
int lineNumber;
public Frame(String clazz, String method, String signature, String sourceFile, int lineNumber)
{
this.clazz = clazz;
this.method = method;
this.signature = signature;
this.sourceFile = sourceFile;
this.lineNumber = lineNumber;
}
/**
* Parse lines such as:
* at org.eclipse.core.internal.jobs.Worker.run()V (Worker.java:55)
* at org.eclipse.swt.widgets.Display.sleep()Z (Display.java:4534)
* at org.eclipse.ui.internal.Workbench.lambda$3(Lorg/eclipse/swt/widgets/Display;Lorg/eclipse/ui/application/WorkbenchAdvisor;[I)V (Workbench.java:683) at
* at org.eclipse.swt.internal.win32.OS.WaitMessage()Z (Native Method)
* at org.eclipse.swt.internal.win32.OS.WaitMessage()Z (Compiled Code)
* at org.eclipse.swt.internal.win32.OS.WaitMessage()Z (Unknown source)
* at org.eclipse.swt.widgets.Display.sleep()Z (Display.java:4534(Compiled Code))
* at java.io.FileInputStream.readBytes([BII)I (Native Method)
* at java.io.FileInputStream.read([BII)I (FileInputStream.java:256)
* at java.io.BufferedInputStream.fill()V (BufferedInputStream.java:246)
* at java.io.BufferedInputStream.read()I (BufferedInputStream.java:265)
* at java.io.BufferedInputStream.read()I (BufferedInputStream.java:265(Compiled Code))
* at
* The last sometimes appears from DTFJ dumps in error.
*
* @param frame
* @return a new Frame object holding the parsed components
*/
public static Frame parse(String frame)
{
String parts[] = frame.split("\\s+", 3); //$NON-NLS-1$
String mn = parts.length >= 2 ? parts[1] : ""; //$NON-NLS-1$
String source = parts.length >= 3 ? parts[2] : ""; //$NON-NLS-1$
int b = mn.indexOf('(');
String method;
String classname;
String sig;
if (b < 0)
{
b = mn.length();
}
int c = mn.lastIndexOf('.', b);
if (c >= 0)
{
classname = mn.substring(0, c);
}
else
{
classname = ""; //$NON-NLS-1$
}
method = mn.substring(c + 1, b);
sig = mn.substring(b);
if (source.startsWith("(")) //$NON-NLS-1$
source = source.substring(1);
if (source.endsWith(")")) //$NON-NLS-1$
source = source.substring(0, source.length() - 1);
int cl = source.indexOf(':');
String sourcefile;
int linenum = 0;
if (cl >= 0)
{
sourcefile = source.substring(0, cl);
int cn1 = cl + 1;
while (cn1 < source.length() && source.charAt(cn1) >= '0' && source.charAt(cn1) <= '9')
{
++cn1;
}
if (cn1 > cl + 1)
{
linenum = Integer.parseInt(source.substring(cl + 1, cn1));
}
}
else
{
int br = source.indexOf('(');
if (br >= 0)
sourcefile = source.substring(0, br);
else
sourcefile = ""; //$NON-NLS-1$
if (source.contains("Compiled Code")) //$NON-NLS-1$
{
linenum = -2;
}
else if (source.contains("Native Method")) //$NON-NLS-1$
{
linenum = -3;
}
else
{
linenum = -1;
}
}
return new Frame(classname, method, sig, sourcefile, linenum);
}
}
/**
* Dump the thread stacks
* @param os the main output stream
* @param startTime
* @throws SnapshotException
* @throws IOException
*/
private void dumpThreadStacks(DataOutput os, long startTime)
throws SnapshotException, IOException
{
dummyStackTrace(os, UNKNOWN_STACK_TRACE_SERIAL, 1);
long nextFrameid = 1;
int serialid = UNKNOWN_STACK_TRACE_SERIAL + 1;
// Find the threads
for (int i : snapshot.getGCRoots())
{
if (!includeObject(i))
continue;
for (GCRootInfo gr : snapshot.getGCRootInfo(i))
{
if (gr.getType() == GCRootInfo.Type.THREAD_OBJ)
{
IThreadStack its = snapshot.getThreadStack(i);
if (its == null)
continue;
// Find the stack frames
ArrayLong frameIds = new ArrayLong();
IObject thread = snapshot.getObject(i);
int frameNumber = 0;
for (IStackFrame isf : its.getStackFrames())
{
long frameid = 0;
for (NamedReference ref : thread.getOutboundReferences())
{
if (ref instanceof ThreadToLocalReference)
{
ThreadToLocalReference tlr = (ThreadToLocalReference)ref;
for (GCRootInfo rootInfo : tlr.getGcRootInfo())
{
if (rootInfo.getType() == GCRootInfo.Type.JAVA_STACK_FRAME)
{
if (Integer.valueOf(frameNumber).equals(tlr.getObject().resolveValue("frameNumber")))
{
frameid = tlr.getObjectAddress();
break;
}
}
}
}
}
if (frameid == 0)
{
frameid = nextFrameid++;
}
String frametext = isf.getText();
Frame f = Frame.parse(frametext);
String classname = f.clazz;
String method = f.method;
String sig = f.signature;
String sourcefile = f.sourceFile;
method = remap.renameMethodName(classname, method, false);
sig = remap.renameSignature(sig);
sourcefile = remap.renameFileName(classname, sourcefile);
int linenum = f.lineNumber;
Collection<IClass> cls = snapshot.getClassesByName(classname, false);
int clsid;
if (cls == null || cls.isEmpty())
{
clsid = 0;
}
else
{
IClass cls1 = cls.iterator().next();
clsid = cls1.getObjectId();
}
os.writeByte(Constants.Record.STACK_FRAME);
os.writeInt((int) (System.currentTimeMillis() - startTime));
os.writeInt(4 * idsize + 2 * 4);
writeID(os, frameid);
writeString(os, method);
writeString(os, sig);
writeString(os, sourcefile);
os.writeInt(clsid);
os.writeInt(linenum);
frameIds.add(frameid);
++frameNumber;
}
os.writeByte(Constants.Record.STACK_TRACE);
os.writeInt((int) (System.currentTimeMillis() - startTime));
os.writeInt(3 * 4 + frameIds.size() * idsize);
os.writeInt(serialid);
Integer prev = threadToStack.put(i, serialid);
//if (prev != null && prev != serialid)
// throw new IllegalStateException("thread " + i + "0x" + Long.toHexString(gr.getObjectAddress()) + " " + serialid + " != " + prev); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
++serialid;
os.writeInt(threadToSerial.get(i));
os.writeInt(frameIds.size());
for (long j : frameIds.toArray())
{
writeID(os, j);
}
}
}
}
}
/**
* Write out the body of a load class definition.
* @param os
* @param startTime
* @param cls
* @throws IOException
*/
private void loadClassBody(DataOutput os, long startTime, IClass cls) throws IOException
{
os.writeInt(cls.getObjectId()); // Class serial id
writeID(os, cls.getObjectAddress());
os.writeInt(UNKNOWN_STACK_TRACE_SERIAL); // stack trace serial number
String classname = cls.getName();
classname = remap.renameClassName(classname);
writeString(os, classname);
}
/**
* Write out the whole load class, including the header and size
* @param os
* @param os2 Uses to measure the size of the body
* @param startTime
* @param cls
* @throws IOException
*/
private void loadClass(DataOutput os, DataOutputStream3 os2, long startTime, IClass cls) throws IOException
{
int str = nextStringID;
long mark = os2.size();
loadClassBody(os2, startTime, cls);
long end = os2.size();
if (nextStringID != str)
{
String classname = cls.getName();
classname = remap.renameClassName(classname);
writeStringUTF(os, os2, startTime, classname, str);
}
loadClass(os, cls, startTime, (int) (end - mark));
}
/**
* Generate load class definitions for all the classes.
* @param os
* @param os2
* @param startTime
* @param listener
* @throws IOException
* @throws SnapshotException
*/
private void loadClasses(DataOutput os, DataOutputStream3 os2, long startTime, IProgressListener listener)
throws IOException, SnapshotException
{
for (IClass cls : snapshot.getClasses())
{
if (includeObject(cls.getObjectId()))
{
loadClass(os, os2, startTime, cls);
}
listener.worked(1);
if (listener.isCanceled())
throw new OperationCanceledException();
}
return;
}
/**
* Write out a single string, as UTF-8.
* @param os
* @param os2
* @param startTime
* @param ss
* @param id
* @throws IOException
*/
private void writeStringUTF(DataOutput os, DataOutputStream3 os2, long startTime, String ss, int id)
throws IOException
{
os.writeByte(Constants.Record.STRING_IN_UTF8);
os.writeInt((int) (System.currentTimeMillis() - startTime));
long mark = os2.size();
writeID(os2, id);
byte utf[] = ss.getBytes(UTF8);
os2.write(utf);
long reclen = os2.size() - mark;
os.writeInt((int)reclen);
writeID(os, id);
os.write(utf);
}
/**