-
Notifications
You must be signed in to change notification settings - Fork 3
/
HprofRandomAccessParser.java
649 lines (607 loc) · 23.7 KB
/
HprofRandomAccessParser.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
/*******************************************************************************
* Copyright (c) 2008, 2023 SAP AG, Netflix, 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
* Netflix (Jason Koch) - refactors for increased performance and concurrency
* IBM Corporation (Andrew Johnson) - compressed dumps
*******************************************************************************/
package org.eclipse.mat.hprof;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.mat.SnapshotException;
import org.eclipse.mat.hprof.AbstractParser.Constants.Record;
import org.eclipse.mat.hprof.describer.Version;
import org.eclipse.mat.hprof.ui.HprofPreferences;
import org.eclipse.mat.parser.index.IIndexReader.IOne2LongIndex;
import org.eclipse.mat.parser.io.BufferedRandomAccessInputStream;
import org.eclipse.mat.parser.model.AbstractObjectImpl;
import org.eclipse.mat.parser.model.ClassImpl;
import org.eclipse.mat.parser.model.ClassLoaderImpl;
import org.eclipse.mat.parser.model.InstanceImpl;
import org.eclipse.mat.parser.model.ObjectArrayImpl;
import org.eclipse.mat.parser.model.PrimitiveArrayImpl;
import org.eclipse.mat.snapshot.ISnapshot;
import org.eclipse.mat.snapshot.model.Field;
import org.eclipse.mat.snapshot.model.FieldDescriptor;
import org.eclipse.mat.snapshot.model.IArray;
import org.eclipse.mat.snapshot.model.IClass;
import org.eclipse.mat.snapshot.model.IObject;
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.ObjectReference;
import org.eclipse.mat.util.MessageUtil;
public class HprofRandomAccessParser extends AbstractParser
{
public static final int LAZY_LOADING_LIMIT = 256;
private final IPositionInputStream in;
public HprofRandomAccessParser(File file, String prefix, Version version, int identifierSize, long len,
HprofPreferences.HprofStrictness strictnessPreference) throws IOException
{
super(strictnessPreference);
RandomAccessFile raf = new RandomAccessFile(file, "r"); //$NON-NLS-1$
boolean gzip = CompressedRandomAccessFile.isGZIP(raf);
if (gzip)
{
ChunkedGZIPRandomAccessFile cgraf = ChunkedGZIPRandomAccessFile.get(raf, file, prefix);
raf.close();
if (cgraf != null)
{
raf = cgraf;
}
else
{
long requested = len / 10;
long maxFree = CompressedRandomAccessFile.checkMemSpace(requested);
// If we are very memory constrained use a file cache
if (requested > maxFree && FileCacheCompressedRandomAccessFile.isDiskSpace(file, len))
raf = new FileCacheCompressedRandomAccessFile(file);
else
raf = new CompressedRandomAccessFile(file, true, len);
}
}
this.in = new DefaultPositionInputStream(new BufferedRandomAccessInputStream(raf, 512));
this.version = version;
this.idSize = identifierSize;
}
public synchronized void close() throws IOException
{
in.close();
}
public synchronized IObject read(int objectId, long position, ISnapshot dump, IOne2LongIndex o2hprof) throws IOException, SnapshotException
{
in.seek(position);
int segmentType = in.readUnsignedByte();
if (objectId == -1)
{
segmentType = skipRecords(segmentType);
}
switch (segmentType)
{
case Constants.Record.STACK_FRAME:
return readStackFrame(objectId, dump);
case Constants.DumpSegment.INSTANCE_DUMP:
return readInstanceDump(objectId, dump);
case Constants.DumpSegment.OBJECT_ARRAY_DUMP:
return readObjectArrayDump(objectId, dump);
case Constants.DumpSegment.PRIMITIVE_ARRAY_DUMP:
return readPrimitiveArrayDump(objectId, dump);
default:
throw new IOException(MessageUtil.format(Messages.HprofRandomAccessParser_Error_IllegalDumpSegment,
segmentType, Long.toHexString(position)));
}
}
private IObject readStackFrame(int objectId, ISnapshot dump) throws SnapshotException, IOException
{
in.readUnsignedInt(); // time
in.readUnsignedInt(); // length
long frameId = in.readID(idSize);
in.readID(idSize); // methodName
in.readID(idSize); // methodSig
in.readID(idSize); // srcFile
in.readUnsignedInt(); // classSerNum
int lineNr = in.readInt(); // can be negative
IClass classImpl = dump.getClassOf(objectId);
List<Field>fields = new ArrayList<Field>();
Field f = new Field(LINE_NUMBER, IObject.Type.INT, lineNr);
fields.add(f);
int compLevel = lineNr == -2 ? 1 : 0;
f = new Field(COMPILATION_LEVEL, IObject.Type.INT, compLevel);
fields.add(f);
boolean nativ = lineNr == -3;
f = new Field(NATIVE, IObject.Type.BOOLEAN, nativ);
fields.add(f);
f = new Field(LOCATION_ADDRESS, IObject.Type.LONG, (long)frameId);
fields.add(f);
// Identify more stack frame information from the .threads index
int thrds[] = dump.getInboundRefererIds(objectId);
l: for (int thrd : thrds)
{
IThreadStack stack = dump.getThreadStack(thrd);
if (stack != null)
{
for (int fm = 0; fm < stack.getStackFrames().length; ++fm)
{
IStackFrame frm = stack.getStackFrames()[fm];
for (int oo : frm.getLocalObjectsIds())
{
if (oo == objectId)
{
f = new Field(FRAME_NUMBER, IObject.Type.INT, fm);
fields.add(f);
f = new Field(STACK_DEPTH, IObject.Type.INT, stack.getStackFrames().length - fm);
fields.add(f);
for (FieldDescriptor fd : classImpl.getFieldDescriptors())
{
if (fd.getName().equals(METHOD_NAME))
{
String stkLine = frm.getText().replaceFirst("\\s*at\\s+([^ ]+).*", "$1"); //$NON-NLS-1$ //$NON-NLS-2$
f = new Field(METHOD_NAME, IObject.Type.OBJECT, stkLine);
fields.add(f);
}
else if (fd.getName().equals(FILE_NAME))
{
String stkLine = frm.getText().replaceFirst("\\s*at\\s+[^ ]+\\s+\\(([^:()]+).*", "$1"); //$NON-NLS-1$ //$NON-NLS-2$
f = new Field(FILE_NAME, IObject.Type.OBJECT, stkLine);
fields.add(f);
}
}
break l;
}
}
}
}
}
long objectAddress = dump.mapIdToAddress(objectId);
return new InstanceImpl(objectId, objectAddress, (ClassImpl)classImpl, fields);
}
public List<IClass> resolveClassHierarchy(ISnapshot snapshot, IClass clazz) throws SnapshotException
{
List<IClass> answer = new ArrayList<IClass>();
answer.add(clazz);
while (clazz.hasSuperClass())
{
clazz = (IClass) snapshot.getObject(clazz.getSuperClassId());
if (clazz == null)
return null;
answer.add(clazz);
}
return answer;
}
/**
* A reference to an object via its address
* which can handle the address not being in the index.
*/
static class ObjectAddressReference extends ObjectReference
{
private static final long serialVersionUID = 1L;
transient IOne2LongIndex o2hprof;
transient ISnapshot snapshot;
transient HprofRandomAccessParser parser;
/**
* Construct an {@link ObjectAddressReference} which can be used to retrieve an
* object by address even if it has not been indexed.
* Used as a proxy by {@link ObjectReference} which can change the {@link ObjectReference#address}
* private field.
* @param snapshot the snapshot
* @param parser the HPROF parser used to build the IObject if required
* @param o2hprof the index from object ID to HPROF file position
* @param address the address of the object
*/
public ObjectAddressReference(ISnapshot snapshot, HprofRandomAccessParser parser, IOne2LongIndex o2hprof, long address)
{
super(snapshot, address);
this.snapshot = snapshot;
this.o2hprof = o2hprof;
this.parser = parser;
}
@Override
public int getObjectId() throws SnapshotException
{
try
{
int id = super.getObjectId();
return id;
}
catch (SnapshotException e)
{
return -1;
}
}
/**
* Actually construct an IObject.
* First try constructing by object ID.
* If that fails then construct by address.
* Find the indexed objects before and after this.
* Parse the HPROF file between these two points looking for an
* object of the correct address.
*/
@Override
public IObject getObject() throws SnapshotException
{
SnapshotException e1 = null;
try
{
int id = super.getObjectId();
if (id >= 0)
{
IObject o = super.getObject();
return o;
}
}
catch (SnapshotException e)
{
e1 = e;
}
// Find the object IDs before and after this object
int low = 0;
int high = o2hprof.size() - 1;
for (;low + 1 < high;)
{
int mid = (low + high) >>> 1;
long midAddr = snapshot.mapIdToAddress(mid);
if (getObjectAddress() < midAddr)
{
high = mid;
}
else if (getObjectAddress() > midAddr)
{
low = mid;
}
else
{
low = mid;
high = mid;
}
}
// Some objects don't have a position (classes?), so find valid file positions
long pos = 0;
while ((pos = o2hprof.get(low)) == 0 && low > 0)
--low;
if (pos == 0)
{
// There might be discarded objects before the first
Long lpos = (Long)snapshot.getSnapshotInfo().getProperty(HprofHeapObjectReader.HPROF_HEAP_START);
if (lpos != null)
pos = lpos;
else while ((pos = o2hprof.get(low)) == 0 && low < o2hprof.size() - 1)
++low;
}
long posHigh = pos;
while (high >= 0 && (posHigh = o2hprof.get(high)) == 0 && high < o2hprof.size() - 1)
++high;
if (posHigh == 0)
{
// There might be discarded objects after the last
Long olen = (Long)snapshot.getSnapshotInfo().getProperty(HprofHeapObjectReader.HPROF_LENGTH_PROPERTY);
posHigh = (olen != null) ? olen : Long.MAX_VALUE;
}
// Reparse the HPROF file looking for an object of the right address
try
{
do
{
IObject o;
synchronized (parser)
{
// Need final position without interference
o = parser.read(-1, pos, snapshot, o2hprof);
pos = parser.in.position();
}
if (o.getObjectAddress() == getObjectAddress())
{
// Class was discarded from the snapshot
if (o.getClazz() == null)
throw new IOException();
((AbstractObjectImpl)o).setSnapshot(snapshot);
return o;
}
// Gone past the object address we want
if (o.getObjectAddress() > getObjectAddress())
break;
}
while (pos < posHigh);
}
catch (IOException e2)
{
if (e2 instanceof EOFException)
throw e1;
throw new SnapshotException(e2);
}
// Not found, so throw the original exception
throw e1;
}
}
private IObject readInstanceDump(int objectId, ISnapshot dump) throws IOException, SnapshotException
{
long address = in.readID(idSize);
IClass oclazz;
if (objectId >= 0)
{
// Skip serial number, class ID, length
if (checkSkipBytes(8 + idSize) != 8 + idSize)
throw new IOException();
oclazz = dump.getClassOf(objectId);
}
else
{
// skip serial number
if (checkSkipBytes(4) != 4)
throw new IOException();
// class ID
long classAddr = in.readID(idSize);
// length
long len = in.readUnsignedInt();
try
{
int classID = dump.mapAddressToId(classAddr);
IObject io = dump.getObject(classID);
if (io instanceof IClass)
oclazz = (IClass)io;
else
throw new IOException();
}
catch (SnapshotException e)
{
// move to end of object
if (checkSkipBytes(len) != len)
throw new IOException();
// Invalid object, but might be good enough for skipping over
return new InstanceImpl(objectId, address, null, null);
}
}
// check if we need to defer reading the class
List<IClass> hierarchy = resolveClassHierarchy(dump, oclazz);
if (hierarchy == null)
{
throw new IOException(Messages.HprofRandomAccessParser_Error_DumpIncomplete);
}
else
{
List<Field> instanceFields = new ArrayList<Field>();
for (IClass clazz : hierarchy)
{
List<FieldDescriptor> fields = clazz.getFieldDescriptors();
for (int ii = 0; ii < fields.size(); ii++)
{
FieldDescriptor field = fields.get(ii);
int type = field.getType();
Object value = readValue(in, dump, type);
instanceFields.add(new Field(field.getName(), field.getType(), value));
}
}
ClassImpl classImpl = (ClassImpl) hierarchy.get(0);
if (dump.isClassLoader(objectId))
return new ClassLoaderImpl(objectId, address, classImpl, instanceFields);
else
return new InstanceImpl(objectId, address, classImpl, instanceFields);
}
}
private IArray readObjectArrayDump(int objectId, ISnapshot dump) throws IOException, SnapshotException
{
long id = in.readID(idSize);
checkSkipBytes(4);
int size = in.readInt();
long len = (long)size * idSize;
long arrayClassObjectID = in.readID(idSize);
int typeId;
if (objectId == -1)
{
try
{
typeId = dump.mapAddressToId(arrayClassObjectID);
}
catch (SnapshotException e)
{
ObjectArrayImpl array = new ObjectArrayImpl(objectId, id, null, size);
// Move to end of object
if (checkSkipBytes(len) != len)
throw new IOException();
return array;
}
}
else
{
typeId = dump.mapAddressToId(arrayClassObjectID);
}
IClass arrayType = (IClass) dump.getObject(typeId);
if (arrayType == null)
throw new RuntimeException(Messages.HprofRandomAccessParser_Error_MissingFakeClass);
Object content = null;
if (len < LAZY_LOADING_LIMIT)
{
long[] data = new long[size];
for (int ii = 0; ii < data.length; ii++)
data[ii] = in.readID(idSize);
content = data;
}
else
{
content = new ArrayDescription.Offline(false, in.position(), 0, size);
if (objectId == -1)
{
// Move to end of object
if (checkSkipBytes(len) != len)
throw new IOException();
}
}
ObjectArrayImpl array = new ObjectArrayImpl(objectId, id, (ClassImpl) arrayType, size);
array.setInfo(content);
return array;
}
private IArray readPrimitiveArrayDump(int objectId, ISnapshot dump) throws IOException, SnapshotException
{
long id = in.readID(idSize);
checkSkipBytes(4);
int arraySize = in.readInt();
long elementType = in.readByte();
if ((elementType < IPrimitiveArray.Type.BOOLEAN) || (elementType > IPrimitiveArray.Type.LONG))
throw new IOException(Messages.Pass1Parser_Error_IllegalType);
int elementSize = IPrimitiveArray.ELEMENT_SIZE[(int) elementType];
long len = elementSize * (long)arraySize;
Object content = null;
if (len < LAZY_LOADING_LIMIT)
{
byte[] data = new byte[(int)len];
in.readFully(data);
content = elementType == IObject.Type.BYTE ? data : new ArrayDescription.Raw(data);
}
else
{
content = new ArrayDescription.Offline(true, in.position(), elementSize, arraySize);
if (objectId == -1)
{
// Move to end of object
if (checkSkipBytes(len) != len)
throw new IOException();
}
}
// lookup class by name
IClass clazz = null;
String name = IPrimitiveArray.TYPE[(int) elementType];
Collection<IClass> classes = dump.getClassesByName(name, false);
if (classes == null || classes.isEmpty())
{
if (objectId == -1)
{
// Return a dummy array which can be ignored
PrimitiveArrayImpl array = new PrimitiveArrayImpl(objectId, id, (ClassImpl) clazz, arraySize, (int) elementType);
return array;
}
throw new IOException(MessageUtil.format(Messages.HprofRandomAccessParser_Error_MissingClass, name));
}
else if (classes.size() > 1)
throw new IOException(MessageUtil.format(Messages.HprofRandomAccessParser_Error_DuplicateClass, name));
else
clazz = classes.iterator().next();
PrimitiveArrayImpl array = new PrimitiveArrayImpl(objectId, id, (ClassImpl) clazz, arraySize, (int) elementType);
array.setInfo(content);
return array;
}
public synchronized long[] readObjectArray(ArrayDescription.Offline descriptor, int offset, int length)
throws IOException
{
int elementSize = this.idSize;
in.seek(descriptor.getPosition() + ((long)offset * elementSize));
long[] data = new long[length];
for (int ii = 0; ii < data.length; ii++)
data[ii] = in.readID(idSize);
return data;
}
public synchronized byte[] readPrimitiveArray(ArrayDescription.Offline descriptor, int offset, int length)
throws IOException
{
int elementSize = descriptor.getElementSize();
in.seek(descriptor.getPosition() + ((long)offset * elementSize));
byte[] data = new byte[length * elementSize];
in.readFully(data);
return data;
}
private int skipRecords(int segmentType) throws IOException
{
boolean again = true;
do
{
int skip = -1;
switch (segmentType)
{
case Record.HEAP_DUMP_SEGMENT:
skip = 8;
break;
case Constants.DumpSegment.ROOT_UNKNOWN:
case Constants.DumpSegment.ROOT_STICKY_CLASS:
case Constants.DumpSegment.ROOT_MONITOR_USED:
skip = idSize;
break;
case Constants.DumpSegment.ROOT_JNI_GLOBAL:
skip = idSize * 2;
break;
case Constants.DumpSegment.ROOT_JNI_LOCAL:
case Constants.DumpSegment.ROOT_JAVA_FRAME:
case Constants.DumpSegment.ROOT_THREAD_OBJECT:
skip = idSize + 8;
break;
case Constants.DumpSegment.ROOT_NATIVE_STACK:
case Constants.DumpSegment.ROOT_THREAD_BLOCK:
skip = idSize + 4;
break;
case Constants.DumpSegment.CLASS_DUMP:
skipClassDump();
// Already skipped enough, so just reread
skip = 0;
break;
default:
again = false;
break;
}
if (skip >= 0)
{
// Skip over new segment header etc.
checkSkipBytes(skip);
segmentType = in.readUnsignedByte();
}
}
while (again);
return segmentType;
}
private void skipClassDump() throws IOException
{
checkSkipBytes(7 * idSize + 8);
int constantPoolSize = in.readUnsignedShort();
for (int ii = 0; ii < constantPoolSize; ii++)
{
checkSkipBytes(2);
skipValue(in);
}
int numStaticFields = in.readUnsignedShort();
for (int i = 0; i < numStaticFields; i++)
{
checkSkipBytes(idSize);
skipValue(in);
}
int numInstanceFields = in.readUnsignedShort();
checkSkipBytes((idSize + 1) * numInstanceFields);
}
private int checkSkipBytes(int skip) throws IOException
{
int left = skip;
while (left > 0)
{
int skipped = in.skipBytes(left);
if (skipped == 0)
{
in.readByte();
skipped = 1;
}
left -= skipped;
}
return skip - left;
}
private long checkSkipBytes(long skip) throws IOException
{
long left = skip;
while (left > 0)
{
int skipped = in.skipBytes(Math.min(left, Integer.MAX_VALUE));
if (skipped == 0)
{
in.readByte();
skipped = 1;
}
left -= skipped;
}
return skip - left;
}
}