1 /*
   2  * Copyright (c) 2011, 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 package org.graalvm.compiler.replacements.test.classfile;
  24 
  25 import static org.junit.Assume.assumeTrue;
  26 
  27 import java.io.FileOutputStream;
  28 import java.io.IOException;
  29 import java.io.InputStream;
  30 import java.lang.instrument.ClassFileTransformer;
  31 import java.lang.instrument.IllegalClassFormatException;
  32 import java.lang.instrument.Instrumentation;
  33 import java.lang.management.ManagementFactory;
  34 import java.lang.reflect.Method;
  35 import java.nio.file.Files;
  36 import java.nio.file.Path;
  37 import java.security.ProtectionDomain;
  38 import java.util.jar.Attributes;
  39 import java.util.jar.JarEntry;
  40 import java.util.jar.JarOutputStream;
  41 import java.util.jar.Manifest;
  42 
  43 import javax.tools.ToolProvider;
  44 
  45 import org.junit.Assert;
  46 import org.junit.Test;
  47 
  48 import org.graalvm.compiler.api.replacements.ClassSubstitution;
  49 import org.graalvm.compiler.api.replacements.MethodSubstitution;
  50 import org.graalvm.compiler.bytecode.BytecodeProvider;
  51 import org.graalvm.compiler.core.test.GraalCompilerTest;
  52 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
  53 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
  54 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.Registration;
  55 
  56 import jdk.vm.ci.meta.ResolvedJavaMethod;
  57 
  58 /**
  59  * Tests that intrinsics (and snippets) are isolated from bytecode instrumentation.
  60  */
  61 public class RedefineIntrinsicTest extends GraalCompilerTest {
  62 
  63     public static class Original {
  64 
  65         // Intrinsified by Intrinsic.getValue
  66         public static String getValue() {
  67             return "original";
  68         }
  69     }
  70 
  71     @ClassSubstitution(Original.class)
  72     private static class Intrinsic {
  73 
  74         @MethodSubstitution
  75         public static String getValue() {
  76             return "intrinsic";
  77         }
  78     }
  79 
  80     @Override
  81     protected GraphBuilderConfiguration editGraphBuilderConfiguration(GraphBuilderConfiguration conf) {
  82         InvocationPlugins invocationPlugins = conf.getPlugins().getInvocationPlugins();
  83         BytecodeProvider replacementBytecodeProvider = getReplacements().getReplacementBytecodeProvider();
  84         Registration r = new Registration(invocationPlugins, Original.class, replacementBytecodeProvider);
  85         r.registerMethodSubstitution(Intrinsic.class, "getValue");
  86         return super.editGraphBuilderConfiguration(conf);
  87     }
  88 
  89     public static String callOriginalGetValue() {
  90         // This call will be intrinsified when compiled by Graal
  91         return Original.getValue();
  92     }
  93 
  94     public static String callIntrinsicGetValue() {
  95         // This call will *not* be intrinsified when compiled by Graal
  96         return Intrinsic.getValue();
  97     }
  98 
  99     @Test
 100     public void test() throws Throwable {
 101         Object receiver = null;
 102         Object[] args = {};
 103 
 104         // Prior to redefinition, both Original and Intrinsic
 105         // should behave as per their Java source code
 106         Assert.assertEquals("original", Original.getValue());
 107         Assert.assertEquals("intrinsic", Intrinsic.getValue());
 108 
 109         ResolvedJavaMethod callOriginalGetValue = getResolvedJavaMethod("callOriginalGetValue");
 110         ResolvedJavaMethod callIntrinsicGetValue = getResolvedJavaMethod("callIntrinsicGetValue");
 111 
 112         // Expect intrinsification to change "original" to "intrinsic"
 113         testAgainstExpected(callOriginalGetValue, new Result("intrinsic", null), receiver, args);
 114 
 115         // Expect no intrinsification
 116         testAgainstExpected(callIntrinsicGetValue, new Result("intrinsic", null), receiver, args);
 117 
 118         // Apply redefinition of intrinsic bytecode
 119         redefineIntrinsic();
 120 
 121         // Expect redefinition to have no effect
 122         Assert.assertEquals("original", Original.getValue());
 123 
 124         // Expect redefinition to change "intrinsic" to "redefined"
 125         Assert.assertEquals("redefined", Intrinsic.getValue());
 126 
 127         // Expect redefinition to have no effect on intrinsification (i.e.,
 128         // "original" is still changed to "intrinsic", not "redefined"
 129         testAgainstExpected(callOriginalGetValue, new Result("intrinsic", null), receiver, args);
 130     }
 131 
 132     /**
 133      * Adds the class file bytes for a given class to a JAR stream.
 134      */
 135     static void add(JarOutputStream jar, Class<?> c) throws IOException {
 136         String name = c.getName();
 137         String classAsPath = name.replace('.', '/') + ".class";
 138         jar.putNextEntry(new JarEntry(classAsPath));
 139 
 140         InputStream stream = c.getClassLoader().getResourceAsStream(classAsPath);
 141 
 142         int nRead;
 143         byte[] buf = new byte[1024];
 144         while ((nRead = stream.read(buf, 0, buf.length)) != -1) {
 145             jar.write(buf, 0, nRead);
 146         }
 147 
 148         jar.closeEntry();
 149     }
 150 
 151     static void redefineIntrinsic() throws Exception {
 152         Manifest manifest = new Manifest();
 153         manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
 154         Attributes mainAttrs = manifest.getMainAttributes();
 155         mainAttrs.putValue("Agent-Class", RedefinerAgent.class.getName());
 156         mainAttrs.putValue("Can-Redefine-Classes", "true");
 157         mainAttrs.putValue("Can-Retransform-Classes", "true");
 158 
 159         Path jar = Files.createTempFile("myagent", ".jar");
 160         try {
 161             JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jar.toFile()), manifest);
 162             add(jarStream, RedefinerAgent.class);
 163             add(jarStream, Redefiner.class);
 164             jarStream.close();
 165 
 166             loadAgent(jar);
 167         } finally {
 168             Files.deleteIfExists(jar);
 169         }
 170     }
 171 
 172     public static void loadAgent(Path agent) throws Exception {
 173         String vmName = ManagementFactory.getRuntimeMXBean().getName();
 174         int p = vmName.indexOf('@');
 175         assumeTrue("VM name not in <pid>@<host> format: " + vmName, p != -1);
 176         String pid = vmName.substring(0, p);
 177         ClassLoader cl = ToolProvider.getSystemToolClassLoader();
 178         Class<?> c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
 179         Method attach = c.getDeclaredMethod("attach", String.class);
 180         Method loadAgent = c.getDeclaredMethod("loadAgent", String.class, String.class);
 181         Method detach = c.getDeclaredMethod("detach");
 182         Object vm = attach.invoke(null, pid);
 183         loadAgent.invoke(vm, agent.toString(), "");
 184         detach.invoke(vm);
 185     }
 186 
 187     public static class RedefinerAgent {
 188 
 189         public static void agentmain(@SuppressWarnings("unused") String args, Instrumentation inst) throws Exception {
 190             if (inst.isRedefineClassesSupported() && inst.isRetransformClassesSupported()) {
 191                 inst.addTransformer(new Redefiner(), true);
 192                 Class<?>[] allClasses = inst.getAllLoadedClasses();
 193                 for (int i = 0; i < allClasses.length; i++) {
 194                     Class<?> c = allClasses[i];
 195                     if (c == Intrinsic.class) {
 196                         inst.retransformClasses(new Class<?>[]{c});
 197                     }
 198                 }
 199             }
 200         }
 201     }
 202 
 203     /**
 204      * This transformer replaces the first instance of the constant "intrinsic" in the class file
 205      * for {@link Intrinsic} with "redefined".
 206      */
 207     static class Redefiner implements ClassFileTransformer {
 208 
 209         @Override
 210         public byte[] transform(ClassLoader cl, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
 211             if (Intrinsic.class.equals(classBeingRedefined)) {
 212                 String cf = new String(classfileBuffer);
 213                 int i = cf.indexOf("intrinsic");
 214                 Assert.assertTrue("cannot find \"intrinsic\" constant in " + Intrinsic.class.getSimpleName() + "'s class file", i > 0);
 215                 System.arraycopy("redefined".getBytes(), 0, classfileBuffer, i, "redefined".length());
 216             }
 217             return classfileBuffer;
 218         }
 219     }
 220 }