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         Path jar = Files.createTempFile("myagent", ".jar");
 119         try {
 120             JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jar.toFile()), manifest);
 121             add(jarStream, FooAgent.class);
 122             add(jarStream, FooTransformer.class);
 123             jarStream.close();
 124             runAgent(jar);
 125         } finally {
 126             Files.deleteIfExists(jar);
 127         }
 128     }
 129 
 130     public static void runAgent(Path agent) throws Exception {
 131         String vmName = ManagementFactory.getRuntimeMXBean().getName();
 132         int p = vmName.indexOf('@');
 133         assert p != -1 : "VM name not in <pid>@<host> format: " + vmName;
 134         String pid = vmName.substring(0, p);
 135         ClassLoader cl = ClassLoader.getSystemClassLoader();
 136         Class<?> c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
 137         Method attach = c.getDeclaredMethod("attach", String.class);
 138         Method loadAgent = c.getDeclaredMethod("loadAgent", String.class);
 139         Method detach = c.getDeclaredMethod("detach");
 140         Object vm = attach.invoke(null, pid);
 141         loadAgent.invoke(vm, agent.toString());
 142         detach.invoke(vm);
 143     }
 144 
 145     public static class FooAgent {
 146 
 147         public static void agentmain(@SuppressWarnings("unused") String args, Instrumentation inst) throws Exception {
 148             assert inst.isRedefineClassesSupported();
 149             assert inst.isRetransformClassesSupported();
 150             inst.addTransformer(new FooTransformer(), true);
 151             Class<?>[] classes = inst.getAllLoadedClasses();
 152             for (int i = 0; i < classes.length; i++) {
 153                 Class<?> c = classes[i];
 154                 if (c == Foo.class) {
 155                     inst.retransformClasses(new Class[]{c});
 156                 }
 157             }
 158         }
 159     }
 160 
 161     static class FooTransformer implements ClassFileTransformer {
 162 
 163         @Override
 164         public byte[] transform(ClassLoader cl, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
 165             if (Foo.class.equals(classBeingRedefined)) {
 166                 System.out.println("redefining " + classBeingRedefined);
 167                 ClassReader cr = new ClassReader(classfileBuffer);
 168                 ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES);
 169                 ClassVisitor adapter = new ClassVisitor(Opcodes.ASM5, cw) {
 170                     @Override
 171                     public MethodVisitor visitMethod(int access, String base, String desc, String signature, String[] exceptions) {
 172                         MethodVisitor mv = cv.visitMethod(access, base, desc, signature, exceptions);
 173                         if (mv != null) {
 174                             mv = new MethodVisitor(Opcodes.ASM5, mv) {
 175                                 @Override
 176                                 public void visitLdcInsn(Object cst) {
 177                                     System.out.println("replacing \"" + cst + "\" with \"bar\"");
 178                                     mv.visitLdcInsn("bar");
 179                                 }
 180                             };
 181                         }
 182                         return mv;
 183                     }
 184                 };
 185 
 186                 cr.accept(adapter, ClassReader.SKIP_FRAMES);
 187                 cw.visitEnd();
 188                 return cw.toByteArray();
 189             }
 190             return classfileBuffer;
 191         }
 192     }
 193 }