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 
  24 
  25 package org.graalvm.compiler.replacements.test.classfile;
  26 
  27 import static org.graalvm.compiler.test.SubprocessUtil.getVMCommandLine;
  28 import static org.graalvm.compiler.test.SubprocessUtil.java;
  29 import static org.graalvm.compiler.test.SubprocessUtil.withoutDebuggerArguments;
  30 import static org.junit.Assume.assumeTrue;
  31 
  32 import java.io.FileOutputStream;
  33 import java.io.IOException;
  34 import java.io.InputStream;
  35 import java.lang.instrument.ClassFileTransformer;
  36 import java.lang.instrument.IllegalClassFormatException;
  37 import java.lang.instrument.Instrumentation;
  38 import java.lang.management.ManagementFactory;
  39 import java.lang.reflect.Method;
  40 import java.nio.file.Files;
  41 import java.nio.file.Path;
  42 import java.security.ProtectionDomain;
  43 import java.util.List;
  44 import java.util.jar.Attributes;
  45 import java.util.jar.JarEntry;
  46 import java.util.jar.JarOutputStream;
  47 import java.util.jar.Manifest;
  48 
  49 import javax.tools.ToolProvider;
  50 
  51 import org.graalvm.compiler.api.replacements.ClassSubstitution;
  52 import org.graalvm.compiler.api.replacements.MethodSubstitution;
  53 import org.graalvm.compiler.bytecode.BytecodeProvider;
  54 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
  55 import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.Registration;
  56 import org.graalvm.compiler.replacements.test.ReplacementsTest;
  57 import org.graalvm.compiler.test.SubprocessUtil.Subprocess;
  58 import org.junit.Assert;
  59 import org.junit.Test;
  60 
  61 import jdk.vm.ci.meta.ResolvedJavaMethod;
  62 
  63 /**
  64  * Tests that intrinsics (and snippets) are isolated from bytecode instrumentation.
  65  */
  66 public class RedefineIntrinsicTest extends ReplacementsTest {
  67 
  68     public static class Original {
  69 
  70         // Intrinsified by Intrinsic.getValue
  71         public static String getValue() {
  72             return "original";
  73         }
  74     }
  75 
  76     @ClassSubstitution(Original.class)
  77     private static class Intrinsic {
  78 
  79         @MethodSubstitution
  80         public static String getValue() {
  81             return "intrinsic";
  82         }
  83     }
  84 
  85     @Override
  86     protected void registerInvocationPlugins(InvocationPlugins invocationPlugins) {
  87         BytecodeProvider replacementBytecodeProvider = getSystemClassLoaderBytecodeProvider();
  88         Registration r = new Registration(invocationPlugins, Original.class, replacementBytecodeProvider);
  89         r.registerMethodSubstitution(Intrinsic.class, "getValue");
  90         super.registerInvocationPlugins(invocationPlugins);
  91     }
  92 
  93     public static String callOriginalGetValue() {
  94         // This call will be intrinsified when compiled by Graal
  95         return Original.getValue();
  96     }
  97 
  98     public static String callIntrinsicGetValue() {
  99         // This call will *not* be intrinsified when compiled by Graal
 100         return Intrinsic.getValue();
 101     }
 102 
 103     @Test
 104     public void test() throws Throwable {
 105         assumeManagementLibraryIsLoadable();
 106         try {
 107             Class.forName("java.lang.instrument.Instrumentation");
 108         } catch (ClassNotFoundException ex) {
 109             // skip this test if java.instrument JDK9 module is missing
 110             return;
 111         }
 112         String recursionPropName = getClass().getName() + ".recursion";
 113         if (Java8OrEarlier || Boolean.getBoolean(recursionPropName)) {
 114             testHelper();
 115         } else {
 116             List<String> vmArgs = withoutDebuggerArguments(getVMCommandLine());
 117             vmArgs.add("-D" + recursionPropName + "=true");
 118             vmArgs.add("-Djdk.attach.allowAttachSelf=true");
 119             Subprocess proc = java(vmArgs, "com.oracle.mxtool.junit.MxJUnitWrapper", getClass().getName());
 120             if (proc.exitCode != 0) {
 121                 Assert.fail(String.format("non-zero exit code %d for command:%n%s", proc.exitCode, proc));
 122             }
 123         }
 124     }
 125 
 126     public void testHelper() throws Throwable {
 127 
 128         Object receiver = null;
 129         Object[] args = {};
 130 
 131         // Prior to redefinition, both Original and Intrinsic
 132         // should behave as per their Java source code
 133         Assert.assertEquals("original", Original.getValue());
 134         Assert.assertEquals("intrinsic", Intrinsic.getValue());
 135 
 136         ResolvedJavaMethod callOriginalGetValue = getResolvedJavaMethod("callOriginalGetValue");
 137         ResolvedJavaMethod callIntrinsicGetValue = getResolvedJavaMethod("callIntrinsicGetValue");
 138 
 139         // Expect intrinsification to change "original" to "intrinsic"
 140         testAgainstExpected(callOriginalGetValue, new Result("intrinsic", null), receiver, args);
 141 
 142         // Expect no intrinsification
 143         testAgainstExpected(callIntrinsicGetValue, new Result("intrinsic", null), receiver, args);
 144 
 145         // Apply redefinition of intrinsic bytecode
 146         if (!redefineIntrinsic()) {
 147             // running on JDK9 without agent
 148             return;
 149         }
 150 
 151         // Expect redefinition to have no effect
 152         Assert.assertEquals("original", Original.getValue());
 153 
 154         // Expect redefinition to change "intrinsic" to "redefined"
 155         Assert.assertEquals("redefined", Intrinsic.getValue());
 156 
 157         // Expect redefinition to have no effect on intrinsification (i.e.,
 158         // "original" is still changed to "intrinsic", not "redefined"
 159         testAgainstExpected(callOriginalGetValue, new Result("intrinsic", null), receiver, args);
 160     }
 161 
 162     /**
 163      * Adds the class file bytes for a given class to a JAR stream.
 164      */
 165     static void add(JarOutputStream jar, Class<?> c) throws IOException {
 166         String name = c.getName();
 167         String classAsPath = name.replace('.', '/') + ".class";
 168         jar.putNextEntry(new JarEntry(classAsPath));
 169 
 170         InputStream stream = c.getClassLoader().getResourceAsStream(classAsPath);
 171 
 172         int nRead;
 173         byte[] buf = new byte[1024];
 174         while ((nRead = stream.read(buf, 0, buf.length)) != -1) {
 175             jar.write(buf, 0, nRead);
 176         }
 177 
 178         jar.closeEntry();
 179     }
 180 
 181     static boolean redefineIntrinsic() throws Exception {
 182         Manifest manifest = new Manifest();
 183         manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
 184         Attributes mainAttrs = manifest.getMainAttributes();
 185         mainAttrs.putValue("Agent-Class", RedefinerAgent.class.getName());
 186         mainAttrs.putValue("Can-Redefine-Classes", "true");
 187         mainAttrs.putValue("Can-Retransform-Classes", "true");
 188 
 189         Path jar = Files.createTempFile("myagent", ".jar");
 190         try {
 191             JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jar.toFile()), manifest);
 192             add(jarStream, RedefinerAgent.class);
 193             add(jarStream, Redefiner.class);
 194             jarStream.close();
 195 
 196             return loadAgent(jar);
 197         } finally {
 198             Files.deleteIfExists(jar);
 199         }
 200     }
 201 
 202     @SuppressWarnings({"deprecation", "unused"})
 203     public static boolean loadAgent(Path agent) throws Exception {
 204         String vmName = ManagementFactory.getRuntimeMXBean().getName();
 205         int p = vmName.indexOf('@');
 206         assumeTrue("VM name not in <pid>@<host> format: " + vmName, p != -1);
 207         String pid = vmName.substring(0, p);
 208         Class<?> c;
 209         if (Java8OrEarlier) {
 210             ClassLoader cl = ToolProvider.getSystemToolClassLoader();
 211             c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
 212         } else {
 213             try {
 214                 // I don't know what changed to make this necessary...
 215                 c = Class.forName("com.sun.tools.attach.VirtualMachine", true, RedefineIntrinsicTest.class.getClassLoader());
 216             } catch (ClassNotFoundException ex) {
 217                 try {
 218                     Class.forName("javax.naming.Reference");
 219                 } catch (ClassNotFoundException coreNamingMissing) {
 220                     // if core JDK classes aren't found, we are probably running in a
 221                     // JDK9 java.base environment and then missing class is OK
 222                     return false;
 223                 }
 224                 throw ex;
 225             }
 226         }
 227         Method attach = c.getDeclaredMethod("attach", String.class);
 228         Method loadAgent = c.getDeclaredMethod("loadAgent", String.class, String.class);
 229         Method detach = c.getDeclaredMethod("detach");
 230         Object vm = attach.invoke(null, pid);
 231         loadAgent.invoke(vm, agent.toString(), "");
 232         detach.invoke(vm);
 233         return true;
 234     }
 235 
 236     public static class RedefinerAgent {
 237 
 238         public static void agentmain(@SuppressWarnings("unused") String args, Instrumentation inst) throws Exception {
 239             if (inst.isRedefineClassesSupported() && inst.isRetransformClassesSupported()) {
 240                 inst.addTransformer(new Redefiner(), true);
 241                 Class<?>[] allClasses = inst.getAllLoadedClasses();
 242                 for (int i = 0; i < allClasses.length; i++) {
 243                     Class<?> c = allClasses[i];
 244                     if (c == Intrinsic.class) {
 245                         inst.retransformClasses(new Class<?>[]{c});
 246                     }
 247                 }
 248             }
 249         }
 250     }
 251 
 252     /**
 253      * This transformer replaces the first instance of the constant "intrinsic" in the class file
 254      * for {@link Intrinsic} with "redefined".
 255      */
 256     static class Redefiner implements ClassFileTransformer {
 257 
 258         @Override
 259         public byte[] transform(ClassLoader cl, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
 260             if (Intrinsic.class.equals(classBeingRedefined)) {
 261                 String cf = new String(classfileBuffer);
 262                 int i = cf.indexOf("intrinsic");
 263                 Assert.assertTrue("cannot find \"intrinsic\" constant in " + Intrinsic.class.getSimpleName() + "'s class file", i > 0);
 264                 System.arraycopy("redefined".getBytes(), 0, classfileBuffer, i, "redefined".length());
 265             }
 266             return classfileBuffer;
 267         }
 268     }
 269 }