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