1 /*
   2  * Copyright (c) 2018, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.jfr.event.io;
  27 
  28 import java.util.Arrays;
  29 import java.util.Set;
  30 import java.util.HashSet;
  31 import java.io.File;
  32 import java.security.ProtectionDomain;
  33 import java.lang.instrument.ClassFileTransformer;
  34 import java.lang.instrument.Instrumentation;
  35 import java.lang.instrument.IllegalClassFormatException;
  36 
  37 import jdk.internal.org.objectweb.asm.ClassReader;
  38 import jdk.internal.org.objectweb.asm.ClassVisitor;
  39 import jdk.internal.org.objectweb.asm.MethodVisitor;
  40 import jdk.internal.org.objectweb.asm.ClassWriter;
  41 import jdk.internal.org.objectweb.asm.Opcodes;
  42 import jdk.internal.org.objectweb.asm.Type;
  43 import jdk.test.lib.process.OutputAnalyzer;
  44 import jdk.test.lib.process.ProcessTools;
  45 
  46 /*
  47  * @test
  48  * @summary Test that will instrument the same classes that JFR will also instrument.
  49  * @key jfr
  50  * @requires vm.hasJFR
  51  *
  52  * @library /test/lib /test/jdk
  53  * @modules java.base/jdk.internal.org.objectweb.asm
  54  *          java.instrument
  55  *          jdk.jartool/sun.tools.jar
  56  *          jdk.jfr
  57  *
  58  * @run main/othervm jdk.jfr.event.io.TestInstrumentation
  59  */
  60 
  61 // Test that will instrument the same classes that JFR will also instrument.
  62 //
  63 // The methods that will be instrumented, for example java.io.RandomAccessFile.write,
  64 // will add the following code at the start of the method:
  65 // InstrumentationCallback.callback("<classname>::<methodname>");
  66 //
  67 // The class InstrumentationCallback will log all keys added by the callback() function.
  68 //
  69 // With this instrumentation in place, we will run some existing jfr.io tests
  70 // to verify that our instrumentation has not broken the JFR instrumentation.
  71 //
  72 // After the tests have been run, we verify that the callback() function have been
  73 // called from all instrumented classes and methods. This will verify that JFR has not
  74 // broken our instrumentation.
  75 //
  76 // To use instrumentation, the test must be run in a new java process with
  77 // the -javaagent option.
  78 // We must also create two jars:
  79 // TestInstrumentation.jar: The javaagent for the instrumentation.
  80 // InstrumentationCallback.jar: This is a separate jar with the instrumentation
  81 // callback() function. It is in a separate jar because it must be added to
  82 // the bootclasspath to be called from java.io classes.
  83 //
  84 // The test contains 3 parts:
  85 // Setup part that will create jars and launch the new test instance.
  86 // Agent part that contains the instrumentation code.
  87 // The actual test part is in the TestMain class.
  88 //
  89 public class TestInstrumentation implements ClassFileTransformer {
  90 
  91     private static Instrumentation instrumentation = null;
  92     private static TestInstrumentation testTransformer = null;
  93 
  94     // All methods that will be instrumented.
  95     private static final String[] instrMethodKeys = {
  96         "java/io/RandomAccessFile::seek::(J)V",
  97         "java/io/RandomAccessFile::read::()I",
  98         "java/io/RandomAccessFile::read::([B)I",
  99         "java/io/RandomAccessFile::write::([B)V",
 100         "java/io/RandomAccessFile::write::(I)V",
 101         "java/io/RandomAccessFile::close::()V",
 102         "java/io/FileInputStream::read::([BII)I",
 103         "java/io/FileInputStream::read::([B)I",
 104         "java/io/FileInputStream::read::()I",
 105         "java/io/FileOutputStream::write::(I)V",
 106         "java/io/FileOutputStream::write::([B)V",
 107         "java/io/FileOutputStream::write::([BII)V",
 108         "java/net/SocketInputStream::read::()I",
 109         "java/net/SocketInputStream::read::([B)I",
 110         "java/net/SocketInputStream::read::([BII)I",
 111         "java/net/SocketInputStream::close::()V",
 112         "java/net/SocketOutputStream::write::(I)V",
 113         "java/net/SocketOutputStream::write::([B)V",
 114         "java/net/SocketOutputStream::write::([BII)V",
 115         "java/net/SocketOutputStream::close::()V",
 116         "java/nio/channels/FileChannel::read::([Ljava/nio/ByteBuffer;)J",
 117         "java/nio/channels/FileChannel::write::([Ljava/nio/ByteBuffer;)J",
 118         "java/nio/channels/SocketChannel::open::()Ljava/nio/channels/SocketChannel;",
 119         "java/nio/channels/SocketChannel::open::(Ljava/net/SocketAddress;)Ljava/nio/channels/SocketChannel;",
 120         "java/nio/channels/SocketChannel::read::([Ljava/nio/ByteBuffer;)J",
 121         "java/nio/channels/SocketChannel::write::([Ljava/nio/ByteBuffer;)J",
 122         "sun/nio/ch/FileChannelImpl::read::(Ljava/nio/ByteBuffer;)I",
 123         "sun/nio/ch/FileChannelImpl::write::(Ljava/nio/ByteBuffer;)I",
 124     };
 125 
 126     private static String getInstrMethodKey(String className, String methodName, String signature) {
 127         // This key is used to identify a class and method. It is sent to callback(key)
 128         return className + "::" + methodName + "::" + signature;
 129     }
 130 
 131     private static String getClassFromMethodKey(String methodKey) {
 132         return methodKey.split("::")[0];
 133     }
 134 
 135     // Set of all classes targeted for instrumentation.
 136     private static Set<String> instrClassesTarget = null;
 137 
 138     // Set of all classes where instrumentation has been completed.
 139     private static Set<String> instrClassesDone = null;
 140 
 141     static {
 142         // Split class names from InstrMethodKeys.
 143         instrClassesTarget = new HashSet<String>();
 144         instrClassesDone = new HashSet<String>();
 145         for (String s : instrMethodKeys) {
 146             String className = getClassFromMethodKey(s);
 147             instrClassesTarget.add(className);
 148         }
 149     }
 150 
 151     private static void log(String msg) {
 152         System.out.println("TestTransformation: " + msg);
 153     }
 154 
 155 
 156     ////////////////////////////////////////////////////////////////////
 157     // This is the actual test part.
 158     // A batch of jfr io tests will be run twice with a
 159     // retransfromClasses() in between. After each test batch we verify
 160     // that all callbacks have been called.
 161     ////////////////////////////////////////////////////////////////////
 162 
 163     public static class TestMain {
 164 
 165         private enum TransformStatus { Transformed, Retransformed, Removed }
 166 
 167         public static void main(String[] args) throws Throwable {
 168             runAllTests(TransformStatus.Transformed);
 169 
 170             // Retransform all classes and then repeat tests
 171             Set<Class<?>> classes = new HashSet<Class<?>>();
 172             for (String className : instrClassesTarget) {
 173                 Class<?> clazz = Class.forName(className.replaceAll("/", "."));
 174                 classes.add(clazz);
 175                 log("Will retransform " + clazz.getName());
 176             }
 177             instrumentation.retransformClasses(classes.toArray(new Class<?>[0]));
 178 
 179             // Clear all callback keys so we don't read keys from the previous test run.
 180             InstrumentationCallback.clear();
 181             runAllTests(TransformStatus.Retransformed);
 182 
 183             // Remove my test transformer and run tests again. Should not get any callbacks.
 184             instrumentation.removeTransformer(testTransformer);
 185             instrumentation.retransformClasses(classes.toArray(new Class<?>[0]));
 186             InstrumentationCallback.clear();
 187             runAllTests(TransformStatus.Removed);
 188         }
 189 
 190         // This is not all available jfr io tests, but a reasonable selection.
 191         public static void runAllTests(TransformStatus status) throws Throwable {
 192             log("runAllTests, TransformStatus: " + status);
 193             try {
 194                 String[] noArgs = new String[0];
 195                 TestRandomAccessFileEvents.main(noArgs);
 196                 TestSocketEvents.main(noArgs);
 197                 TestSocketChannelEvents.main(noArgs);
 198                 TestFileChannelEvents.main(noArgs);
 199                 TestFileStreamEvents.main(noArgs);
 200                 TestDisabledEvents.main(noArgs);
 201 
 202                 // Verify that all expected callbacks have been called.
 203                 Set<String> callbackKeys = InstrumentationCallback.getKeysCopy();
 204                 for (String key : instrMethodKeys) {
 205                     boolean gotCallback = callbackKeys.contains(key);
 206                     boolean expectsCallback = isClassInstrumented(status, key);
 207                     String msg = String.format("key:%s, expects:%b", key, expectsCallback);
 208                     if (gotCallback != expectsCallback) {
 209                         throw new Exception("Wrong callback() for " + msg);
 210                     } else {
 211                         log("Correct callback() for " + msg);
 212                     }
 213                 }
 214             } catch (Throwable t) {
 215                 log("Test failed in phase " + status);
 216                 t.printStackTrace();
 217                 throw t;
 218             }
 219         }
 220 
 221         private static boolean isClassInstrumented(TransformStatus status, String key) throws Throwable {
 222             switch (status) {
 223             case Retransformed:
 224                 return true;
 225             case Removed:
 226                 return false;
 227             case Transformed:
 228                 String className = getClassFromMethodKey(key);
 229                 return instrClassesDone.contains(className);
 230             }
 231             throw new Exception("Test error: Unknown TransformStatus: " + status);
 232         }
 233     }
 234 
 235 
 236     ////////////////////////////////////////////////////////////////////
 237     // This is the setup part. It will create needed jars and
 238     // launch a new java instance that will run the internal class TestMain.
 239     // This setup step is needed because we must use a javaagent jar to
 240     // transform classes.
 241     ////////////////////////////////////////////////////////////////////
 242 
 243     public static void main(String[] args) throws Throwable {
 244         buildJar("TestInstrumentation", true);
 245         buildJar("InstrumentationCallback", false);
 246         launchTest();
 247     }
 248 
 249     private static void buildJar(String jarName, boolean withManifest) throws Throwable {
 250         final String slash = File.separator;
 251         final String packageName = "jdk/jfr/event/io".replace("/", slash);
 252         System.out.println("buildJar packageName: " + packageName);
 253 
 254         String testClasses = System.getProperty("test.classes", "?");
 255         String testSrc = System.getProperty("test.src", "?");
 256         String jarPath = testClasses + slash + jarName + ".jar";
 257         String manifestPath = testSrc + slash + jarName + ".mf";
 258         String className = packageName + slash + jarName + ".class";
 259 
 260         String[] args = null;
 261         if (withManifest) {
 262             args = new String[] {"-cfm", jarPath, manifestPath, "-C", testClasses, className};
 263         } else {
 264             args = new String[] {"-cf", jarPath, "-C", testClasses, className};
 265         }
 266 
 267         log("Running jar " + Arrays.toString(args));
 268         sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar");
 269         if (!jarTool.run(args)) {
 270             throw new Exception("jar failed: args=" + Arrays.toString(args));
 271         }
 272     }
 273 
 274     // Launch the test instance. Will run the internal class TestMain.
 275     private static void launchTest() throws Throwable {
 276         final String slash = File.separator;
 277 
 278         // Need to add jdk/lib/tools.jar to classpath.
 279         String classpath =
 280             System.getProperty("test.class.path", "") + File.pathSeparator +
 281             System.getProperty("test.jdk", ".") + slash + "lib" + slash + "tools.jar";
 282         String testClassDir = System.getProperty("test.classes", "") + slash;
 283 
 284         String[] args = {
 285             "-Xbootclasspath/a:" + testClassDir + "InstrumentationCallback.jar",
 286             "--add-exports", "java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED",
 287             "-classpath", classpath,
 288             "-javaagent:" + testClassDir + "TestInstrumentation.jar",
 289             "jdk.jfr.event.io.TestInstrumentation$TestMain" };
 290         OutputAnalyzer output = ProcessTools.executeTestJvm(args);
 291         output.shouldHaveExitValue(0);
 292     }
 293 
 294 
 295     ////////////////////////////////////////////////////////////////////
 296     // This is the java agent part. Used to transform classes.
 297     //
 298     // Each transformed method will add this call:
 299     // InstrumentationCallback.callback("<classname>::<methodname>");
 300     ////////////////////////////////////////////////////////////////////
 301 
 302     public static void premain(String args, Instrumentation inst) throws Exception {
 303         instrumentation = inst;
 304         testTransformer = new TestInstrumentation();
 305         inst.addTransformer(testTransformer, true);
 306     }
 307 
 308     public byte[] transform(
 309             ClassLoader classLoader, String className, Class<?> classBeingRedefined,
 310             ProtectionDomain pd, byte[] bytes) throws IllegalClassFormatException {
 311         // Check if this class should be instrumented.
 312         if (!instrClassesTarget.contains(className)) {
 313             return null;
 314         }
 315 
 316         boolean isRedefinition = classBeingRedefined != null;
 317         log("instrument class(" + className + ") " + (isRedefinition ? "redef" : "load"));
 318 
 319         ClassReader reader = new ClassReader(bytes);
 320         ClassWriter writer = new ClassWriter(
 321                 reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
 322         CallbackClassVisitor classVisitor = new CallbackClassVisitor(writer);
 323         reader.accept(classVisitor, 0);
 324         instrClassesDone.add(className);
 325         return writer.toByteArray();
 326     }
 327 
 328     private static class CallbackClassVisitor extends ClassVisitor {
 329         private String className;
 330 
 331         public CallbackClassVisitor(ClassVisitor cv) {
 332             super(Opcodes.ASM5, cv);
 333         }
 334 
 335         @Override
 336         public void visit(
 337                 int version, int access, String name, String signature,
 338                 String superName, String[] interfaces) {
 339             cv.visit(version, access, name, signature, superName, interfaces);
 340             className = name;
 341         }
 342 
 343         @Override
 344         public MethodVisitor visitMethod(
 345                 int access, String methodName, String desc, String signature, String[] exceptions) {
 346             String methodKey = getInstrMethodKey(className, methodName, desc);
 347             boolean isInstrumentedMethod = Arrays.asList(instrMethodKeys).contains(methodKey);
 348             MethodVisitor mv = cv.visitMethod(access, methodName, desc, signature, exceptions);
 349             if (isInstrumentedMethod && mv != null) {
 350                 mv = new CallbackMethodVisitor(mv, methodKey);
 351                 log("instrumented " + methodKey);
 352             }
 353             return mv;
 354         }
 355     }
 356 
 357     public static class CallbackMethodVisitor extends MethodVisitor {
 358         private String logMessage;
 359 
 360         public CallbackMethodVisitor(MethodVisitor mv, String logMessage) {
 361             super(Opcodes.ASM5, mv);
 362             this.logMessage = logMessage;
 363         }
 364 
 365         @Override
 366         public void visitCode() {
 367             mv.visitCode();
 368             String methodDescr = Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class));
 369             String className = InstrumentationCallback.class.getName().replace('.', '/');
 370             mv.visitLdcInsn(logMessage);
 371             mv.visitMethodInsn(Opcodes.INVOKESTATIC, className, "callback", methodDescr);
 372         }
 373     }
 374 
 375 }