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