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