1 /*
  2  * Copyright (c) 2016, 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 package gc.g1.humongousObjects;
 25 
 26 import gc.testlibrary.Helpers;
 27 import jdk.test.lib.Asserts;
 28 import sun.hotspot.WhiteBox;
 29 
 30 import java.io.IOException;
 31 import java.lang.reflect.InvocationTargetException;
 32 import java.net.URL;
 33 import java.net.URLClassLoader;
 34 import java.nio.file.Path;
 35 import java.nio.file.Paths;
 36 
 37 /**
 38  * @test gc.g1.humongousObjects.TestHumongousClassLoader
 39  * @summary Checks that unreachable classes and unreachable humongous class loader are unloaded after GC
 40  * @requires vm.gc.G1
 41  * @requires vm.opt.G1HeapRegionSize == "null" | vm.opt.G1HeapRegionSize == "1M"
 42  * @requires vm.opt.ExplicitGCInvokesConcurrent != true
 43  * @requires vm.opt.ClassUnloading  != false
 44  * @requires vm.opt.ClassUnloadingWithConcurrentMark  != false
 45  * @library /test/lib /
 46  * @modules java.base/jdk.internal.misc
 47  * @modules java.management
 48  * @build sun.hotspot.WhiteBox
 49  * @run driver ClassFileInstaller sun.hotspot.WhiteBox
 50  *                                sun.hotspot.WhiteBox$WhiteBoxPermission
 51  *
 52  * @run main/othervm/timeout=240  -Xms256M -Xmx256M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
 53  *                                gc.g1.humongousObjects.ClassLoaderGenerator 1
 54  *
 55  * @run main/othervm -Xms256M -Xmx256M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
 56  *                   -Xlog:class+load,class+unload=debug:file=TestHumongousClassLoader_Full_GC.log
 57  *                   -XX:G1HeapRegionSize=1M
 58  *                   gc.g1.humongousObjects.TestHumongousClassLoader FULL_GC
 59  *
 60  * @run main/othervm -Xms256M -Xmx256M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
 61  *                   -Xlog:class+load,class+unload=debug:file=TestHumongousClassLoader_Full_GC_Mem_Pressure.log
 62  *                   -XX:G1HeapRegionSize=1M
 63  *                   gc.g1.humongousObjects.TestHumongousClassLoader FULL_GC_MEMORY_PRESSURE
 64  *
 65  *@run main/othervm -Xms256M -Xmx256M -XX:+UseG1GC -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.
 66  *                   -Xlog:class+load,class+unload=debug:file=TestHumongousClassLoader_CMC.log
 67  *                   -XX:G1HeapRegionSize=1M -XX:MaxTenuringThreshold=1
 68  *                   gc.g1.humongousObjects.TestHumongousClassLoader CMC
 69  *
 70  */
 71 
 72 public class TestHumongousClassLoader {
 73 
 74     private static final WhiteBox WB = WhiteBox.getWhiteBox();
 75     private static final String SAMPLE_CLASS_NAME_PREFIX = "SampleClassFiller";
 76     public static final String SIMPLE_CLASSLOADER_NAME = "SimpleClassLoader";
 77     public static final String HUMONGOUS_CLASSLOADER_NAME = "HumongousClassLoader";
 78 
 79 
 80     public static final String LOAD_CLASS_METHOD_PROTOTYPE =
 81             "    @Override\n"
 82                     + "    public Class loadClass(String fileName) throws ClassNotFoundException {\n"
 83                     + "        if (${ClassLoadFilter}) {\n"
 84                     + "            System.out.println(\"Loading class \" + fileName);\n"
 85                     + "            byte[] b = null;\n"
 86                     + "            try {\n"
 87                     + "                b = Files.readAllBytes(new File(fileName + \".class\").toPath());\n"
 88                     + "            } catch (IOException e) {\n"
 89                     + "                e.printStackTrace();\n"
 90                     + "            }\n"
 91                     + "            Class c = defineClass(fileName, b, 0, b.length);\n"
 92                     + "            resolveClass(c);\n"
 93                     + "            return c;\n"
 94                     + "        } else {\n"
 95                     + "            return super.loadClass(fileName);\n"
 96                     + "        }\n"
 97                     + "\n"
 98                     + "\n"
 99                     + "    }\n";
100 
101     public static final String CLASS_HEADER = "import java.io.File;\n"
102             + "import java.io.IOException;\n"
103             + "import java.nio.file.Files;\n"
104             + "import java.nio.file.Paths;\n";
105 
106     public static final String GENERIC_PROTOTYPE = "${ClassHeader}\n"
107             + "public class ${ClassName} extends ${BaseClass}{\n"
108             + "    ${ConstructorClause}\n"
109             + "    ${Methods}\n"
110             + "    ${Fields}\n"
111             + "}\n";
112 
113     public static final String CONSTUCTOR_PROTOTYPE = "public ${ClassName}(ClassLoader parent) { super(parent);}\n";
114 
115     private enum GC {
116         FULL_GC {
117             @Override
118             public void provoke() {
119                 System.gc();
120             }
121         },
122         CMC {
123             @Override
124             public void provoke() {
125                 // We need 2 young gc to promote class loader to old gen
126                 // Otherwise it will not be unloaded after CMC
127                 WHITE_BOX.youngGC();
128                 Helpers.waitTillCMCFinished(WHITE_BOX, 0);
129                 WHITE_BOX.youngGC();
130                 Helpers.waitTillCMCFinished(WHITE_BOX, 0);
131                 WHITE_BOX.g1StartConcMarkCycle();
132                 Helpers.waitTillCMCFinished(WHITE_BOX, 0);
133             }
134         },
135         FULL_GC_MEMORY_PRESSURE {
136             @Override
137             public void provoke() {
138                 WHITE_BOX.fullGC();
139             }
140         };
141         private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
142 
143         public abstract void provoke();
144     }
145 
146     public static void main(String[] args) throws ClassNotFoundException, InstantiationException,
147             IllegalAccessException, IOException, NoSuchMethodException, InvocationTargetException {
148 
149         if (args.length != 1) {
150             throw new Error("Test Bug: Expected GC type wasn't provided as command line argument");
151         }
152         GC gc = GC.valueOf(args[0]);
153 
154         Path wrkDir = Paths.get("");
155         URL[] url = {wrkDir.toUri().toURL()};
156         URLClassLoader urlLoader = new URLClassLoader(url);
157 
158         Class<?> simpleClassLoaderClass = urlLoader.loadClass(SIMPLE_CLASSLOADER_NAME);
159 
160         ClassLoader simpleClassLoader = (ClassLoader) simpleClassLoaderClass
161                 .getConstructor(java.lang.ClassLoader.class)
162                 .newInstance(TestHumongousClassLoader.class.getClassLoader());
163 
164         // Sanity check
165         Asserts.assertEquals(WB.g1IsHumongous(simpleClassLoader), false,
166                 "Test Bug: simpleClassLoader is expected to be non-humongous but it's humongous");
167 
168 
169         Class<?> humongousClassLoaderClass = simpleClassLoader.loadClass(HUMONGOUS_CLASSLOADER_NAME);
170 
171         ClassLoader humongousClassLoader = (ClassLoader) humongousClassLoaderClass
172                 .getConstructor(java.lang.ClassLoader.class)
173                 .newInstance(simpleClassLoader);
174 
175         // Sanity check
176         Asserts.assertEquals(WB.g1IsHumongous(humongousClassLoader), true,
177                 "Test Bug: humongousClassLoader is expected to be humongous but it's non-humongous");
178 
179         //Asserts.assertEquals(1,0);
180 
181         Object[] loadedClasses = new Object[]{
182                 G1SampleClass.LARGEST_NON_HUMONGOUS.getCls(humongousClassLoader, wrkDir, SAMPLE_CLASS_NAME_PREFIX)
183                         .newInstance(),
184                 G1SampleClass.SMALLEST_HUMONGOUS.getCls(humongousClassLoader, wrkDir, SAMPLE_CLASS_NAME_PREFIX)
185                         .newInstance(),
186                 G1SampleClass.ONE_REGION_HUMONGOUS.getCls(humongousClassLoader, wrkDir, SAMPLE_CLASS_NAME_PREFIX)
187                         .newInstance(),
188                 G1SampleClass.TWO_REGION_HUMONGOUS.getCls(humongousClassLoader, wrkDir, SAMPLE_CLASS_NAME_PREFIX)
189                         .newInstance(),
190         };
191 
192         // forgetting references to loaded classes
193         for (int i = 0; i < loadedClasses.length; ++i) {
194             loadedClasses[i] = null;
195         }
196 
197         // forgetting referencies to classloaders
198         humongousClassLoader = null;
199         humongousClassLoaderClass = null;
200 
201         simpleClassLoader = null;
202         simpleClassLoaderClass = null;
203 
204         gc.provoke();
205 
206         // Test checks
207         Asserts.assertEquals(WB.isClassAlive(HUMONGOUS_CLASSLOADER_NAME), false,
208                 String.format("Classloader class %s is loaded after we forget all references to it",
209                         HUMONGOUS_CLASSLOADER_NAME));
210 
211         for (G1SampleClass sampleClass : G1SampleClass.values()) {
212             String className = Helpers.enumNameToClassName(sampleClass.name()) + "Class";
213             Asserts.assertEquals(WB.isClassAlive(className), false,
214                     String.format("Class %s is loaded after we forget all references to it", className));
215         }
216     }
217 
218 }