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