-
Notifications
You must be signed in to change notification settings - Fork 7
/
GeneralSnapshotTests.java
1341 lines (1284 loc) · 55 KB
/
GeneralSnapshotTests.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) 2010,2020 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Andrew Johnson - test class specific name for Strings etc.
*******************************************************************************/
package org.eclipse.mat.tests.snapshot;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.collection.IsEmptyCollection.emptyCollectionOf;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeNotNull;
import static org.junit.Assume.assumeThat;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.mat.SnapshotException;
import org.eclipse.mat.collect.SetInt;
import org.eclipse.mat.internal.snapshot.SnapshotQueryContext;
import org.eclipse.mat.query.IResult;
import org.eclipse.mat.query.IResultTable;
import org.eclipse.mat.query.IResultTree;
import org.eclipse.mat.query.ISelectionProvider;
import org.eclipse.mat.query.registry.QueryObjectLink;
import org.eclipse.mat.query.results.CompositeResult;
import org.eclipse.mat.query.results.DisplayFileResult;
import org.eclipse.mat.snapshot.ISnapshot;
import org.eclipse.mat.snapshot.SnapshotFactory;
import org.eclipse.mat.snapshot.SnapshotInfo;
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.IClassLoader;
import org.eclipse.mat.snapshot.model.IObject;
import org.eclipse.mat.snapshot.model.IStackFrame;
import org.eclipse.mat.snapshot.model.IThreadStack;
import org.eclipse.mat.snapshot.query.SnapshotQuery;
import org.eclipse.mat.tests.TestSnapshots;
import org.eclipse.mat.util.IProgressListener;
import org.eclipse.mat.util.VoidProgressListener;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(value = Parameterized.class)
public class GeneralSnapshotTests
{
enum Methods {
NONE,
FRAMES_ONLY,
RUNNING_METHODS,
ALL_METHODS
}
final Methods hasMethods;
enum Stacks {
NONE,
FRAMES,
FRAMES_AND_OBJECTS
};
final Stacks stackInfo;
@Parameters(name="{index}: Snapshot={0} options={1}")
public static Collection<Object[]> data()
{
return Arrays.asList(new Object[][] {
{TestSnapshots.SUN_JDK6_32BIT, Stacks.NONE},
{TestSnapshots.SUN_JDK5_64BIT, Stacks.NONE},
{TestSnapshots.SUN_JDK6_18_32BIT, Stacks.FRAMES_AND_OBJECTS},
{TestSnapshots.SUN_JDK6_18_64BIT, Stacks.FRAMES_AND_OBJECTS},
{TestSnapshots.SUN_JDK5_13_32BIT, Stacks.NONE},
{TestSnapshots.IBM_JDK6_32BIT_HEAP, Stacks.NONE},
{TestSnapshots.IBM_JDK6_32BIT_JAVA, Stacks.FRAMES},
{TestSnapshots.IBM_JDK6_32BIT_HEAP_AND_JAVA, Stacks.FRAMES},
{TestSnapshots.IBM_JDK6_32BIT_SYSTEM, Stacks.FRAMES_AND_OBJECTS},
{"allMethods", Stacks.FRAMES_AND_OBJECTS},
{"runningMethods", Stacks.FRAMES_AND_OBJECTS},
{"framesOnly", Stacks.FRAMES_AND_OBJECTS},
{"noMethods", Stacks.FRAMES_AND_OBJECTS},
{TestSnapshots.IBM_JDK142_32BIT_HEAP, Stacks.NONE},
{TestSnapshots.IBM_JDK142_32BIT_JAVA, Stacks.FRAMES},
{TestSnapshots.IBM_JDK142_32BIT_HEAP_AND_JAVA, TestSnapshots.DTFJreadJavacore142 ? Stacks.FRAMES : Stacks.NONE},
{TestSnapshots.IBM_JDK142_32BIT_SYSTEM, Stacks.FRAMES},
{TestSnapshots.ORACLE_JDK7_21_64BIT, Stacks.FRAMES_AND_OBJECTS},
{TestSnapshots.ORACLE_JDK8_05_64BIT, Stacks.FRAMES_AND_OBJECTS},
{TestSnapshots.ORACLE_JDK9_01_64BIT, Stacks.FRAMES_AND_OBJECTS},
{TestSnapshots.ADOPTOPENJDK_HOTSPOT_JDK11_0_4_11_64BIT, Stacks.FRAMES_AND_OBJECTS},
});
}
public GeneralSnapshotTests(String snapshotname, Stacks s)
{
if (snapshotname.equals("allMethods")) {
snapshot = snapshot2(TestSnapshots.IBM_JDK6_32BIT_SYSTEM, "all");
hasMethods = Methods.ALL_METHODS;
}
else if (snapshotname.equals("runningMethods")) {
snapshot = snapshot2(TestSnapshots.IBM_JDK6_32BIT_SYSTEM, "running");
hasMethods = Methods.RUNNING_METHODS;
}
else if (snapshotname.equals("framesOnly")) {
snapshot = snapshot2(TestSnapshots.IBM_JDK6_32BIT_SYSTEM, "frames");
hasMethods = Methods.FRAMES_ONLY;
}
else if (snapshotname.equals("noMethods")) {
snapshot = snapshot2(TestSnapshots.IBM_JDK6_32BIT_SYSTEM, "none");
hasMethods = Methods.NONE;
}
else
{
snapshot = TestSnapshots.getSnapshot(snapshotname, false);
hasMethods = Methods.NONE;
}
stackInfo = s;
}
/**
* Create a snapshot with the methods as classes option
*/
public ISnapshot snapshot2(String snapshotname, String includeMethods)
{
final String dtfjPlugin = "org.eclipse.mat.dtfj";
final String key = "methodsAsClasses";
IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(dtfjPlugin);
String prev = preferences.get(key, null);
preferences.put(key, includeMethods);
try {
// Tag the snapshot name so we don't end up with the wrong version
ISnapshot ret = TestSnapshots.getSnapshot(snapshotname+";#"+includeMethods, false);
return ret;
} finally {
if (prev != null)
preferences.put(key, prev);
else
preferences.remove(key);
}
}
final ISnapshot snapshot;
@Test
public void stacks1() throws SnapshotException
{
int frames = 0;
int foundTop = 0;
int foundNotTop = 0;
SetInt objs = new SetInt();
Collection<IClass>tClasses = snapshot.getClassesByName("java.lang.Thread", true);
if (tClasses != null) for (IClass thrdcls : tClasses)
{
for (int o : thrdcls.getObjectIds())
{
objs.add(o);
}
}
/*
* PHD+javacore sometimes doesn't mark javacore threads as type Thread as
* javacore thread id is not a real object id.
*/
for (int o : snapshot.getGCRoots())
{
for (GCRootInfo g : snapshot.getGCRootInfo(o)) {
if (g.getType() == Type.THREAD_OBJ) {
objs.add(o);
}
}
}
for (int o : objs.toArray())
{
IThreadStack stk = snapshot.getThreadStack(o);
if (stk != null)
{
int i = 0;
for (IStackFrame frm : stk.getStackFrames())
{
int os[] = frm.getLocalObjectsIds();
if (os != null)
{
if (i == 0)
foundTop += os.length;
else
foundNotTop += os.length;
}
++i;
++frames;
}
}
}
// If there were some frames, and some frames had some objects
// then a topmost frame should have some objects
if (frames > 0 && foundNotTop > 0)
{
assertTrue("Expected some objects on top of stack", foundTop > 0);
}
if (this.stackInfo != Stacks.NONE)
{
assertTrue(frames > 0);
if (this.stackInfo == Stacks.FRAMES_AND_OBJECTS)
assertTrue(foundNotTop > 0 || foundTop > 0);
}
}
@Test
public void totalClasses() throws SnapshotException
{
int nc = snapshot.getClasses().size();
int n = snapshot.getSnapshotInfo().getNumberOfClasses();
assertEquals("Total classes", n, nc);
}
@Test
public void totalObjects() throws SnapshotException
{
int no = 0;
for (IClass cls : snapshot.getClasses())
{
no += cls.getNumberOfObjects();
}
int n = snapshot.getSnapshotInfo().getNumberOfObjects();
assertEquals("Total objects", n, no);
}
@Test
public void totalHeapSize() throws SnapshotException
{
long total = 0;
for (IClass cls : snapshot.getClasses())
{
total += snapshot.getHeapSize(cls.getObjectIds());
}
long n = snapshot.getSnapshotInfo().getUsedHeapSize();
assertEquals("Total heap size", n, total);
}
@Test
public void objectSizes() throws SnapshotException
{
long total = 0;
for (IClass cls : snapshot.getClasses())
{
long prev = -1;
for (int o : cls.getObjectIds())
{
IObject obj = snapshot.getObject(o);
long n = obj.getUsedHeapSize();
long n2 = snapshot.getHeapSize(o);
if (n != n2)
{
assertEquals("snapshot object heap size / object heap size "+obj, n, n2);
}
total += n;
if (prev >= 0)
{
if (prev != n && !cls.isArrayType() && !(obj instanceof IClass))
{
// This might not be a problem as variable sized plain objects
// are now permitted using the array index to record the alternative sizes.
// However, the current dumps don't appear to have them, so test for it here.
// Future dumps may make this test fail.
assertEquals("Variable size plain objects " + cls + " " + obj, prev, n);
}
}
else if (!(obj instanceof IClass))
{
// IClass objects are variably sized, so don't track those
prev = n;
}
assertEquals("All instance of a class must be of that type", cls, obj.getClazz());
}
}
long n = snapshot.getSnapshotInfo().getUsedHeapSize();
assertEquals("Total heap size", n, total);
}
@Test
public void topComponents() throws SnapshotException
{
SnapshotQuery query = SnapshotQuery.lookup("component_report_top", snapshot);
query.setArgument("aggressive", true);
IResult result = query.execute(new CheckedProgressListener(collector));
assertTrue(result != null);
}
@Test
public void topReferenceLeak() throws SnapshotException
{
SnapshotQuery query = SnapshotQuery.parse("reference_leak java.lang.ref.WeakReference -include_subclasses -maxpaths 10 -factor 0.2", snapshot);
IResult result = query.execute(new CheckedProgressListener(collector));
assertTrue(result != null);
if (result instanceof CompositeResult)
{
CompositeResult r = (CompositeResult)result;
// Check each of the subresults
for (CompositeResult.Entry e : r.getResultEntries())
{
IResult r2 = e.getResult();
assertNotNull(r2);
// Check the trees have some selected rows and some are expanded
if (r2 instanceof IResultTree)
{
assertNotNull(e.getName());
IResultTree rt = (IResultTree)r2;
assertThat(rt.getElements().size(), greaterThan(0));
int selected = 0;
int expanded = 0;
for (Object o : rt.getElements())
{
if (rt instanceof ISelectionProvider)
{
ISelectionProvider ss = (ISelectionProvider)rt;
if (ss.isSelected(o))
++selected;
if (ss.isExpanded(o))
++expanded;
}
while (rt.hasChildren(o))
{
// Has children, but zero of them?
if (rt.getChildren(o).size() == 0)
break;
// Just search the first entry each time
o = rt.getChildren(o).get(0);
if (rt instanceof ISelectionProvider)
{
ISelectionProvider ss = (ISelectionProvider)rt;
if (ss.isSelected(o))
++selected;
if (ss.isExpanded(o))
++expanded;
}
}
}
assertThat("selected "+e.getName(), selected, greaterThan(0));
assertThat("expanded "+e.getName(), expanded, greaterThan(0));
}
}
}
}
@Test
public void testMethods() throws SnapshotException
{
int methods = 0;
int methodsWithObjects = 0;
for (IClass cls : snapshot.getClasses())
{
if (cls.getName().contains("(") || cls.getName().equals("<stack frame>"))
{
++methods;
if (cls.getObjectIds().length > 0)
++methodsWithObjects;
}
}
if (hasMethods == Methods.ALL_METHODS)
{
assertTrue(methods > 0);
assertTrue(methods > methodsWithObjects);
}
else if (hasMethods == Methods.RUNNING_METHODS)
{
assertTrue(methods > 0);
assertEquals(methods, methodsWithObjects);
}
else if (hasMethods == Methods.FRAMES_ONLY)
{
assertEquals(1, methods);
assertThat(methodsWithObjects, greaterThan(0));
}
else
{
assertEquals(0, methodsWithObjects);
assertEquals(0, methods);
}
}
@Test
public void testClassLoaders() throws SnapshotException
{
assertThat(snapshot.getSnapshotInfo().getNumberOfClassLoaders(), greaterThan(1));
}
@Test
public void testRegressionReport() throws SnapshotException, IOException
{
SnapshotQuery query = SnapshotQuery.parse("default_report org.eclipse.mat.tests:regression", snapshot);
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
checkHTMLResult(t);
}
@Test
public void testPerformanceReport() throws SnapshotException, IOException
{
SnapshotQuery query = SnapshotQuery.parse("default_report org.eclipse.mat.tests:performance", snapshot);
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
checkHTMLResult(t);
}
@Test
public void testLeakSuspectsReport() throws SnapshotException, IOException
{
SnapshotQuery query = SnapshotQuery.parse("default_report org.eclipse.mat.api:suspects", snapshot);
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
checkHTMLResult(t);
}
@Test
public void testOverviewReport() throws SnapshotException, IOException
{
SnapshotQuery query = SnapshotQuery.parse("default_report org.eclipse.mat.api:overview", snapshot);
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
checkHTMLResult(t);
// See if the zip exists
String prefix = snapshot.getSnapshotInfo().getPrefix();
// Remove dot
prefix = prefix.substring(0, prefix.length() - 1);
File zipf = new File(prefix + "_System_Overview.zip");
assertThat(zipf.toString(), zipf.length(), greaterThan(100L));
}
/**
* See if a report with a new name is created if the old one is not writable.
* Bug 55835
* @throws SnapshotException
* @throws IOException
*/
@Test
public void testOverviewReportRename() throws SnapshotException, IOException
{
// Lock the normal output file
String prefix = snapshot.getSnapshotInfo().getPrefix();
// Remove dot
prefix = prefix.substring(0, prefix.length() - 1);
File out1 = new File(prefix + "_System_Overview.zip");
FileOutputStream fos = new FileOutputStream(out1);
//readonly seems to be sufficient for this test
//FileLock lock = fos.getChannel().lock();
try
{
// Charset doesn't really matter
fos.write("Testing".getBytes(Charset.defaultCharset()));
assertThat(out1.toString(), out1.setReadOnly(), equalTo(true));
/*
* Not actually a need to keep the file open as only prevents
* delete on Windows.
*/
// The new output file
File out2 = new File(prefix + "_System_Overview_1.zip");
assertThat(out2.toString(), out2.exists(), equalTo(false));
SnapshotQuery query = SnapshotQuery.parse("default_report org.eclipse.mat.api:overview", snapshot);
try
{
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
checkHTMLResult(t);
// check the new zipped report file exists
assertThat(out2.toString(), out2.exists(), equalTo(true));
assertThat(out2.toString(), out2.length(), greaterThan(100L));
assertThat(out2.toString(), out2.delete(), equalTo(true));
}
finally
{
if (out2.exists() && !out2.delete())
System.out.println("unable to delete "+out2);
}
//lock.close();
fos.close();
assertThat(out1.toString(), out1.delete(), equalTo(true));
}
finally
{
//lock.close();
fos.close();
if (out1.exists() && !out1.delete())
System.out.println("unable to delete "+out1);
}
}
/**
* See if a new file is not created if the old file is not writable,
* but contains the same contents as the new file.
* Bug 558353
* @throws SnapshotException
* @throws IOException
*/
@Test
public void testOverviewReportRename2() throws SnapshotException, IOException
{
String prefix = snapshot.getSnapshotInfo().getPrefix();
// Remove dot
prefix = prefix.substring(0, prefix.length() - 1);
File out1 = new File(prefix + "_System_Overview.zip");
if (out1.exists())
assertThat(out1.toString(), out1.delete(), equalTo(true));
// The new output file
File out2 = new File(prefix + "_System_Overview_1.zip");
if (out2.exists())
assertThat(out2.toString(), out2.delete(), equalTo(true));
SnapshotQuery query = SnapshotQuery.parse("default_report org.eclipse.mat.api:overview", snapshot);
try
{
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
checkHTMLResult(t);
assertThat(out1.toString(), out1.exists(), equalTo(true));
assertThat(out1.toString(), out1.length(), greaterThan(100L));
assertThat(out2.toString(), out2.exists(), equalTo(false));
// Lock the usual output file
assertThat(out1.toString(), out1.setReadOnly(), equalTo(true));
FileInputStream fis = new FileInputStream(out1);
//readonly seems to be sufficient for this test
//FileLock lock = fis.getChannel().lock(0, Long.MAX_VALUE, true);
long mdate = out1.lastModified();
long len1 = out1.length();
try
{
query = SnapshotQuery.parse("default_report org.eclipse.mat.api:overview", snapshot);
t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
checkHTMLResult(t);
assertThat(out1.toString(), out1.exists(), equalTo(true));
assertThat(out1.length(), equalTo(len1));
long mdate2 = out1.lastModified();
// Modification date should not change as the file should not have been rewritten
assertThat(out1.toString(), mdate2, equalTo(mdate));
// but a new file should not have been created either
assertThat(out2.toString(), out2.exists(), equalTo(false));
}
finally
{
if (out2.exists() && !out2.delete())
System.out.println("unable to delete "+out2);
//lock.release();
fis.close();
}
assertThat(out1.toString(), out1.delete(), equalTo(true));
}
finally
{
if (out1.exists() && !out1.delete())
System.out.println("unable to delete "+out1);
}
}
@Test
public void testTopComponentsReport() throws SnapshotException, IOException
{
SnapshotQuery query = SnapshotQuery.parse("default_report org.eclipse.mat.api:top_components", snapshot);
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
checkHTMLResult(t);
}
@Rule
public ErrorCollector collector = new ErrorCollector();
static class CheckedProgressListener extends VoidProgressListener
{
ErrorCollector collector = new ErrorCollector();
public CheckedProgressListener(ErrorCollector collector)
{
this.collector = collector;
}
public void sendUserMessage(Severity severity, String message, Throwable exception)
{
if (exception != null && severity != Severity.INFO)
collector.addError(exception);
collector.checkThat(message, severity, lessThan(Severity.WARNING));
}
};
@Test
public void testAllQueriesReport() throws SnapshotException, IOException
{
IProgressListener checkListener = new CheckedProgressListener(collector);
SnapshotQuery query = SnapshotQuery.parse("default_report org.eclipse.mat.tests:all", snapshot);
IResult t = query.execute(checkListener);
assertNotNull(t);
checkHTMLResult(t);
}
public void checkHTMLResult(IResult r) throws IOException, SnapshotException
{
assertThat(r, instanceOf(DisplayFileResult.class));
if (r instanceof DisplayFileResult)
{
DisplayFileResult d = (DisplayFileResult)r;
File f = d.getFile();
checkHTMLFile(f);
}
}
/**
* Recursively check an HTML file.
* @param f
* @throws IOException
*/
public void checkHTMLFile(File f) throws IOException, SnapshotException
{
Set<File>seen = new HashSet<File>();
checkHTMLFile(f, seen);
}
/**
* Recursively check an HTML file, avoiding going
* into files already seen.
* @param f
* @param seen Files already seen
* @throws IOException
*/
public void checkHTMLFile(File f, Set<File>seen) throws IOException, SnapshotException
{
// canonical needed to avoid problems with ..
if (!seen.add(f.getCanonicalFile()))
return;
FileInputStream fis = new FileInputStream(f);
try
{
if (!f.getName().endsWith(".html"))
{
// Not HTML
return;
}
String encoding = System.getProperty("file.encoding", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
try
{
// Convert to canonical form
encoding = Charset.forName(encoding).name();
}
catch (IllegalCharsetNameException e)
{
// Ignore
}
// Read the file into a string
InputStreamReader ir = new InputStreamReader(fis, encoding);
char cbuf[] = new char[(int)f.length()];
int l = ir.read(cbuf);
String s = new String(cbuf, 0, l);
/*
* All these checks are approximate and would be confused
* by false tags in attribute value string etc.
*/
// Some basic checks
assertThat("Expected charset", s, containsString("content=\"text/html;charset=" + encoding + "\""));
assertThat("Possible double escaping <", s, not(containsString("&lt;")));
assertThat("Possible double escaping &", s, not(containsString("&amp;")));
/*
* Rough test for bad tag - might indicate unescaped '<'.
* Find a less-than sign
* Negative lookahead for:
* optional / or !
* series of letters
* then optional digits
* ending with a space or greater-than
* or !DOCTYPE
* then match all until next space or greater-than
* We normally have lower case tags and no self-closed tags.
*/
Pattern p = Pattern.compile("<(?!(/?[a-z]+[0-9]*)[ >]|!DOCTYPE )[^ >]*");
Matcher m = p.matcher(s);
String v;
if (m.find())
{
v = m.group(0);
}
else
{
v = null;
}
assertThat("Bad tag in "+f, v, equalTo(null));
/*
* Rough test for bad entity or unescaped ampersand.
* Negative lookahead for
* entity name followed by semicolon
* entity number preceded by # followed by semicolon
*/
p = Pattern.compile("&(?!([a-z]+;)|(#[0-9]+;))[^a-z#]+");
m = p.matcher(s);
if (m.find())
{
v = m.group(0);
}
else
{
v = null;
}
assertThat("Bad entity in "+f, v, equalTo(null));
/*
* Check for alt text for images.
*/
p = Pattern.compile("<img (?![^>]*alt)[^>]*>");
m = p.matcher(s);
if (m.find())
{
v = m.group(0);
}
else
{
v = null;
}
assertThat("No alt for img in "+f, v, equalTo(null));
/*
* Check for alt text for areas.
*/
p = Pattern.compile("<area (?![^>]*alt)[^>]*>");
m = p.matcher(s);
if (m.find())
{
v = m.group(0);
}
else
{
v = null;
}
assertThat("No alt for area in "+f, v, equalTo(null));
/*
* Rough check for nesting of tags.
*/
Stack<String> stk = new Stack<String>();
Stack<Integer> stki = new Stack<Integer>();
// Matches tags
p = Pattern.compile("</?[a-z]+[1-6]?");
m = p.matcher(s);
while (m.find())
{
String tag = m.group().substring(1);
if (tag.startsWith("/"))
{
// Closing tag
assertThat("Stack for "+tag, stk.size(), greaterThan(0));
tag = tag.substring(1);
String tag2 = stk.pop();
int si = stki.pop();
if (tag2.equals("p") && !tag.equals("a") && !tag.equals("p"))
{
// <p> closed by any outer tag except <a>
tag2 = stk.pop();
si = stki.pop();
assertThat("Stack for "+tag, stk.size(), greaterThan(0));
}
String range = s.substring(si, m.end());
assertThat("Tag closing at " + m.start()+" "+range+" "+f, tag, equalTo(tag2));
}
else
{
// Self closing tag?
if (!(tag.equals("br")
|| tag.equals("hr")
|| tag.equals("img")
|| tag.equals("link")
|| tag.equals("input")
|| tag.equals("meta")
|| tag.equals("area")))
{
// <p> is closed by following block tag
if (stk.size() >= 1 && stk.peek().equals("p") && (
tag.equals("h1") ||
tag.equals("h2") ||
tag.equals("h3") ||
tag.equals("h4") ||
tag.equals("h5") ||
tag.equals("h6") ||
tag.equals("pre") ||
tag.equals("ol") ||
tag.equals("ul") ||
tag.equals("div")))
{
// Close the <p> tag
stk.pop();
stki.pop();
}
stk.push(tag);
stki.push(m.start());
}
}
}
assertThat("Stack should be empty", stk.size(), equalTo(0));
// Look for references to other files
for (int i = 0; i >= 0; )
{
String match = "href=\"";
i = s.indexOf(match, i);
if (i >= 0)
{
int j = s.indexOf("\"", i + match.length());
String fn = s.substring(i + match.length(), j);
if (!fn.startsWith("/") && !fn.contains("#") && !fn.startsWith("http") && !fn.startsWith(QueryObjectLink.PROTOCOL))
{
File d = f.getParentFile();
File newf = new File(d, fn);
checkHTMLFile(newf, seen);
}
else if (fn.startsWith(QueryObjectLink.PROTOCOL))
{
QueryObjectLink link = QueryObjectLink.parse(fn);
if (link.getType() == QueryObjectLink.Type.OBJECT)
{
String t = link.getTarget();
assertNotNull(fn, t);
SnapshotQueryContext sc = new SnapshotQueryContext(snapshot);
int id = sc.mapToObjectId(t);
}
else if (link.getType() == QueryObjectLink.Type.QUERY)
{
String t = link.getTarget();
assertNotNull(fn, t);
SnapshotQuery q = SnapshotQuery.parse(t, snapshot);
String cmdname = q.getDescriptor().getIdentifier();
IResult r = q.execute(new CheckedProgressListener(collector));
if ((cmdname.equals("system_properties") || cmdname.equals("thread_overview")|| cmdname.equals("finalizer_thread"))
&& (snapshot.getSnapshotInfo().getProperty("$heapFormat").equals("DTFJ-PHD")
|| snapshot.getSnapshotInfo().getProperty("$heapFormat")
.equals("DTFJ-Javacore")))
{
// Might not return a result for PHD but
// shouldn't fail
}
else
{
assertNotNull(t, r);
}
}
else if (link.getType() == QueryObjectLink.Type.DETAIL_RESULT)
{
String t = link.getTarget();
assertNotNull(fn, t);
}
else
{
assertTrue("Unexpected link type "+link.getType()+" "+fn, false);
}
}
i = j;
}
}
ir.close();
}
finally
{
fis.close();
}
}
@Test
public void listEntries() throws SnapshotException
{
Collection<IClass>tClasses = snapshot.getClassesByName("java.util.AbstractMap", true);
if (tClasses != null) for (IClass thrdcls : tClasses)
{
for (int o : thrdcls.getObjectIds())
{
SnapshotQuery query = SnapshotQuery.parse("extract_list_values 0x"+Long.toHexString(snapshot.mapIdToAddress(o)), snapshot);
try {
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
} catch (IllegalArgumentException e) {
}
}
}
}
@Test
public void groupByValue() throws SnapshotException
{
SnapshotQuery query = SnapshotQuery.parse("group_by_value \".*\"", snapshot);
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
// Will run name resolvers on every object!
IResultTable table = (IResultTable)t;
// Every PHD files have some empty char arrays which get resolved.
assumeThat(snapshot.getSnapshotInfo().getProperty("$heapFormat"), not(equalTo((Serializable)"DTFJ-Javacore")));
// More than one different line, so some name resolvers are working
assertThat(table.getRowCount(), greaterThan(1));
}
/**
* Test exporting as HPROF
* @param compress whether to compress the generated HPROF file
* @throws SnapshotException
* @throws IOException
*/
public void exportHPROF(boolean compress, boolean redact, long segsize) throws SnapshotException, IOException
{
// Currently can't export PHD
assumeThat(snapshot.getSnapshotInfo().getProperty("$heapFormat"), not(equalTo((Serializable)"DTFJ-PHD")));
// Currently can't export methods as classes properly
assumeThat(hasMethods, equalTo(Methods.NONE));
// HPROF parser can't handle adding links from classloader to classes for javacore
File fn = new File(snapshot.getSnapshotInfo().getPrefix());
assumeThat(fn.getName(), not(containsString("javacore")));
File tmpdir = TestSnapshots.createGeneratedName(fn.getName(), null);
File newSnapshotFile = new File(tmpdir, fn.getName() + (compress ? "hprof.gz" : "hprof"));
File mapping = redact ? new File(tmpdir, fn.getName() + "_mapping.properties") : null;
try {
SnapshotQuery query = SnapshotQuery.parse("export_hprof -output "+newSnapshotFile.getPath() +
(compress ? " -compress" : "") +
(mapping != null ? " -redact NAMES -map "+mapping.getPath() : "") +
(segsize > 0 ? " -segsize "+segsize : ""), snapshot);
IResult t = query.execute(new CheckedProgressListener(collector));
assertNotNull(t);
ISnapshot newSnapshot = SnapshotFactory.openSnapshot(newSnapshotFile, Collections.<String,String>emptyMap(), new VoidProgressListener());
try {
assertEquals("Snapshot prefix filename", new File(tmpdir, fn.getName()).getName(), new File(newSnapshot.getSnapshotInfo().getPrefix()).getName());
SnapshotInfo oldInfo = snapshot.getSnapshotInfo();
SnapshotInfo newInfo = newSnapshot.getSnapshotInfo();
assertEquals("Classes", oldInfo.getNumberOfClasses(), newInfo.getNumberOfClasses());
assertEquals("Objects", oldInfo.getNumberOfObjects(), newInfo.getNumberOfObjects());
assertEquals("Classloaders", oldInfo.getNumberOfClassLoaders(), newInfo.getNumberOfClassLoaders());
// Check number of (non-array) system classes not marked as GC root
IObject boot = snapshot.getObject(0);
int bootcls = 0;
int systemclsroot = 0;
if (boot instanceof IClassLoader)
{
IClassLoader bootldr = ((IClassLoader)boot);
if (bootldr.getObjectAddress() == 0)
{
for (IClass cl : bootldr.getDefinedClasses())
{
if (cl.isArrayType())
continue;
++bootcls;
GCRootInfo g[] = snapshot.getGCRootInfo(cl.getObjectId());
if (g != null && g.length >= 1)
{
// The class is a root for some reason
++systemclsroot;
}
}
}
}
// Parsing new HPROF will make all classes loaded by boot loader as GC roots, so adjust the expected total
// Only seems to apply for IBM 1.4.2 SDFF dumps with 'double', 'long' classes not as system class roots
assertEquals("GC Roots", oldInfo.getNumberOfGCRoots() + (bootcls - systemclsroot), newInfo.getNumberOfGCRoots());
if (redact)
{
// Check redaction
String excluded = "java\\..*|(boolean|byte|char|short|int|long|float|double|void)(\\[\\])*";
for (IClass cl : snapshot.getClasses())
{
if (cl.getName().matches(excluded))
continue;
// Should not be any classes which match the original snapshot, apart from the excluded ones above
Collection<IClass>classes = newSnapshot.getClassesByName(cl.getName(), false);
assertThat("Class matching original snapshot", classes, anyOf(emptyCollectionOf(IClass.class), nullValue()));
}
// Check that no byte arrays match the old class names