RedefineIntrinsicTest.java revision 12968:4d8a004e5c6d
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.junit.Assume.assumeTrue;
26
27import java.io.FileOutputStream;
28import java.io.IOException;
29import java.io.InputStream;
30import java.lang.instrument.ClassFileTransformer;
31import java.lang.instrument.IllegalClassFormatException;
32import java.lang.instrument.Instrumentation;
33import java.lang.management.ManagementFactory;
34import java.lang.reflect.Method;
35import java.nio.file.Files;
36import java.nio.file.Path;
37import java.security.ProtectionDomain;
38import java.util.jar.Attributes;
39import java.util.jar.JarEntry;
40import java.util.jar.JarOutputStream;
41import java.util.jar.Manifest;
42
43import javax.tools.ToolProvider;
44
45import org.junit.Assert;
46import org.junit.Test;
47
48import org.graalvm.compiler.api.replacements.ClassSubstitution;
49import org.graalvm.compiler.api.replacements.MethodSubstitution;
50import org.graalvm.compiler.bytecode.BytecodeProvider;
51import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration;
52import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins;
53import org.graalvm.compiler.nodes.graphbuilderconf.InvocationPlugins.Registration;
54import org.graalvm.compiler.replacements.test.ReplacementsTest;
55
56import jdk.vm.ci.meta.ResolvedJavaMethod;
57
58/**
59 * Tests that intrinsics (and snippets) are isolated from bytecode instrumentation.
60 */
61public class RedefineIntrinsicTest extends ReplacementsTest {
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 = getSystemClassLoaderBytecodeProvider();
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        Class<?> c;
178        if (Java8OrEarlier) {
179            ClassLoader cl = ToolProvider.getSystemToolClassLoader();
180            c = Class.forName("com.sun.tools.attach.VirtualMachine", true, cl);
181        } else {
182            // I don't know what changed to make this necessary...
183            c = Class.forName("com.sun.tools.attach.VirtualMachine", true, RedefineIntrinsicTest.class.getClassLoader());
184        }
185        Method attach = c.getDeclaredMethod("attach", String.class);
186        Method loadAgent = c.getDeclaredMethod("loadAgent", String.class, String.class);
187        Method detach = c.getDeclaredMethod("detach");
188        Object vm = attach.invoke(null, pid);
189        loadAgent.invoke(vm, agent.toString(), "");
190        detach.invoke(vm);
191    }
192
193    public static class RedefinerAgent {
194
195        public static void agentmain(@SuppressWarnings("unused") String args, Instrumentation inst) throws Exception {
196            if (inst.isRedefineClassesSupported() && inst.isRetransformClassesSupported()) {
197                inst.addTransformer(new Redefiner(), true);
198                Class<?>[] allClasses = inst.getAllLoadedClasses();
199                for (int i = 0; i < allClasses.length; i++) {
200                    Class<?> c = allClasses[i];
201                    if (c == Intrinsic.class) {
202                        inst.retransformClasses(new Class<?>[]{c});
203                    }
204                }
205            }
206        }
207    }
208
209    /**
210     * This transformer replaces the first instance of the constant "intrinsic" in the class file
211     * for {@link Intrinsic} with "redefined".
212     */
213    static class Redefiner implements ClassFileTransformer {
214
215        @Override
216        public byte[] transform(ClassLoader cl, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
217            if (Intrinsic.class.equals(classBeingRedefined)) {
218                String cf = new String(classfileBuffer);
219                int i = cf.indexOf("intrinsic");
220                Assert.assertTrue("cannot find \"intrinsic\" constant in " + Intrinsic.class.getSimpleName() + "'s class file", i > 0);
221                System.arraycopy("redefined".getBytes(), 0, classfileBuffer, i, "redefined".length());
222            }
223            return classfileBuffer;
224        }
225    }
226}
227