< prev index next >

test/hotspot/jtreg/runtime/Metaspace/DefineClass.java

Print this page




  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /**
  26  * @test
  27  * @bug 8173743
  28  * @requires vm.compMode != "Xcomp"
  29  * @summary Failures during class definition can lead to memory leaks in metaspace
  30  * @requires vm.opt.final.ClassUnloading
  31  * @library /test/lib
  32  * @run main/othervm test.DefineClass defineClass
  33  * @run main/othervm test.DefineClass defineSystemClass
  34  * @run main/othervm -XX:+AllowParallelDefineClass
  35                      test.DefineClass defineClassParallel
  36  * @run main/othervm -XX:-AllowParallelDefineClass
  37                      test.DefineClass defineClassParallel
  38  * @run main/othervm -Djdk.attach.allowAttachSelf test.DefineClass redefineClass
  39  * @run main/othervm -Djdk.attach.allowAttachSelf test.DefineClass redefineClassWithError







  40  * @author volker.simonis@gmail.com
  41  */
  42 
  43 package test;
  44 
  45 import java.io.ByteArrayOutputStream;
  46 import java.io.File;
  47 import java.io.FileOutputStream;
  48 import java.io.InputStream;
  49 import java.lang.instrument.ClassDefinition;
  50 import java.lang.instrument.Instrumentation;
  51 import java.lang.management.ManagementFactory;
  52 import java.util.Scanner;
  53 import java.util.concurrent.CountDownLatch;
  54 import java.util.jar.Attributes;
  55 import java.util.jar.JarEntry;
  56 import java.util.jar.JarOutputStream;
  57 import java.util.jar.Manifest;
  58 
  59 import javax.management.MBeanServer;
  60 import javax.management.ObjectName;
  61 
  62 import com.sun.tools.attach.VirtualMachine;
  63 
  64 import jdk.test.lib.process.ProcessTools;

  65 
  66 public class DefineClass {
  67 
  68     private static Instrumentation instrumentation;
  69 
  70     public void getID(CountDownLatch start, CountDownLatch stop) {
  71         String id = "AAAAAAAA";
  72         System.out.println(id);
  73         try {
  74             // Signal that we've entered the activation..
  75             start.countDown();
  76             //..and wait until we can leave it.
  77             stop.await();
  78         } catch (InterruptedException e) {
  79             e.printStackTrace();
  80         }
  81         System.out.println(id);
  82         return;
  83     }
  84 


 188         return getStringIndex(needle, buf, 0);
 189     }
 190 
 191     private static int getStringIndex(String needle, byte[] buf, int offset) {
 192         outer:
 193         for (int i = offset; i < buf.length - offset - needle.length(); i++) {
 194             for (int j = 0; j < needle.length(); j++) {
 195                 if (buf[i + j] != (byte)needle.charAt(j)) continue outer;
 196             }
 197             return i;
 198         }
 199         return 0;
 200     }
 201 
 202     private static void replaceString(byte[] buf, String name, int index) {
 203         for (int i = index; i < index + name.length(); i++) {
 204             buf[i] = (byte)name.charAt(i - index);
 205         }
 206     }
 207 
 208     private static MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();
 209 
 210     private static int getClassStats(String pattern) {
 211         try {
 212             ObjectName diagCmd = new ObjectName("com.sun.management:type=DiagnosticCommand");
 213 
 214             String result = (String)mbserver.invoke(diagCmd , "gcClassStats" , new Object[] { null }, new String[] {String[].class.getName()});
 215             int count = 0;
 216             try (Scanner s = new Scanner(result)) {
 217                 if (s.hasNextLine()) {
 218                     System.out.println(s.nextLine());
 219                 }
 220                 while (s.hasNextLine()) {
 221                     String l = s.nextLine();
 222                     if (l.endsWith(pattern)) {
 223                         count++;
 224                         System.out.println(l);
 225                     }
 226                 }
 227             }
 228             return count;
 229         }
 230         catch (Exception e) {
 231             throw new RuntimeException("Test failed because we can't read the class statistics!", e);
 232         }
 233     }
 234 
 235     private static void printClassStats(int expectedCount, boolean reportError) {
 236         int count = getClassStats("DefineClass");
 237         String res = "Should have " + expectedCount +
 238                      " DefineClass instances and we have: " + count;
 239         System.out.println(res);
 240         if (reportError && count != expectedCount) {
 241             throw new RuntimeException(res);
 242         }
 243     }
 244 
 245     public static final int ITERATIONS = 10;
 246 















 247     public static void main(String[] args) throws Exception {
 248         String myName = DefineClass.class.getName();
 249         byte[] buf = getBytecodes(myName.substring(myName.lastIndexOf(".") + 1));
 250         int iterations = (args.length > 1 ? Integer.parseInt(args[1]) : ITERATIONS);
 251 
 252         if (args.length == 0 || "defineClass".equals(args[0])) {
 253             MyClassLoader cl = new MyClassLoader();
 254             for (int i = 0; i < iterations; i++) {
 255                 try {
 256                     @SuppressWarnings("unchecked")
 257                     Class<DefineClass> dc = (Class<DefineClass>) cl.myDefineClass(myName, buf, 0, buf.length);
 258                     System.out.println(dc);
 259                 }
 260                 catch (LinkageError jle) {
 261                     // Can only define once!
 262                     if (i == 0) throw new Exception("Should succeed the first time.");
 263                 }
 264             }
 265             // We expect to have two instances of DefineClass here: the initial version in which we are
 266             // executing and another version which was loaded into our own classloader 'MyClassLoader'.
 267             // All the subsequent attempts to reload DefineClass into our 'MyClassLoader' should have failed.
 268             printClassStats(2, false);
 269             System.gc();
 270             System.out.println("System.gc()");
 271             // At least after System.gc() the failed loading attempts should leave no instances around!
 272             printClassStats(2, true);
 273         }
 274         else if ("defineSystemClass".equals(args[0])) {
 275             MyClassLoader cl = new MyClassLoader();
 276             int index = getStringIndex("test/DefineClass", buf);
 277             replaceString(buf, "java/DefineClass", index);
 278             while ((index = getStringIndex("Ltest/DefineClass;", buf, index + 1)) != 0) {
 279                 replaceString(buf, "Ljava/DefineClass;", index);
 280             }
 281             index = getStringIndex("test.DefineClass", buf);
 282             replaceString(buf, "java.DefineClass", index);
 283 
 284             for (int i = 0; i < iterations; i++) {
 285                 try {
 286                     @SuppressWarnings("unchecked")
 287                     Class<DefineClass> dc = (Class<DefineClass>) cl.myDefineClass(null, buf, 0, buf.length);
 288                     throw new RuntimeException("Defining a class in the 'java' package should fail!");
 289                 }
 290                 catch (java.lang.SecurityException jlse) {
 291                     // Expected, because we're not allowed to define a class in the 'java' package
 292                 }
 293             }
 294             // We expect to stay with one (the initial) instances of DefineClass.
 295             // All the subsequent attempts to reload DefineClass into the 'java' package should have failed.
 296             printClassStats(1, false);
 297             System.gc();
 298             System.out.println("System.gc()");
 299             // At least after System.gc() the failed loading attempts should leave no instances around!
 300             printClassStats(1, true);
 301         }
 302         else if ("defineClassParallel".equals(args[0])) {
 303             MyParallelClassLoader pcl = new MyParallelClassLoader();
 304             CountDownLatch stop = new CountDownLatch(1);
 305 
 306             Thread[] threads = new Thread[iterations];
 307             for (int i = 0; i < iterations; i++) {
 308                 (threads[i] = new ParallelLoadingThread(pcl, buf, stop)).start();
 309             }
 310             stop.countDown(); // start parallel class loading..
 311             // ..and wait until all threads loaded the class
 312             for (int i = 0; i < iterations; i++) {
 313                 threads[i].join();
 314             }
 315             System.out.print("Counted " + pcl.getLinkageErrors() + " LinkageErrors ");
 316             System.out.println(pcl.getLinkageErrors() == 0 ?
 317                     "" : "(use -XX:+AllowParallelDefineClass to avoid this)");
 318             System.gc();
 319             System.out.println("System.gc()");
 320             // After System.gc() we expect to remain with two instances: one is the initial version which is
 321             // kept alive by this main method and another one in the parallel class loader.
 322             printClassStats(2, true);
 323         }
 324         else if ("redefineClass".equals(args[0])) {
 325             loadInstrumentationAgent(myName, buf);
 326             int index = getStringIndex("AAAAAAAA", buf);
 327             CountDownLatch stop = new CountDownLatch(1);
 328 
 329             Thread[] threads = new Thread[iterations];
 330             for (int i = 0; i < iterations; i++) {
 331                 buf[index] = (byte) ('A' + i + 1); // Change string constant in getID() which is legal in redefinition
 332                 instrumentation.redefineClasses(new ClassDefinition(DefineClass.class, buf));
 333                 DefineClass dc = DefineClass.class.newInstance();
 334                 CountDownLatch start = new CountDownLatch(1);
 335                 (threads[i] = new MyThread(dc, start, stop)).start();
 336                 start.await(); // Wait until the new thread entered the getID() method
 337             }
 338             // We expect to have one instance for each redefinition because they are all kept alive by an activation
 339             // plus the initial version which is kept active by this main method.
 340             printClassStats(iterations + 1, false);
 341             stop.countDown(); // Let all threads leave the DefineClass.getID() activation..
 342             // ..and wait until really all of them returned from DefineClass.getID()
 343             for (int i = 0; i < iterations; i++) {
 344                 threads[i].join();
 345             }
 346             System.gc();
 347             System.out.println("System.gc()");
 348             // After System.gc() we expect to remain with two instances: one is the initial version which is
 349             // kept alive by this main method and another one which is the latest redefined version.
 350             printClassStats(2, true);
 351         }
 352         else if ("redefineClassWithError".equals(args[0])) {
 353             loadInstrumentationAgent(myName, buf);
 354             int index = getStringIndex("getID", buf);
 355 
 356             for (int i = 0; i < iterations; i++) {
 357                 buf[index] = (byte) 'X'; // Change getID() to XetID() which is illegal in redefinition
 358                 try {
 359                     instrumentation.redefineClasses(new ClassDefinition(DefineClass.class, buf));
 360                     throw new RuntimeException("Class redefinition isn't allowed to change method names!");
 361                 }
 362                 catch (UnsupportedOperationException uoe) {
 363                     // Expected because redefinition can't change the name of methods
 364                 }
 365             }
 366             // We expect just a single DefineClass instance because failed redefinitions should
 367             // leave no garbage around.
 368             printClassStats(1, false);
 369             System.gc();
 370             System.out.println("System.gc()");
 371             // At least after a System.gc() we should definitely stay with a single instance!
 372             printClassStats(1, true);
 373         }
 374     }
 375 }


  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /**
  26  * @test
  27  * @bug 8173743
  28  * @requires vm.compMode != "Xcomp"
  29  * @summary Failures during class definition can lead to memory leaks in metaspace
  30  * @requires vm.opt.final.ClassUnloading
  31  * @library /test/lib
  32  * @build sun.hotspot.WhiteBox
  33  * @run main ClassFileInstaller sun.hotspot.WhiteBox
  34  *                              sun.hotspot.WhiteBox$WhiteBoxPermission
  35  * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI test.DefineClass defineClass
  36  * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI test.DefineClass defineSystemClass
  37  * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  38  *                   -XX:+AllowParallelDefineClass
  39  *                   test.DefineClass defineClassParallel
  40  * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  41  *                   -XX:-AllowParallelDefineClass
  42  *                   test.DefineClass defineClassParallel
  43  * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  44  *                   -Djdk.attach.allowAttachSelf test.DefineClass redefineClass
  45  * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  46  *                   -Djdk.attach.allowAttachSelf test.DefineClass redefineClassWithError
  47  * @author volker.simonis@gmail.com
  48  */
  49 
  50 package test;
  51 
  52 import java.io.ByteArrayOutputStream;
  53 import java.io.File;
  54 import java.io.FileOutputStream;
  55 import java.io.InputStream;
  56 import java.lang.instrument.ClassDefinition;
  57 import java.lang.instrument.Instrumentation;


  58 import java.util.concurrent.CountDownLatch;
  59 import java.util.jar.Attributes;
  60 import java.util.jar.JarEntry;
  61 import java.util.jar.JarOutputStream;
  62 import java.util.jar.Manifest;
  63 



  64 import com.sun.tools.attach.VirtualMachine;
  65 
  66 import jdk.test.lib.process.ProcessTools;
  67 import sun.hotspot.WhiteBox;
  68 
  69 public class DefineClass {
  70 
  71     private static Instrumentation instrumentation;
  72 
  73     public void getID(CountDownLatch start, CountDownLatch stop) {
  74         String id = "AAAAAAAA";
  75         System.out.println(id);
  76         try {
  77             // Signal that we've entered the activation..
  78             start.countDown();
  79             //..and wait until we can leave it.
  80             stop.await();
  81         } catch (InterruptedException e) {
  82             e.printStackTrace();
  83         }
  84         System.out.println(id);
  85         return;
  86     }
  87 


 191         return getStringIndex(needle, buf, 0);
 192     }
 193 
 194     private static int getStringIndex(String needle, byte[] buf, int offset) {
 195         outer:
 196         for (int i = offset; i < buf.length - offset - needle.length(); i++) {
 197             for (int j = 0; j < needle.length(); j++) {
 198                 if (buf[i + j] != (byte)needle.charAt(j)) continue outer;
 199             }
 200             return i;
 201         }
 202         return 0;
 203     }
 204 
 205     private static void replaceString(byte[] buf, String name, int index) {
 206         for (int i = index; i < index + name.length(); i++) {
 207             buf[i] = (byte)name.charAt(i - index);
 208         }
 209     }
 210 
 211     public static WhiteBox wb = WhiteBox.getWhiteBox();




 212 
 213     private static void checkClasses(int expectedCount, boolean reportError) {
 214         int count = wb.countAliveClasses("test.DefineClass");





















 215         String res = "Should have " + expectedCount +
 216                      " DefineClass instances and we have: " + count;
 217         System.out.println(res);
 218         if (reportError && count != expectedCount) {
 219             throw new RuntimeException(res);
 220         }
 221     }
 222 
 223     public static final int ITERATIONS = 10;
 224 
 225     private static void checkClassesAfterGC(int expectedCount) {
 226         // The first System.gc() doesn't clean metaspaces but triggers cleaning
 227         // for the next safepoint.
 228         // In the future the ServiceThread may clean metaspaces, but this loop
 229         // should give it enough time to run, when that is changed.
 230         // We might need to revisit this test though.
 231         for (int i = 0; i < ITERATIONS; i++) {
 232             System.gc();
 233             System.out.println("System.gc()");
 234             // Break if the GC has cleaned metaspace before iterations.
 235             if (wb.countAliveClasses("test.DefineClass") == expectedCount) break;
 236         }
 237         checkClasses(expectedCount, true);
 238     }
 239 
 240     public static void main(String[] args) throws Exception {
 241         String myName = DefineClass.class.getName();
 242         byte[] buf = getBytecodes(myName.substring(myName.lastIndexOf(".") + 1));
 243         int iterations = (args.length > 1 ? Integer.parseInt(args[1]) : ITERATIONS);
 244 
 245         if (args.length == 0 || "defineClass".equals(args[0])) {
 246             MyClassLoader cl = new MyClassLoader();
 247             for (int i = 0; i < iterations; i++) {
 248                 try {
 249                     @SuppressWarnings("unchecked")
 250                     Class<DefineClass> dc = (Class<DefineClass>) cl.myDefineClass(myName, buf, 0, buf.length);
 251                     System.out.println(dc);
 252                 }
 253                 catch (LinkageError jle) {
 254                     // Can only define once!
 255                     if (i == 0) throw new Exception("Should succeed the first time.");
 256                 }
 257             }
 258             // We expect to have two instances of DefineClass here: the initial version in which we are
 259             // executing and another version which was loaded into our own classloader 'MyClassLoader'.
 260             // All the subsequent attempts to reload DefineClass into our 'MyClassLoader' should have failed.
 261             // The ClassLoaderDataGraph has the failed instances recorded at least until the next GC.
 262             checkClasses(2, false);
 263             // At least after some System.gc() the failed loading attempts should leave no instances around!
 264             checkClassesAfterGC(2);

 265         }
 266         else if ("defineSystemClass".equals(args[0])) {
 267             MyClassLoader cl = new MyClassLoader();
 268             int index = getStringIndex("test/DefineClass", buf);
 269             replaceString(buf, "java/DefineClass", index);
 270             while ((index = getStringIndex("Ltest/DefineClass;", buf, index + 1)) != 0) {
 271                 replaceString(buf, "Ljava/DefineClass;", index);
 272             }
 273             index = getStringIndex("test.DefineClass", buf);
 274             replaceString(buf, "java.DefineClass", index);
 275 
 276             for (int i = 0; i < iterations; i++) {
 277                 try {
 278                     @SuppressWarnings("unchecked")
 279                     Class<DefineClass> dc = (Class<DefineClass>) cl.myDefineClass(null, buf, 0, buf.length);
 280                     throw new RuntimeException("Defining a class in the 'java' package should fail!");
 281                 }
 282                 catch (java.lang.SecurityException jlse) {
 283                     // Expected, because we're not allowed to define a class in the 'java' package
 284                 }
 285             }
 286             // We expect to stay with one (the initial) instances of DefineClass.
 287             // All the subsequent attempts to reload DefineClass into the 'java' package should have failed.
 288             // The ClassLoaderDataGraph has the failed instances recorded at least until the next GC.
 289             checkClasses(1, false);
 290             checkClassesAfterGC(1);


 291         }
 292         else if ("defineClassParallel".equals(args[0])) {
 293             MyParallelClassLoader pcl = new MyParallelClassLoader();
 294             CountDownLatch stop = new CountDownLatch(1);
 295 
 296             Thread[] threads = new Thread[iterations];
 297             for (int i = 0; i < iterations; i++) {
 298                 (threads[i] = new ParallelLoadingThread(pcl, buf, stop)).start();
 299             }
 300             stop.countDown(); // start parallel class loading..
 301             // ..and wait until all threads loaded the class
 302             for (int i = 0; i < iterations; i++) {
 303                 threads[i].join();
 304             }
 305             System.out.print("Counted " + pcl.getLinkageErrors() + " LinkageErrors ");
 306             System.out.println(pcl.getLinkageErrors() == 0 ?
 307                     "" : "(use -XX:+AllowParallelDefineClass to avoid this)");


 308             // After System.gc() we expect to remain with two instances: one is the initial version which is
 309             // kept alive by this main method and another one in the parallel class loader.
 310             checkClassesAfterGC(2);
 311         }
 312         else if ("redefineClass".equals(args[0])) {
 313             loadInstrumentationAgent(myName, buf);
 314             int index = getStringIndex("AAAAAAAA", buf);
 315             CountDownLatch stop = new CountDownLatch(1);
 316 
 317             Thread[] threads = new Thread[iterations];
 318             for (int i = 0; i < iterations; i++) {
 319                 buf[index] = (byte) ('A' + i + 1); // Change string constant in getID() which is legal in redefinition
 320                 instrumentation.redefineClasses(new ClassDefinition(DefineClass.class, buf));
 321                 DefineClass dc = DefineClass.class.newInstance();
 322                 CountDownLatch start = new CountDownLatch(1);
 323                 (threads[i] = new MyThread(dc, start, stop)).start();
 324                 start.await(); // Wait until the new thread entered the getID() method
 325             }
 326             // We expect to have one instance for each redefinition because they are all kept alive by an activation
 327             // plus the initial version which is kept active by this main method.
 328             checkClasses(iterations + 1, true);
 329             stop.countDown(); // Let all threads leave the DefineClass.getID() activation..
 330             // ..and wait until really all of them returned from DefineClass.getID()
 331             for (int i = 0; i < iterations; i++) {
 332                 threads[i].join();
 333             }


 334             // After System.gc() we expect to remain with two instances: one is the initial version which is
 335             // kept alive by this main method and another one which is the latest redefined version.
 336             checkClassesAfterGC(2);
 337         }
 338         else if ("redefineClassWithError".equals(args[0])) {
 339             loadInstrumentationAgent(myName, buf);
 340             int index = getStringIndex("getID", buf);
 341 
 342             for (int i = 0; i < iterations; i++) {
 343                 buf[index] = (byte) 'X'; // Change getID() to XetID() which is illegal in redefinition
 344                 try {
 345                     instrumentation.redefineClasses(new ClassDefinition(DefineClass.class, buf));
 346                     throw new RuntimeException("Class redefinition isn't allowed to change method names!");
 347                 }
 348                 catch (UnsupportedOperationException uoe) {
 349                     // Expected because redefinition can't change the name of methods
 350                 }
 351             }
 352             // We expect just a single DefineClass instance because failed redefinitions should
 353             // leave no garbage around.
 354             // The ClassLoaderDataGraph has the failed instances recorded at least until the next GC.
 355             checkClasses(1, false);

 356             // At least after a System.gc() we should definitely stay with a single instance!
 357             checkClassesAfterGC(1);
 358         }
 359     }
 360 }
< prev index next >