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