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