1 /*
   2  * Copyright (c) 2014, 2017, 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 import jdk.testlibrary.TimeLimitedRunner;
  25 import jdk.testlibrary.Utils;
  26 import test.java.lang.invoke.lib.CodeCacheOverflowProcessor;
  27 import test.java.lang.invoke.lib.Helper;
  28 
  29 import java.lang.invoke.MethodHandle;
  30 import java.lang.management.GarbageCollectorMXBean;
  31 import java.lang.management.ManagementFactory;
  32 import java.lang.ref.Reference;
  33 import java.lang.reflect.Field;
  34 import java.lang.reflect.Method;
  35 import java.util.Collection;
  36 import java.util.List;
  37 import java.util.function.Function;
  38 
  39 /**
  40  * Lambda forms caching test case class. Contains all necessary test routines to
  41  * test lambda forms caching in method handles returned by methods of
  42  * MethodHandles class.
  43  *
  44  * @author kshefov
  45  */
  46 public abstract class LambdaFormTestCase {
  47 
  48     private static final long TIMEOUT = Helper.IS_THOROUGH ? 0L : (long) (Utils.adjustTimeout(Utils.DEFAULT_TEST_TIMEOUT) * 0.9);
  49 
  50     /**
  51      * Reflection link to {@code j.l.i.MethodHandle.internalForm} method. It is
  52      * used to get a lambda form from a method handle.
  53      */
  54     protected static final Method INTERNAL_FORM;
  55     protected static final Field KIND_FIELD;
  56     protected static final Field REF_FIELD;
  57     private static final List<GarbageCollectorMXBean> gcInfo;
  58 
  59     private static long gcCount() {
  60         return gcInfo.stream().mapToLong(GarbageCollectorMXBean::getCollectionCount).sum();
  61     }
  62 
  63     static {
  64         try {
  65             INTERNAL_FORM = MethodHandle.class.getDeclaredMethod("internalForm");
  66             INTERNAL_FORM.setAccessible(true);
  67 
  68             KIND_FIELD = Class.forName("java.lang.invoke.LambdaForm").getDeclaredField("kind");
  69             KIND_FIELD.setAccessible(true);
  70 
  71             REF_FIELD = Reference.class.getDeclaredField("referent");
  72             REF_FIELD.setAccessible(true);
  73         } catch (Exception ex) {
  74             throw new Error("Unexpected exception", ex);
  75         }
  76 
  77         gcInfo = ManagementFactory.getGarbageCollectorMXBeans();
  78         if (gcInfo.size() == 0) {
  79             throw new Error("No GarbageCollectorMXBeans found.");
  80         }
  81     }
  82 
  83     private final TestMethods testMethod;
  84     private long gcCountAtStart;
  85 
  86     private static class TestRun {
  87 
  88         final Function<TestMethods, LambdaFormTestCase> ctor;
  89         final Collection<TestMethods> testMethods;
  90         final long totalIterations;
  91         long doneIterations;
  92         long testCounter;
  93         long failCounter;
  94         boolean passed;
  95 
  96         TestRun(Function<TestMethods, LambdaFormTestCase> ctor, Collection<TestMethods> testMethods) {
  97             this.ctor = ctor;
  98             this.testMethods = testMethods;
  99             long testCaseNum = testMethods.size();
 100             long iterations = Math.max(1, Helper.TEST_LIMIT / testCaseNum);
 101             System.out.printf("Number of iterations according to -DtestLimit is %d (%d cases)%n",
 102                     iterations, iterations * testCaseNum);
 103             System.out.printf("Number of iterations is set to %d (%d cases)%n",
 104                     iterations, iterations * testCaseNum);
 105             System.out.flush();
 106             totalIterations = iterations;
 107             doneIterations = 0L;
 108             testCounter = 0L;
 109             failCounter = 0L;
 110             passed = true;
 111         }
 112 
 113         Boolean doIteration() {
 114             if (doneIterations >= totalIterations) {
 115                 return false;
 116             }
 117             System.err.println(String.format("Iteration %d:", doneIterations));
 118             for (TestMethods testMethod : testMethods) {
 119                 LambdaFormTestCase testCase = ctor.apply(testMethod);
 120                 try {
 121                     System.err.printf("Tested LF caching feature"
 122                             + " with MethodHandles.%s method.%n",
 123                             testCase.getTestMethod().name);
 124                     Throwable t = CodeCacheOverflowProcessor
 125                             .runMHTest(testCase::doTest);
 126                     if (t != null) {
 127                         return false;
 128                     }
 129                     System.err.println("PASSED");
 130                 } catch (OutOfMemoryError oome) {
 131                     // Don't swallow OOME so a heap dump can be created.
 132                     System.err.println("FAILED");
 133                     throw oome;
 134                 } catch (Throwable t) {
 135                     t.printStackTrace();
 136                     System.err.printf("FAILED. Caused by %s%n", t.getMessage());
 137                     passed = false;
 138                     failCounter++;
 139                 }
 140                 testCounter++;
 141             }
 142             doneIterations++;
 143             return true;
 144         }
 145     }
 146 
 147     /**
 148      * Test case constructor. Generates test cases with random method types for
 149      * given methods form {@code j.l.i.MethodHandles} class.
 150      *
 151      * @param testMethod A method from {@code j.l.i.MethodHandles} class which
 152      * returns a {@code j.l.i.MethodHandle}.
 153      */
 154     protected LambdaFormTestCase(TestMethods testMethod) {
 155         this.testMethod = testMethod;
 156         this.gcCountAtStart = gcCount();
 157     }
 158 
 159     public TestMethods getTestMethod() {
 160         return testMethod;
 161     }
 162 
 163     protected boolean noGCHappened() {
 164         return gcCount() == gcCountAtStart;
 165     }
 166 
 167     /**
 168      * Routine that executes a test case.
 169      */
 170     public abstract void doTest();
 171 
 172     /**
 173      * Runs a number of test cases defined by the size of testCases list.
 174      *
 175      * @param ctor constructor of LambdaFormCachingTest or its child classes
 176      * object.
 177      * @param testMethods list of test methods
 178      */
 179     public static void runTests(Function<TestMethods, LambdaFormTestCase> ctor, Collection<TestMethods> testMethods) {
 180         LambdaFormTestCase.TestRun run
 181                 = new LambdaFormTestCase.TestRun(ctor, testMethods);
 182         TimeLimitedRunner runner = new TimeLimitedRunner(TIMEOUT, 4.0d, run::doIteration);
 183         try {
 184             runner.call();
 185         } catch (Exception ex) {
 186             System.err.println("FAILED");
 187             throw new Error("Unexpected error!", ex);
 188         }
 189         if (!run.passed) {
 190             throw new Error(String.format("%d of %d test cases FAILED! %n"
 191                     + "Rerun the test with the same \"-Dseed=\" option as in the log file!",
 192                     run.failCounter, run.testCounter));
 193         } else {
 194             System.err.printf("All %d test cases PASSED!%n", run.testCounter);
 195         }
 196     }
 197 }