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