1 /*
   2  * Copyright (c) 2014, 2015, 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
  26  * @bug 8042235
  27  * @summary redefining method used by multiple MethodHandles crashes VM
  28  * @library /
  29  * @modules java.base/jdk.internal.org.objectweb.asm
  30  *          java.compiler
  31  *          java.instrument
  32  *          java.management
  33  *          jdk.attach
  34  *
  35  * @run main/othervm -Djdk.attach.allowAttachSelf compiler.jsr292.RedefineMethodUsedByMultipleMethodHandles
  36  */
  37 
  38 package compiler.jsr292;
  39 
  40 import jdk.internal.org.objectweb.asm.ClassReader;
  41 import jdk.internal.org.objectweb.asm.ClassVisitor;
  42 import jdk.internal.org.objectweb.asm.ClassWriter;
  43 import jdk.internal.org.objectweb.asm.MethodVisitor;
  44 import jdk.internal.org.objectweb.asm.Opcodes;
  45 
  46 import java.io.FileOutputStream;
  47 import java.io.IOException;
  48 import java.io.InputStream;
  49 import java.lang.instrument.ClassFileTransformer;
  50 import java.lang.instrument.IllegalClassFormatException;
  51 import java.lang.instrument.Instrumentation;
  52 import java.lang.invoke.MethodHandle;
  53 import java.lang.invoke.MethodHandles;
  54 import java.lang.invoke.MethodHandles.Lookup;
  55 import java.lang.management.ManagementFactory;
  56 import java.lang.reflect.Method;
  57 import java.nio.file.Files;
  58 import java.nio.file.Path;
  59 import java.security.ProtectionDomain;
  60 import java.util.jar.Attributes;
  61 import java.util.jar.JarEntry;
  62 import java.util.jar.JarOutputStream;
  63 import java.util.jar.Manifest;
  64 
  65 public class RedefineMethodUsedByMultipleMethodHandles {
  66 
  67     static class Foo {
  68         public static Object getName() {
  69             return "foo";
  70         }
  71     }
  72 
  73     public static void main(String[] args) throws Throwable {
  74 
  75         Lookup lookup = MethodHandles.lookup();
  76         Method fooMethod = Foo.class.getDeclaredMethod("getName");
  77 
  78         // fooMH2 displaces fooMH1 from the MemberNamesTable
  79         MethodHandle fooMH1 = lookup.unreflect(fooMethod);
  80         MethodHandle fooMH2 = lookup.unreflect(fooMethod);
  81 
  82         System.out.println("fooMH1.invoke = " + fooMH1.invokeExact());
  83         System.out.println("fooMH2.invoke = " + fooMH2.invokeExact());
  84 
  85         // Redefining Foo.getName() causes vmtarget to be updated
  86         // in fooMH2 but not fooMH1
  87         redefineFoo();
  88 
  89         // Full GC causes fooMH1.vmtarget to be deallocated
  90         System.gc();
  91 
  92         // Calling fooMH1.vmtarget crashes the VM
  93         System.out.println("fooMH1.invoke = " + fooMH1.invokeExact());
  94     }
  95 
  96     /**
  97      * Adds the class file bytes for {@code c} to {@code jar}.
  98      */
  99     static void add(JarOutputStream jar, Class<?> c) throws IOException {
 100         String classAsPath = c.getName().replace('.', '/') + ".class";
 101         jar.putNextEntry(new JarEntry(classAsPath));
 102         InputStream stream = c.getClassLoader().getResourceAsStream(classAsPath);
 103 
 104         int b;
 105         while ((b = stream.read()) != -1) {
 106             jar.write(b);
 107         }
 108     }
 109 
 110     static void redefineFoo() throws Exception {
 111         Manifest manifest = new Manifest();
 112         manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
 113         Attributes mainAttrs = manifest.getMainAttributes();
 114         mainAttrs.putValue("Agent-Class", FooAgent.class.getName());
 115         mainAttrs.putValue("Can-Redefine-Classes", "true");
 116         mainAttrs.putValue("Can-Retransform-Classes", "true");
 117 
 118         // The jar file will be added to the system classloader search path.  It is not safe
 119         // to delete it while the JVM is running, so make sure to create it in the test
 120         // directory so it will be cleaned up by the test harness.
 121         Path jar = Files.createTempFile(Path.of(""), "myagent", ".jar");
 122         JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jar.toFile()), manifest);
 123         add(jarStream, FooAgent.class);
 124         add(jarStream, FooTransformer.class);
 125         jarStream.close();
 126         runAgent(jar);
 127     }
 128 
 129     public static void runAgent(Path agent) throws Exception {
 130         String vmName = ManagementFactory.getRuntimeMXBean().getName();
 131         int p = vmName.indexOf('@');
 132         assert p != -1 : "VM name not in <pid>@<host> format: " + vmName;
 133         String pid = vmName.substring(0, p);
 134         ClassLoader cl = ClassLoader.getSystemClassLoader();
 135         Class<?> c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
 136         Method attach = c.getDeclaredMethod("attach", String.class);
 137         Method loadAgent = c.getDeclaredMethod("loadAgent", String.class);
 138         Method detach = c.getDeclaredMethod("detach");
 139         Object vm = attach.invoke(null, pid);
 140         loadAgent.invoke(vm, agent.toString());
 141         detach.invoke(vm);
 142     }
 143 
 144     public static class FooAgent {
 145 
 146         public static void agentmain(@SuppressWarnings("unused") String args, Instrumentation inst) throws Exception {
 147             assert inst.isRedefineClassesSupported();
 148             assert inst.isRetransformClassesSupported();
 149             inst.addTransformer(new FooTransformer(), true);
 150             Class<?>[] classes = inst.getAllLoadedClasses();
 151             for (int i = 0; i < classes.length; i++) {
 152                 Class<?> c = classes[i];
 153                 if (c == Foo.class) {
 154                     inst.retransformClasses(new Class[]{c});
 155                 }
 156             }
 157         }
 158     }
 159 
 160     static class FooTransformer implements ClassFileTransformer {
 161 
 162         @Override
 163         public byte[] transform(ClassLoader cl, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
 164             if (Foo.class.equals(classBeingRedefined)) {
 165                 System.out.println("redefining " + classBeingRedefined);
 166                 ClassReader cr = new ClassReader(classfileBuffer);
 167                 ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES);
 168                 ClassVisitor adapter = new ClassVisitor(Opcodes.ASM5, cw) {
 169                     @Override
 170                     public MethodVisitor visitMethod(int access, String base, String desc, String signature, String[] exceptions) {
 171                         MethodVisitor mv = cv.visitMethod(access, base, desc, signature, exceptions);
 172                         if (mv != null) {
 173                             mv = new MethodVisitor(Opcodes.ASM5, mv) {
 174                                 @Override
 175                                 public void visitLdcInsn(Object cst) {
 176                                     System.out.println("replacing \"" + cst + "\" with \"bar\"");
 177                                     mv.visitLdcInsn("bar");
 178                                 }
 179                             };
 180                         }
 181                         return mv;
 182                     }
 183                 };
 184 
 185                 cr.accept(adapter, ClassReader.SKIP_FRAMES);
 186                 cw.visitEnd();
 187                 return cw.toByteArray();
 188             }
 189             return classfileBuffer;
 190         }
 191     }
 192 }