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