-
Notifications
You must be signed in to change notification settings - Fork 3
/
FindLeaksQuery.java
669 lines (562 loc) · 25 KB
/
FindLeaksQuery.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
/*******************************************************************************
* Copyright (c) 2008, 2023 SAP AG and 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:
* SAP AG - initial API and implementation
* Andrew Johnson (IBM Corporation)- for comparisons
*******************************************************************************/
package org.eclipse.mat.inspections;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.eclipse.core.runtime.Status;
import org.eclipse.mat.SnapshotException;
import org.eclipse.mat.collect.ArrayInt;
import org.eclipse.mat.collect.ArrayIntBig;
import org.eclipse.mat.collect.BitField;
import org.eclipse.mat.internal.MATPlugin;
import org.eclipse.mat.internal.Messages;
import org.eclipse.mat.internal.snapshot.inspections.Path2GCRootsQuery;
import org.eclipse.mat.query.Bytes;
import org.eclipse.mat.query.Column;
import org.eclipse.mat.query.ContextProvider;
import org.eclipse.mat.query.IContextObject;
import org.eclipse.mat.query.IContextObjectSet;
import org.eclipse.mat.query.IQuery;
import org.eclipse.mat.query.IResult;
import org.eclipse.mat.query.IResultTable;
import org.eclipse.mat.query.ResultMetaData;
import org.eclipse.mat.query.annotations.Argument;
import org.eclipse.mat.query.annotations.Category;
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.ClassHistogramRecord;
import org.eclipse.mat.snapshot.ClassLoaderHistogramRecord;
import org.eclipse.mat.snapshot.Histogram;
import org.eclipse.mat.snapshot.IMultiplePathsFromGCRootsComputer;
import org.eclipse.mat.snapshot.ISnapshot;
import org.eclipse.mat.snapshot.MultiplePathsFromGCRootsRecord;
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.util.IProgressListener;
import org.eclipse.mat.util.MessageUtil;
import com.ibm.icu.text.NumberFormat;
@CommandName("find_leaks")
@Category(Category.HIDDEN)
@Icon("/META-INF/icons/leak.gif")
@HelpUrl("/org.eclipse.mat.ui.help/tasks/runningleaksuspectsreport.html")
public class FindLeaksQuery implements IQuery
{
// ///////////////////////////////////////////
//
// static fields
//
// ///////////////////////////////////////////
private final static int MAX_DEPTH = 1000;
// ////////////////////////////////////////////
//
// Command parameters
//
// ////////////////////////////////////////////
@Argument
public ISnapshot snapshot;
@Argument(isMandatory = false)
public int threshold_percent = 20;
@Argument(isMandatory = false)
public int max_paths = 10000;
// @Argument(isMandatory = false, flag = "big_drop_ratio")
public double big_drop_ratio = 0.7;
public double group_suspects_accumulation_ratio = 0.8;
public List<String> excludes = Arrays.asList( //
new String[] { "java.lang.ref.Reference:referent", "java.lang.ref.Finalizer:unfinalized", "java.lang.Runtime:" + "<" + GCRootInfo.getTypeAsString(GCRootInfo.Type.UNFINALIZED) + ">" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
public IResult execute(IProgressListener listener) throws Exception
{
long totalHeap;
int[] topDominators;
totalHeap = snapshot.getSnapshotInfo().getUsedHeapSize();
topDominators = snapshot.getImmediateDominatedIds(-1);
long threshold = threshold_percent * totalHeap / 100;
/*
* find suspect single objects
*/
listener.subTask(Messages.FindLeaksQuery_SearchingSingleObjects);
ArrayInt suspiciousObjects = new ArrayInt();
Set<String> suspectNames = new HashSet<String>();
int i = 0;
while (i < topDominators.length && snapshot.getRetainedHeapSize(topDominators[i]) > threshold)
{
suspiciousObjects.add(topDominators[i]);
suspectNames.add(snapshot.getClassOf(topDominators[i]).getName());
i++;
}
if (listener.isCanceled())
throw new IProgressListener.OperationCanceledException();
/*
* Find suspect classes
*/
listener.subTask(Messages.FindLeaksQuery_SearchingGroupsOfObjects);
Histogram histogram = groupByClasses(topDominators, listener);
ArrayList<ClassHistogramRecord> suspiciousClasses = new ArrayList<ClassHistogramRecord>();
ClassHistogramRecord[] classRecords = histogram.getClassHistogramRecords().toArray(new ClassHistogramRecord[0]);
Arrays.sort(classRecords, Histogram.reverseComparator(Histogram.COMPARATOR_FOR_RETAINEDHEAPSIZE));
int k = 0;
while (k < classRecords.length && classRecords[k].getRetainedHeapSize() > threshold)
{
// avoid showing class-suspect for s.th. which was found on object
// level
if (!suspectNames.contains(classRecords[k].getLabel()))
{
suspiciousClasses.add(classRecords[k]);
}
k++;
}
if (listener.isCanceled())
throw new IProgressListener.OperationCanceledException();
/*
* build the results
*/
return buildResult(suspiciousObjects, suspiciousClasses, totalHeap, listener);
}
private Histogram groupByClasses(int[] dominated, IProgressListener listener) throws SnapshotException
{
Histogram histogram = snapshot.getHistogram(dominated, listener);
if (listener.isCanceled())
throw new IProgressListener.OperationCanceledException();
Collection<ClassHistogramRecord> records = histogram.getClassHistogramRecords();
ClassHistogramRecord[] arr = new ClassHistogramRecord[records.size()];
int i = 0;
for (ClassHistogramRecord record : records)
{
record.setRetainedHeapSize(sumRetainedSize(record.getObjectIds(), snapshot));
arr[i++] = record;
if (i % 10 == 0 && listener.isCanceled())
throw new IProgressListener.OperationCanceledException();
}
Collection<ClassLoaderHistogramRecord> loaderRecords = histogram.getClassLoaderHistogramRecords();
ClassLoaderHistogramRecord[] loaderArr = new ClassLoaderHistogramRecord[loaderRecords.size()];
i = 0;
for (ClassLoaderHistogramRecord record : loaderRecords)
{
long retainedSize = 0;
for (ClassHistogramRecord classRecord : record.getClassHistogramRecords())
{
retainedSize += classRecord.getRetainedHeapSize();
}
record.setRetainedHeapSize(retainedSize);
loaderArr[i++] = record;
}
return histogram;
}
private long sumRetainedSize(int[] objectIds, ISnapshot snapshot) throws SnapshotException
{
long sum = 0;
for (int id : objectIds)
{
sum += snapshot.getRetainedHeapSize(id);
}
return sum;
}
private AccumulationPoint findAccumulationPoint(int bigObjectId) throws SnapshotException
{
int dominator = bigObjectId;
double dominatorRetainedSize = snapshot.getRetainedHeapSize(dominator);
int dominated[] = snapshot.getImmediateDominatedIds(dominator);
int depth = 0;
while (dominated != null && dominated.length != 0 && depth < MAX_DEPTH)
{
double dominatedRetainedSize = snapshot.getRetainedHeapSize(dominated[0]);
if (dominatedRetainedSize / dominatorRetainedSize < big_drop_ratio) { return new AccumulationPoint(snapshot
.getObject(dominator)); }
dominatorRetainedSize = dominatedRetainedSize;
dominator = dominated[0];
dominated = snapshot.getImmediateDominatedIds(dominator);
depth++;
}
if (dominated == null || dominated.length == 0)
return new AccumulationPoint(snapshot.getObject(dominator));
return null;
}
static class ExcludesConverter extends Path2GCRootsQuery
{
public static Map<IClass, Set<String>> convert(ISnapshot snapshot, List<String> excludes)
throws SnapshotException
{
return Path2GCRootsQuery.convert(snapshot, excludes);
}
}
private SuspectRecord buildSuspectRecordGroupOfObjects(ClassHistogramRecord record, IProgressListener listener)
throws SnapshotException
{
int[] objectIds = getRandomIds(record.getObjectIds());
IObject suspectClass = snapshot.getObject(record.getClassId());
// calculate the shortest paths to all
// avoid weak paths
// Unfinalized objects from J9 and HotSpot
// convert excludes into the required format
Map<IClass, Set<String>> excludeMap = ExcludesConverter.convert(snapshot, excludes);
IMultiplePathsFromGCRootsComputer comp = snapshot.getMultiplePathsFromGCRoots(objectIds, excludeMap);
MultiplePathsFromGCRootsRecord[] records = comp.getPathsByGCRoot(listener);
ArrayIntBig commonPath = new ArrayIntBig();
if (listener.isCanceled())
throw new IProgressListener.OperationCanceledException();
if (records.length == 0)
{
// We have no paths with all the excludes, so try again without the excludes
comp = snapshot.getMultiplePathsFromGCRoots(objectIds, Collections.emptyMap());
records = comp.getPathsByGCRoot(listener);
if (listener.isCanceled())
throw new IProgressListener.OperationCanceledException();
}
if (records.length > 0)
{
int numPaths = comp.getAllPaths(listener).length;
int diff = objectIds.length - numPaths;
if (diff > 0)
{
listener.sendUserMessage(IProgressListener.Severity.INFO,
MessageUtil.format(Messages.FindLeaksQuery_PathNotFound, diff, objectIds.length), null);
}
setRetainedSizesForMPaths(records, snapshot);
Arrays.sort(records, MultiplePathsFromGCRootsRecord.getComparatorByNumberOfReferencedObjects());
MultiplePathsFromGCRootsRecord parentRecord = records[0];
// parentRecord.getReferencedRetainedSize()
int threshold = (int) (group_suspects_accumulation_ratio * objectIds.length);
while (parentRecord.getCount() > threshold)
{
// System.out.println("count: " + parentRecord.getCount());
commonPath.add(parentRecord.getObjectId());
MultiplePathsFromGCRootsRecord[] children = parentRecord.nextLevel();
if (children == null || children.length == 0)
{
// reached the end ?! report the parent as it is big enough
AccumulationPoint accPoint = new AccumulationPoint(snapshot.getObject(parentRecord.getObjectId()));
SuspectRecordGroupOfObjects result = new SuspectRecordGroupOfObjects(suspectClass,
record.getObjectIds(), record.getRetainedHeapSize(), accPoint, commonPath.toArray(),
comp);
return result;
}
setRetainedSizesForMPaths(children, snapshot);
Arrays.sort(children, MultiplePathsFromGCRootsRecord.getComparatorByNumberOfReferencedObjects());
if ((double) children[0].getReferencedRetainedSize()
/ (double) parentRecord.getReferencedRetainedSize() < big_drop_ratio)
{
// there is a big drop here - return the parent
AccumulationPoint accPoint = new AccumulationPoint(snapshot.getObject(parentRecord.getObjectId()));
SuspectRecordGroupOfObjects result = new SuspectRecordGroupOfObjects(suspectClass,
record.getObjectIds(), record.getRetainedHeapSize(), accPoint, commonPath.toArray(),
comp);
return result;
}
// no big drop - take the biggest child and try again
parentRecord = children[0];
}
}
// return a SuspectRecord without an accumulation point
return new SuspectRecordGroupOfObjects(suspectClass, record.getObjectIds(), record.getRetainedHeapSize(), null,
commonPath.toArray(), comp);
}
private void setRetainedSizesForMPaths(MultiplePathsFromGCRootsRecord[] records, ISnapshot snapshot)
throws SnapshotException
{
for (MultiplePathsFromGCRootsRecord rec : records)
{
int[] referencedObjects = rec.getReferencedObjects();
long retained = 0;
for (int objectId : referencedObjects)
{
retained += snapshot.getRetainedHeapSize(objectId);
}
rec.setReferencedRetainedSize(retained);
}
}
private IResult buildResult(ArrayInt suspiciousObjects, ArrayList<ClassHistogramRecord> suspiciousClasses,
long totalHeap, IProgressListener listener) throws SnapshotException
{
SuspectRecord[] allSuspects = new SuspectRecord[suspiciousObjects.size() + suspiciousClasses.size()];
int j = 0;
int[] suspectObjIds = suspiciousObjects.toArray();
for (int objectId : suspectObjIds)
{
if (listener.isCanceled())
throw new IProgressListener.OperationCanceledException();
IObject suspectObject = snapshot.getObject(objectId);
AccumulationPoint accPoint = findAccumulationPoint(objectId);
SuspectRecord r = new SuspectRecord(suspectObject, suspectObject.getRetainedHeapSize(), accPoint);
allSuspects[j++] = r;
}
for (ClassHistogramRecord record : suspiciousClasses)
{
if (listener.isCanceled())
throw new IProgressListener.OperationCanceledException();
SuspectRecord r = buildSuspectRecordGroupOfObjects(record, /*
* (long)
* (
* threshold
* 0.7),
*/listener);
allSuspects[j++] = r;
}
return new SuspectsResultTable(allSuspects, totalHeap);
}
private int[] getRandomIds(int[] objectIds)
{
if (objectIds.length <= max_paths)
return objectIds;
MATPlugin.log(new Status(Status.INFO, MATPlugin.PLUGIN_ID, MessageUtil.format(
Messages.FindLeaksQuery_TooManySuspects,
objectIds.length, max_paths)));
Random random = new Random();
int length = objectIds.length;
BitField visited = new BitField(length);
int[] result = new int[max_paths];
for (int i = 0; i < max_paths; i++)
{
int index = random.nextInt(length);
while (visited.get(index))
index = random.nextInt(length);
visited.set(index);
result[i] = objectIds[index];
}
return result;
}
public static class AccumulationPoint
{
IObject object;
public AccumulationPoint(IObject object)
{
this.object = object;
}
public IObject getObject()
{
return object;
}
public long getRetainedHeapSize()
{
return getObject().getRetainedHeapSize();
}
}
public static class AccumulationPointOfGroupOfObject extends AccumulationPoint
{
int[] commonPath;
IMultiplePathsFromGCRootsComputer pathsComputer;
public AccumulationPointOfGroupOfObject(IObject object, int[] commonPath,
IMultiplePathsFromGCRootsComputer pathsComputer)
{
super(object);
this.commonPath = commonPath.clone(); // clone to keep SpotBugs happy
this.pathsComputer = pathsComputer;
}
public int[] getCommonPath()
{
return commonPath.clone(); // clone to keep SpotBugs happy
}
public IMultiplePathsFromGCRootsComputer getPathsComputer()
{
return pathsComputer;
}
}
public static class SuspectRecordGroupOfObjects extends SuspectRecord
{
int[] commonPath;
IMultiplePathsFromGCRootsComputer pathsComputer;
int[] suspectInstances;
SuspectRecordGroupOfObjects(IObject suspect, int[] suspectInstances, long suspectRetained,
AccumulationPoint accumulationPoint, int[] commonPath,
IMultiplePathsFromGCRootsComputer pathsComputer)
{
super(suspect, suspectRetained, accumulationPoint);
this.suspectInstances = suspectInstances;
this.commonPath = commonPath;
this.pathsComputer = pathsComputer;
}
public int[] getCommonPath()
{
return commonPath.clone(); // clone to keep SpotBugs happy
}
public IMultiplePathsFromGCRootsComputer getPathsComputer()
{
return pathsComputer;
}
public int[] getSuspectInstances()
{
return suspectInstances.clone(); // clone to keep SpotBugs happy;
}
}
public static class SuspectRecord
{
IObject suspect;
Bytes suspectRetained;
AccumulationPoint accumulationPoint;
SuspectRecord(IObject suspect, long suspectRetained, AccumulationPoint accumulationPoint)
{
this.suspect = suspect;
this.suspectRetained = new Bytes(suspectRetained);
this.accumulationPoint = accumulationPoint;
}
public IObject getSuspect()
{
return suspect;
}
public long getSuspectRetained()
{
return suspectRetained.getValue();
}
public AccumulationPoint getAccumulationPoint()
{
return accumulationPoint;
}
}
public static class SuspectsResultTable implements IResultTable
{
SuspectRecord[] data;
long totalHeap;
public SuspectsResultTable(SuspectRecord[] data, long totalHeap)
{
this.data = data.clone(); // clone to keep SpotBugs happy
this.totalHeap = totalHeap;
}
public ResultMetaData getResultMetaData()
{
return new ResultMetaData.Builder() //
.addContext(new ContextProvider(Messages.FindLeaksQuery_LeakSuspect)
{
@Override
public IContextObject getContext(Object row)
{
return getLeakSuspect(row);
}
}) //
.addContext(new ContextProvider(Messages.FindLeaksQuery_AccumulationPoint)
{
@Override
public IContextObject getContext(Object row)
{
return getAccumulationPoint(row);
}
}) //
.build();
}
public Column[] getColumns()
{
return new Column[] { new Column(Messages.FindLeaksQuery_ColumnLeakSuspect), //
new Column(Messages.FindLeaksQuery_Column_NumObjects, Long.class), //
new Column(Messages.FindLeaksQuery_Column_SuspectRetainedHeap, Bytes.class), //
new Column(Messages.FindLeaksQuery_Column_SuspectPercent, Double.class).formatting(NumberFormat.getPercentInstance()), //
new Column(Messages.FindLeaksQuery_Column_AccumulationPoint), //
new Column(Messages.FindLeaksQuery_Column_AccPointRetainedHeap, Bytes.class), //
new Column(Messages.FindLeaksQuery_Column_AccPointPercent, Double.class).formatting(NumberFormat.getPercentInstance()) };
}
public int getRowCount()
{
return data.length;
}
public SuspectRecord getRow(int rowId)
{
return data[rowId];
}
public Object getColumnValue(Object row, int columnIndex)
{
SuspectRecord suspect = (SuspectRecord) row;
switch (columnIndex)
{
case 0:
return suspect.suspect.getTechnicalName();
case 1:
return suspect instanceof SuspectRecordGroupOfObjects ? ((SuspectRecordGroupOfObjects) suspect).suspectInstances.length
: 1;
case 2:
return suspect.suspectRetained;
case 3:
return Double.valueOf((double) suspect.getSuspectRetained() / (double) totalHeap);
case 4:
return suspect.accumulationPoint == null ? Messages.FindLeaksQuery_NotFound : suspect.accumulationPoint.getObject()
.getTechnicalName();
case 5:
return new Bytes(suspect.accumulationPoint == null ? 0 : suspect.accumulationPoint
.getRetainedHeapSize());
case 6:
return Double.valueOf(suspect.accumulationPoint == null ? 0 : (double) suspect.accumulationPoint
.getRetainedHeapSize()
/ (double) totalHeap);
}
return null;
}
public IContextObject getContext(final Object row)
{
return new IContextObject()
{
public int getObjectId()
{
return ((SuspectRecord) row).suspect.getObjectId();
}
};
}
IContextObject getLeakSuspect(Object row)
{
final SuspectRecord suspect = (SuspectRecord) row;
if (suspect instanceof SuspectRecordGroupOfObjects)
{
return new IContextObjectSet()
{
public int getObjectId()
{
return suspect.suspect.getObjectId();
}
public int[] getObjectIds()
{
return ((SuspectRecordGroupOfObjects) suspect).suspectInstances;
}
public String getOQL()
{
return null;
}
};
}
else
{
return new IContextObject()
{
public int getObjectId()
{
return suspect.suspect.getObjectId();
}
};
}
}
IContextObject getAccumulationPoint(final Object row)
{
final SuspectRecord suspect = (SuspectRecord) row;
if (suspect.accumulationPoint == null)
return null;
return new IContextObject()
{
public int getObjectId()
{
return suspect.accumulationPoint.getObject().getObjectId();
}
};
}
public SuspectRecord[] getData()
{
return data.clone(); // clone to keep SpotBugs happy;;
}
public long getTotalHeap()
{
return totalHeap;
}
}
}