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