1 /*
   2  * Copyright (c) 2011, 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  * @requires (os.simpleArch == "x64" | os.simpleArch == "sparcv9" | os.simpleArch == "aarch64")
  27  * @compile RedefineClassTest.java TypeUniverse.java TestMetaAccessProvider.java
  28  * @run junit/othervm -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI jdk.vm.ci.runtime.test.RedefineClassTest
  29  */
  30 
  31 package jdk.vm.ci.runtime.test;
  32 
  33 import static org.junit.Assume.assumeTrue;
  34 
  35 import java.io.FileOutputStream;
  36 import java.io.IOException;
  37 import java.io.InputStream;
  38 import java.lang.instrument.ClassFileTransformer;
  39 import java.lang.instrument.IllegalClassFormatException;
  40 import java.lang.instrument.Instrumentation;
  41 import java.lang.management.ManagementFactory;
  42 import java.lang.reflect.Method;
  43 import java.nio.file.Files;
  44 import java.nio.file.Path;
  45 import java.security.ProtectionDomain;
  46 import java.util.Arrays;
  47 import java.util.jar.Attributes;
  48 import java.util.jar.JarEntry;
  49 import java.util.jar.JarOutputStream;
  50 import java.util.jar.Manifest;
  51 
  52 import javax.tools.ToolProvider;
  53 
  54 import jdk.vm.ci.meta.ResolvedJavaMethod;
  55 
  56 import org.junit.Assert;
  57 import org.junit.Test;
  58 
  59 /**
  60  * Tests that {@link ResolvedJavaMethod}s are safe in the context of class redefinition being used
  61  * to redefine the method to which they refer.
  62  */
  63 public class RedefineClassTest extends TypeUniverse {
  64 
  65     static class Foo {
  66         public static Object getName() {
  67             return "foo";
  68         }
  69     }
  70 
  71     @Test
  72     public void test() throws Throwable {
  73 
  74         Method fooMethod = Foo.class.getDeclaredMethod("getName");
  75 
  76         ResolvedJavaMethod foo1 = metaAccess.lookupJavaMethod(fooMethod);
  77         ResolvedJavaMethod foo2 = metaAccess.lookupJavaMethod(fooMethod);
  78 
  79         String foo1Code = Arrays.toString(foo1.getCode());
  80         String foo2Code = Arrays.toString(foo2.getCode());
  81 
  82         Assert.assertEquals("foo", Foo.getName());
  83 
  84         redefineFoo();
  85         System.gc();
  86 
  87         // Make sure the transformation happened
  88         Assert.assertEquals("bar", Foo.getName());
  89 
  90         Assert.assertEquals(foo1Code, Arrays.toString(foo1.getCode()));
  91         Assert.assertEquals(foo2Code, Arrays.toString(foo1.getCode()));
  92     }
  93 
  94     /**
  95      * Adds the class file bytes for a given class to a JAR stream.
  96      */
  97     static void add(JarOutputStream jar, Class<?> c) throws IOException {
  98         String name = c.getName();
  99         String classAsPath = name.replace('.', '/') + ".class";
 100         jar.putNextEntry(new JarEntry(classAsPath));
 101 
 102         InputStream stream = c.getClassLoader().getResourceAsStream(classAsPath);
 103 
 104         int nRead;
 105         byte[] buf = new byte[1024];
 106         while ((nRead = stream.read(buf, 0, buf.length)) != -1) {
 107             jar.write(buf, 0, nRead);
 108         }
 109 
 110         jar.closeEntry();
 111     }
 112 
 113     protected void redefineFoo() throws Exception {
 114         Manifest manifest = new Manifest();
 115         manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
 116         Attributes mainAttrs = manifest.getMainAttributes();
 117         mainAttrs.putValue("Agent-Class", FooAgent.class.getName());
 118         mainAttrs.putValue("Can-Redefine-Classes", "true");
 119         mainAttrs.putValue("Can-Retransform-Classes", "true");
 120 
 121         Path jar = Files.createTempFile("myagent", ".jar");
 122         try {
 123             JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jar.toFile()), manifest);
 124             add(jarStream, FooAgent.class);
 125             add(jarStream, FooTransformer.class);
 126             jarStream.close();
 127 
 128             loadAgent(jar);
 129         } finally {
 130             Files.deleteIfExists(jar);
 131         }
 132     }
 133 
 134     public static void loadAgent(Path agent) throws Exception {
 135         String vmName = ManagementFactory.getRuntimeMXBean().getName();
 136         int p = vmName.indexOf('@');
 137         assumeTrue(p != -1);
 138         String pid = vmName.substring(0, p);
 139         ClassLoader cl = ToolProvider.getSystemToolClassLoader();
 140         Class<?> c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
 141         Method attach = c.getDeclaredMethod("attach", String.class);
 142         Method loadAgent = c.getDeclaredMethod("loadAgent", String.class, String.class);
 143         Method detach = c.getDeclaredMethod("detach");
 144         Object vm = attach.invoke(null, pid);
 145         loadAgent.invoke(vm, agent.toString(), "");
 146         detach.invoke(vm);
 147     }
 148 
 149     public static class FooAgent {
 150 
 151         public static void agentmain(@SuppressWarnings("unused") String args, Instrumentation inst) throws Exception {
 152             if (inst.isRedefineClassesSupported() && inst.isRetransformClassesSupported()) {
 153                 inst.addTransformer(new FooTransformer(), true);
 154                 Class<?>[] allClasses = inst.getAllLoadedClasses();
 155                 for (int i = 0; i < allClasses.length; i++) {
 156                     Class<?> c = allClasses[i];
 157                     if (c == Foo.class) {
 158                         inst.retransformClasses(new Class<?>[]{c});
 159                     }
 160                 }
 161             }
 162         }
 163     }
 164 
 165     /**
 166      * This transformer replaces the first instance of the constant "foo" in the class file for
 167      * {@link Foo} with "bar".
 168      */
 169     static class FooTransformer implements ClassFileTransformer {
 170 
 171         @Override
 172         public byte[] transform(ClassLoader cl, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
 173             if (Foo.class.equals(classBeingRedefined)) {
 174                 String cf = new String(classfileBuffer);
 175                 int i = cf.indexOf("foo");
 176                 Assert.assertTrue("cannot find \"foo\" constant in " + Foo.class.getSimpleName() + "'s class file", i > 0);
 177                 classfileBuffer[i] = 'b';
 178                 classfileBuffer[i + 1] = 'a';
 179                 classfileBuffer[i + 2] = 'r';
 180             }
 181             return classfileBuffer;
 182         }
 183     }
 184 }