1/*
2 * Copyright (c) 2014, 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/*
25 * @test MethodUnloadingTest
26 * @bug 8029443
27 * @summary Tests the unloading of methods to to class unloading
28 * @modules java.base/jdk.internal.misc
29 * @library /test/lib /
30 *
31 * @build sun.hotspot.WhiteBox
32 *        compiler.classUnloading.methodUnloading.WorkerClass
33 * @run driver ClassFileInstaller sun.hotspot.WhiteBox
34 *                              sun.hotspot.WhiteBox$WhiteBoxPermission
35 * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions
36 *                   -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
37 *                   -XX:-BackgroundCompilation -XX:-UseCompressedOops
38 *                   -XX:CompileCommand=compileonly,compiler.classUnloading.methodUnloading.TestMethodUnloading::doWork
39 *                   compiler.classUnloading.methodUnloading.TestMethodUnloading
40 */
41
42package compiler.classUnloading.methodUnloading;
43
44import sun.hotspot.WhiteBox;
45
46import java.lang.reflect.Method;
47import java.net.URL;
48import java.net.URLClassLoader;
49import compiler.whitebox.CompilerWhiteBoxTest;
50
51public class TestMethodUnloading {
52    private static final String workerClassName = "compiler.classUnloading.methodUnloading.WorkerClass";
53    private static int work = -1;
54
55    private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
56
57    /**
58     * Does some work by either using the workerClass or locally producing values.
59     * @param workerClass Class performing some work (will be unloaded)
60     * @param useWorker If true the workerClass is used
61     */
62    static private void doWork(Class<?> workerClass, boolean useWorker) throws InstantiationException, IllegalAccessException {
63        if (useWorker) {
64            // Create a new instance
65            Object worker = workerClass.newInstance();
66            // We would like to call a method of WorkerClass here but we cannot cast to WorkerClass
67            // because the class was loaded by a different class loader. One solution would be to use
68            // reflection but since we want C2 to implement the call as an optimized IC we call
69            // Object::hashCode() here which actually calls WorkerClass::hashCode().
70            // C2 will then implement this call as an optimized IC that points to a to-interpreter stub
71            // referencing the Method* for WorkerClass::hashCode().
72            work = worker.hashCode();
73            if (work != 42) {
74                new RuntimeException("Work not done");
75            }
76        } else {
77            // Do some important work here
78            work = 1;
79        }
80    }
81
82    /**
83     * Makes sure that method is compiled by forcing compilation if not yet compiled.
84     * @param m Method to be checked
85     */
86    static private void makeSureIsCompiled(Method m) {
87        // Make sure background compilation is disabled
88        if (WHITE_BOX.getBooleanVMFlag("BackgroundCompilation")) {
89            throw new RuntimeException("Background compilation enabled");
90        }
91
92        // Check if already compiled
93        if (!WHITE_BOX.isMethodCompiled(m)) {
94            // If not, try to compile it with C2
95            if(!WHITE_BOX.enqueueMethodForCompilation(m, CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION)) {
96                // C2 compiler not available, try to compile with C1
97                WHITE_BOX.enqueueMethodForCompilation(m, CompilerWhiteBoxTest.COMP_LEVEL_SIMPLE);
98            }
99            // Because background compilation is disabled, method should now be compiled
100            if(!WHITE_BOX.isMethodCompiled(m)) {
101                throw new RuntimeException(m + " not compiled");
102            }
103        }
104    }
105
106    /**
107     * This test creates stale Method* metadata in a to-interpreter stub of an optimized IC.
108     *
109     * The following steps are performed:
110     * (1) A workerClass is loaded by a custom class loader
111     * (2) The method doWork that calls a method of the workerClass is compiled. The call
112     *     is implemented as an optimized IC calling a to-interpreted stub. The to-interpreter
113     *     stub contains a Method* to a workerClass method.
114     * (3) Unloading of the workerClass is enforced. The to-interpreter stub now contains a dead Method*.
115     * (4) Depending on the implementation of the IC, the compiled version of doWork should still be
116     *     valid. We call it again without using the workerClass.
117     */
118    static public void main(String[] args) throws Exception {
119        // (1) Create a custom class loader with no parent class loader
120        URL url = TestMethodUnloading.class.getProtectionDomain().getCodeSource().getLocation();
121        URLClassLoader loader = new URLClassLoader(new URL[] {url}, null);
122
123        // Load worker class with custom class loader
124        Class<?> workerClass = Class.forName(workerClassName, true, loader);
125
126        // (2) Make sure all paths of doWork are profiled and compiled
127        for (int i = 0; i < 100000; ++i) {
128            doWork(workerClass, true);
129            doWork(workerClass, false);
130        }
131
132        // Make sure doWork is compiled now
133        Method doWork = TestMethodUnloading.class.getDeclaredMethod("doWork", Class.class, boolean.class);
134        makeSureIsCompiled(doWork);
135
136        // (3) Throw away class loader and reference to workerClass to allow unloading
137        loader.close();
138        loader = null;
139        workerClass = null;
140
141        // Force garbage collection to trigger unloading of workerClass
142        // Dead reference to WorkerClass::hashCode triggers JDK-8029443
143        WHITE_BOX.fullGC();
144
145        // (4) Depending on the implementation of the IC, the compiled version of doWork
146        // may still be valid here. Execute it without a workerClass.
147        doWork(null, false);
148        if (work != 1) {
149            throw new RuntimeException("Work not done");
150        }
151
152        doWork(Object.class, false);
153    }
154}
155