1 /*
   2  * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 package gc.g1.humongousObjects.objectGraphTest;
  25 
  26 import jdk.test.lib.process.OutputAnalyzer;
  27 import sun.hotspot.WhiteBox;
  28 
  29 import java.io.File;
  30 import java.io.IOException;
  31 import java.lang.ref.Reference;
  32 import java.lang.ref.ReferenceQueue;
  33 import java.lang.ref.SoftReference;
  34 import java.lang.ref.WeakReference;
  35 import java.nio.file.Files;
  36 import java.util.Map;
  37 import java.util.HashMap;
  38 import java.util.List;
  39 import java.util.HashSet;
  40 import java.util.Set;
  41 import java.util.function.BiConsumer;
  42 import java.util.function.Consumer;
  43 import java.util.function.Predicate;
  44 import java.util.stream.Collectors;
  45 
  46 
  47 /**
  48  * @test TestObjectGraphAfterGC
  49  * @summary Checks that objects' graph behave as expected after gc
  50  * @requires vm.gc.G1
  51  * @requires vm.opt.ExplicitGCInvokesConcurrent != true
  52  * @library /test/lib /
  53  * @modules java.management java.base/jdk.internal.misc
  54  * @build sun.hotspot.WhiteBox
  55  * @ignore 8156755
  56  *
  57  * @run driver ClassFileInstaller sun.hotspot.WhiteBox
  58  *                                sun.hotspot.WhiteBox$WhiteBoxPermission
  59  *
  60  * @run main/othervm -Xms200M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
  61  * -XX:+UnlockExperimentalVMOptions -XX:MaxGCPauseMillis=30000 -XX:G1MixedGCLiveThresholdPercent=100 -XX:G1HeapWastePercent=0
  62  * -XX:G1HeapRegionSize=1M -Xlog:gc=info:file=TestObjectGraphAfterGC_MIXED_GC.gc.log -XX:MaxTenuringThreshold=1
  63  * -XX:G1MixedGCCountTarget=1  -XX:G1OldCSetRegionThresholdPercent=100 -XX:SurvivorRatio=1 -XX:InitiatingHeapOccupancyPercent=0
  64  * gc.g1.humongousObjects.objectGraphTest.TestObjectGraphAfterGC MIXED_GC
  65  *
  66  * @run main/othervm -Xms200M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
  67  * -XX:G1HeapRegionSize=1M -Xlog:gc*=debug:file=TestObjectGraphAfterGC_YOUNG_GC.gc.log
  68  * gc.g1.humongousObjects.objectGraphTest.TestObjectGraphAfterGC YOUNG_GC
  69  *
  70  * @run main/othervm -Xms200M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
  71  * -XX:G1HeapRegionSize=1M -Xlog:gc=info:file=TestObjectGraphAfterGC_FULL_GC.gc.log
  72  * gc.g1.humongousObjects.objectGraphTest.TestObjectGraphAfterGC FULL_GC
  73  *
  74  * @run main/othervm -Xms200M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
  75  * -XX:G1HeapRegionSize=1M -Xlog:gc=info:file=TestObjectGraphAfterGC_FULL_GC_MEMORY_PRESSURE.gc.log
  76  * gc.g1.humongousObjects.objectGraphTest.TestObjectGraphAfterGC FULL_GC_MEMORY_PRESSURE
  77  *
  78  * @run main/othervm -Xms200M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
  79  * -XX:G1HeapRegionSize=1M -Xlog:gc=info:file=TestObjectGraphAfterGC_CMC.gc.log -XX:MaxTenuringThreshold=16
  80  * gc.g1.humongousObjects.objectGraphTest.TestObjectGraphAfterGC CMC
  81  *
  82  * @run main/othervm -Xms200M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
  83  * -XX:G1HeapRegionSize=1M -Xlog:gc=info:file=TestObjectGraphAfterGC_CMC_NO_SURV_ROOTS.gc.log -XX:MaxTenuringThreshold=1
  84  * gc.g1.humongousObjects.objectGraphTest.TestObjectGraphAfterGC CMC_NO_SURV_ROOTS
  85  *
  86  */
  87 
  88 /**
  89  * Checks that objects' graph behave as expected after gc
  90  * See README file for detailed info on test's logic
  91  */
  92 public class TestObjectGraphAfterGC {
  93 
  94     private static final int simpleAllocationSize = 1024;
  95 
  96     /**
  97      * Entry point
  98      *
  99      * @param args - first argument - gc name
 100      */
 101     public static void main(String[] args) {
 102 
 103         if (args.length < 1) {
 104             throw new Error("Expected gc name wasn't provided as command line argument");
 105         }
 106 
 107         GC gcType = GC.valueOf(args[0].toUpperCase());
 108 
 109         System.out.println("Testing " + gcType.name());
 110 
 111         TestcaseData.getPregeneratedTestcases().stream().forEach(testcase -> {
 112             System.out.println("Testcase: " + testcase);
 113 
 114             try {
 115                 TestObjectGraphAfterGC.doTesting(testcase, gcType.get(), gcType.getChecker(),
 116                         gcType.getGcLogName(TestObjectGraphAfterGC.class.getSimpleName()), gcType.shouldContain(),
 117                         gcType.shouldNotContain());
 118             } catch (IOException e) {
 119                 throw new Error("Problems trying to find or open " + TestObjectGraphAfterGC.class.getSimpleName()
 120                         + ".gc.log", e);
 121             }
 122             System.out.println(" Passed");
 123         });
 124     }
 125 
 126     /**
 127      * Implements testing with 3 methods - allocateObjectGraph, checkResults and checkGCLog
 128      *
 129      * @param testcaseData     testcase in the following notation:
 130      *                         H - humongous node
 131      *                         S - non-humongous node
 132      *                         s - external soft reference
 133      *                         w - external weak reference
 134      *                         Hs->Sw - 1st node is humongous, externally soft referenced and strong references to
 135      *                         non-humongous node 2 which is externally weak referenced
 136      *                         H->1 - humongous node connects to the first node of chain
 137      * @param doGC             method that initiates gc
 138      * @param checker          consumer that checks node's state after gc and throws Error if it's wrong
 139      * @param gcLogName        name of gc log
 140      * @param shouldContain    list of tokens that should be contained in gc log
 141      * @param shouldNotContain list of tokens that should not be contained in gc log
 142      * @throws IOException if there are some issues with gc log
 143      */
 144     private static void doTesting(String testcaseData, Runnable doGC, Consumer<ReferenceInfo<Object[]>> checker,
 145                                   String gcLogName, List<String> shouldContain, List<String> shouldNotContain)
 146             throws IOException {
 147         Set<ReferenceInfo<Object[]>> nodeData = allocateObjectGraph(testcaseData);
 148         doGC.run();
 149         checkResults(nodeData, checker);
 150         checkGCLog(gcLogName, shouldContain, shouldNotContain);
 151     }
 152 
 153     /**
 154      * Allocates a number of objects of humongous and regular size and links then with strong references.
 155      * How many objects to create, their size and links between them is encoded in the given parameters.
 156      * As the result an object graph will be created.
 157      * For the testing purpose for each created object (a graph node) an extra ReferenceInfo object will be created.
 158      * The ReferenceInfo instances will contain either weak or soft reference to the graph node.
 159      *
 160      * @param testcaseData testcase in the
 161      *                     <p>
 162      *                     H - humongous node
 163      *                     S - non-humongous node
 164      *                     s - external soft reference
 165      *                     w - external weak reference
 166      *                     Hs->Sw - 1st node is humongous, externally soft referenced and strong references to
 167      *                     non-humongous node 2 which is externally weak referenced
 168      *                     H->1 - humongous node connects to the first node of chain
 169      * @return set of ReferenceInfo objects containing weak/soft reference to the graph node and other data on how
 170      * objects should behave after gc
 171      */
 172     private static Set<ReferenceInfo<Object[]>> allocateObjectGraph(String testcaseData) {
 173         Map<Object[], String> nodeIds = new HashMap<>();
 174         Set<Object[]> humongousNodes = new HashSet<>();
 175         Set<Object[]> externalSoftReferenced = new HashSet<>();
 176         Set<Object[]> externalWeakReferenced = new HashSet<>();
 177 
 178         Map<Predicate<TestcaseData.FinalParsedNode>, BiConsumer<TestcaseData.FinalParsedNode, Object[][]>> visitors
 179                 = new HashMap<>();
 180 
 181         visitors.put((parsedNode -> true),
 182                 (parsedNode, objects) -> nodeIds.put(objects[Integer.valueOf(parsedNode.id)], parsedNode.id)
 183         );
 184 
 185         visitors.put((parsedNode -> parsedNode.isHumongous),
 186                 (parsedNode, objects) -> humongousNodes.add(objects[Integer.valueOf(parsedNode.id)])
 187         );
 188 
 189         visitors.put(parsedNode -> parsedNode.getReferencesTypes().stream().
 190                         anyMatch(referenceType -> referenceType == ObjectGraph.ReferenceType.SOFT),
 191                 (parsedNode, objects) -> externalSoftReferenced.add(objects[Integer.valueOf(parsedNode.id)])
 192         );
 193 
 194         visitors.put(parsedNode -> parsedNode.getReferencesTypes().stream().
 195                         anyMatch(referenceType -> referenceType == ObjectGraph.ReferenceType.WEAK),
 196                 (parsedNode, objects) -> externalWeakReferenced.add(objects[Integer.valueOf(parsedNode.id)])
 197         );
 198 
 199         List<TestcaseData.FinalParsedNode> internalParsedNodes = TestcaseData.parse(testcaseData);
 200 
 201         Object[] root = ObjectGraph.generateObjectNodes(internalParsedNodes, visitors,
 202                 WhiteBox.getWhiteBox().g1RegionSize(), simpleAllocationSize);
 203 
 204         ObjectGraph.propagateTransitiveProperty(humongousNodes, humongousNodes::add);
 205         Set<Object[]> effectiveSoftReferenced = new HashSet<>();
 206         ObjectGraph.propagateTransitiveProperty(externalSoftReferenced, effectiveSoftReferenced::add);
 207 
 208         // Create external references
 209         ReferenceQueue<Object[]> referenceQueue = new ReferenceQueue<>();
 210         Set<Reference<Object[]>> externalRefs = new HashSet<>();
 211 
 212         externalWeakReferenced.stream()
 213                 .forEach(objects -> externalRefs.add(new WeakReference<>(objects, referenceQueue)));
 214         externalSoftReferenced.stream()
 215                 .forEach(objects -> externalRefs.add(new SoftReference<>(objects, referenceQueue)));
 216 
 217         return externalRefs.stream()
 218                 .map(ref -> new ReferenceInfo<>(ref, testcaseData, nodeIds.get(ref.get()),
 219                         effectiveSoftReferenced.contains(ref.get()), humongousNodes.contains(ref.get())))
 220                 .collect(Collectors.toSet());
 221 
 222     }
 223 
 224     /**
 225      * Checks that object' state after gc is as expected
 226      *
 227      * @param nodeData array with information about nodes
 228      * @param checker  consumer that checks node's state after gc and throws Error if it's wrong
 229      */
 230     private static void checkResults(Set<ReferenceInfo<Object[]>> nodeData, Consumer<ReferenceInfo<Object[]>> checker) {
 231         nodeData.stream().forEach(checker::accept);
 232     }
 233 
 234     /**
 235      * Checks that gc log contains what we expected and does not contain what we didn't expect
 236      *
 237      * @param gcLogName        gc log name
 238      * @param shouldContain    list of tokens that should be contained in gc log
 239      * @param shouldNotContain list of tokens that should not be contained in gc log
 240      * @throws IOException if there are some issues with gc log
 241      */
 242     private static void checkGCLog(String gcLogName, List<String> shouldContain, List<String> shouldNotContain)
 243             throws IOException {
 244 
 245         if (gcLogName == null) {
 246             return;
 247         }
 248         String gcLog = new String(Files.readAllBytes(new File(gcLogName).toPath()));
 249 
 250         OutputAnalyzer outputAnalyzer = new OutputAnalyzer(gcLog, "");
 251 
 252         shouldContain.stream().forEach(outputAnalyzer::shouldContain);
 253         shouldNotContain.stream().forEach(outputAnalyzer::shouldNotContain);
 254     }
 255 
 256 }