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