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  * @test
  26  * @bug 8042235
  27  * @summary redefining method used by multiple MethodHandles crashes VM
  28  * @compile -XDignore.symbol.file RedefineMethodUsedByMultipleMethodHandlesNoASM.java
  29  * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+EnableInvokeDynamic RedefineMethodUsedByMultipleMethodHandlesNoASM
  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 public class RedefineMethodUsedByMultipleMethodHandlesNoASM {
  45 
  46     static class Foo {
  47         public static Object getName() {
  48             int fooInt = 1;
  49             if (true) {
  50                 // We "just know" that this creates bytecodes:
  51                 // bipush 0x7     0x10 0x7
  52                 // ishl           0x78
  53                 fooInt <<= 0x7;
  54             }
  55             return "foo" + fooInt;
  56         }
  57     }
  58 
  59     public static void main(String[] args) throws Throwable {
  60 
  61         Lookup lookup = MethodHandles.lookup();
  62         Method fooMethod = Foo.class.getDeclaredMethod("getName");
  63 
  64         // fooMH2 displaces fooMH1 from the MemberNamesTable
  65         MethodHandle fooMH1 = lookup.unreflect(fooMethod);
  66         MethodHandle fooMH2 = lookup.unreflect(fooMethod);
  67 
  68         System.out.println("Foo.getName() = " + Foo.getName());
  69         System.out.println("fooMH1.invoke = " + fooMH1.invokeExact());
  70         System.out.println("fooMH2.invoke = " + fooMH2.invokeExact());
  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         // Calling fooMH1.vmtarget crashes the VM on JDK8, on JDK7 we see
  80         // the wrong method invoked, we execute the old code.
  81         Object newResult = fooMH1.invokeExact();
  82         System.out.println("fooMH1.invoke = " + fooMH1.invokeExact());
  83         if (!((String) newResult).equals("foo32")) {
  84             throw new RuntimeException("failed, fooMH1 invoke gets '" + newResult + "'");
  85         }
  86     }
  87 
  88     /**
  89      * Adds the class file bytes for {@code c} to {@code jar}.
  90      */
  91     static void add(JarOutputStream jar, Class<?> c) throws IOException {
  92         String classAsPath = c.getName().replace('.', '/') + ".class";
  93         jar.putNextEntry(new JarEntry(classAsPath));
  94         InputStream stream = c.getClassLoader().getResourceAsStream(classAsPath);
  95 
  96         int b;
  97         while ((b = stream.read()) != -1) {
  98             jar.write(b);
  99         }
 100     }
 101 
 102     static void redefineFoo() throws Exception {
 103         Manifest manifest = new Manifest();
 104         manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
 105         Attributes mainAttrs = manifest.getMainAttributes();
 106         mainAttrs.putValue("Agent-Class", FooAgent.class.getName());
 107         mainAttrs.putValue("Can-Redefine-Classes", "true");
 108         mainAttrs.putValue("Can-Retransform-Classes", "true");
 109 
 110         Path jar = Files.createTempFile("myagent", ".jar");
 111         try {
 112             JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jar.toFile()), manifest);
 113             add(jarStream, FooAgent.class);
 114             add(jarStream, FooTransformer.class);
 115             jarStream.close();
 116             runAgent(jar);
 117         } finally {
 118             Files.deleteIfExists(jar);
 119         }
 120     }
 121 
 122     public static void runAgent(Path agent) throws Exception {
 123         String vmName = ManagementFactory.getRuntimeMXBean().getName();
 124         int p = vmName.indexOf('@');
 125         assert p != -1 : "VM name not in <pid>@<host> format: " + vmName;
 126         String pid = vmName.substring(0, p);
 127         ClassLoader cl = ToolProvider.getSystemToolClassLoader();
 128         Class<?> c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
 129         Method attach = c.getDeclaredMethod("attach", String.class);
 130         Method loadAgent = c.getDeclaredMethod("loadAgent", String.class);
 131         Method detach = c.getDeclaredMethod("detach");
 132         Object vm = attach.invoke(null, pid);
 133         loadAgent.invoke(vm, agent.toString());
 134         detach.invoke(vm);
 135     }
 136 
 137     public static class FooAgent {
 138 
 139         public static void agentmain(@SuppressWarnings("unused") String args, Instrumentation inst) throws Exception {
 140             assert inst.isRedefineClassesSupported();
 141             assert inst.isRetransformClassesSupported();
 142             inst.addTransformer(new FooTransformer(), true);
 143             Class<?>[] classes = inst.getAllLoadedClasses();
 144             for (int i = 0; i < classes.length; i++) {
 145                 Class<?> c = classes[i];
 146                 if (c == Foo.class) {
 147                     inst.retransformClasses(new Class[]{c});
 148                 }
 149             }
 150         }
 151     }
 152 
 153 
 154     /**
 155       * This method will only be called on the class Foo, above, and that class
 156       * only has the method getName().
 157       * Avoid using the objectweb ASM library as we do in jdk8, by 
 158       * looking for a specific bytecode pattern (which this method does not really
 159       * understand).
 160       */
 161     static class FooTransformer implements ClassFileTransformer {
 162 
 163         @Override
 164         public byte[] transform(ClassLoader cl, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
 165                                 byte[] classfileBuffer) throws IllegalClassFormatException {
 166 
 167 
 168             if (Foo.class.equals(classBeingRedefined)) {
 169 
 170                 try {
 171                     System.out.println("redefining " + classBeingRedefined);
 172                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
 173                     InputStream is = new ByteArrayInputStream(classfileBuffer);
 174                     copyWithSubstitution(is, new byte[] {(byte)0x10,(byte)0x07,(byte)0x78}, 
 175                                          new byte[] {(byte)0x10,(byte)0x05,(byte)0x78},
 176                                          baos);
 177                     return baos.toByteArray();
 178                 } catch(Exception e) {
 179                      e.printStackTrace(); 
 180                 }
 181             }
 182             return classfileBuffer;
 183         }
 184 
 185         /**
 186           * Copy bytes from a Reader to an OutputStream.  If a sequence of bytes
 187           * matches the given oldBytes byte array, write the newBytes array instead.
 188           */
 189         public void copyWithSubstitution(InputStream is, byte[] oldBytes, byte [] newBytes, OutputStream out) throws Exception {
 190 
 191             byte[] buffer = new byte[oldBytes.length];
 192 
 193             while (is.available() > 0) {
 194                 int i = 0xff & is.read();
 195                 if (i != oldBytes[0]) {
 196                     out.write(i);
 197                     continue;
 198                 }
 199                 int pos = 0;
 200                 while (pos < oldBytes.length && oldBytes[pos] == (byte) i) {
 201                     buffer[pos] = (byte) i;
 202                     pos++;
 203                     i = is.read();
 204                 }
 205                 // We have read as much as matches oldBytes, plus one byte (now in i).
 206                 // Write out:
 207                 // buffer it if did not match fully
 208                 // new bytes if it was a full match
 209                 if (pos > 0) {
 210                 if (pos == oldBytes.length) {
 211                     System.out.println("copyWithSubstitution: replacing: ");
 212                     printBytesOn(System.out, buffer);
 213                     System.out.println("copyWithSubstitution: with:");
 214                     printBytesOn(System.out, newBytes);
 215                     out.write(newBytes, 0, newBytes.length);
 216                 } else {
 217                     out.write(buffer, 0, pos);
 218                 }
 219                 }
 220                 // Does not handle two sequential occurrences of oldBytes.
 221                 out.write(i);
 222             }
 223             out.close();
 224         }
 225 
 226 
 227     public static void printBytesOn(PrintStream out, byte[] bytes) {
 228         int numColumns =  16;
 229         int column = 0;
 230         for (int i = 0; i < bytes.length; i++) {
 231             if (column == 0) {
 232                 out.print(i);
 233                 out.print("\t");
 234             }
 235             out.print("0x" + Integer.toHexString(255 & bytes[i])
 236                     /* + " (" + (char) bytes[i] + */ + "\t");
 237             column++;
 238             if (column == numColumns) {
 239                 out.println();
 240                 column = 0;
 241             }
 242         }
 243         out.println();
 244     }
 245     }
 246 }