Java Code Examples for jdk.internal.org.objectweb.asm.ClassReader

The following examples show how to use jdk.internal.org.objectweb.asm.ClassReader. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public byte[] transform(
        ClassLoader classLoader, String className, Class<?> classBeingRedefined,
        ProtectionDomain pd, byte[] bytes) throws IllegalClassFormatException {
    // Check if this class should be instrumented.
    if (!instrClassesTarget.contains(className)) {
        return null;
    }

    boolean isRedefinition = classBeingRedefined != null;
    log("instrument class(" + className + ") " + (isRedefinition ? "redef" : "load"));

    ClassReader reader = new ClassReader(bytes);
    ClassWriter writer = new ClassWriter(
            reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    CallbackClassVisitor classVisitor = new CallbackClassVisitor(writer);
    reader.accept(classVisitor, 0);
    instrClassesDone.add(className);
    return writer.toByteArray();
}
 
Example 2
Source Project: TencentKona-8   Source File: Utils.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void writeGeneratedASM(String className, byte[] bytes) {
    if (SAVE_GENERATED == null) {
        // We can't calculate value statically because it will force
        // initialization of SecuritySupport, which cause
        // UnsatisfiedLinkedError on JDK 8 or non-Oracle JDKs
        SAVE_GENERATED = SecuritySupport.getBooleanProperty("jfr.save.generated.asm");
    }
    if (SAVE_GENERATED) {
        try {
            try (FileOutputStream fos = new FileOutputStream(className + ".class")) {
                fos.write(bytes);
            }

            try (FileWriter fw = new FileWriter(className + ".asm"); PrintWriter pw = new PrintWriter(fw)) {
                ClassReader cr = new ClassReader(bytes);
                CheckClassAdapter.verify(cr, true, pw);
            }
            Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.INFO, "Instrumented code saved to " + className + ".class and .asm");
        } catch (IOException e) {
            Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.INFO, "Could not save instrumented code, for " + className + ".class and .asm");
        }
    }
}
 
Example 3
public byte[] transform(
        ClassLoader classLoader, String className, Class<?> classBeingRedefined,
        ProtectionDomain pd, byte[] bytes) throws IllegalClassFormatException {
    // Check if this class should be instrumented.
    if (!instrClassesTarget.contains(className)) {
        return null;
    }

    boolean isRedefinition = classBeingRedefined != null;
    log("instrument class(" + className + ") " + (isRedefinition ? "redef" : "load"));

    ClassReader reader = new ClassReader(bytes);
    ClassWriter writer = new ClassWriter(
            reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    CallbackClassVisitor classVisitor = new CallbackClassVisitor(writer);
    reader.accept(classVisitor, 0);
    instrClassesDone.add(className);
    return writer.toByteArray();
}
 
Example 4
public static ModuleTarget read(InputStream in) throws IOException {
    ModuleTargetAttribute[] modTargets = new ModuleTargetAttribute[1];
    ClassVisitor cv = new ClassVisitor(Opcodes.ASM5) {
        @Override
        public void visitAttribute(Attribute attr) {
            if (attr instanceof ModuleTargetAttribute) {
                modTargets[0] = (ModuleTargetAttribute)attr;
            }
        }
    };

    // prototype of attributes that should be parsed
    Attribute[] attrs = new Attribute[] {
        new ModuleTargetAttribute()
    };

    // parse module-info.class
    ClassReader cr = new ClassReader(in);
    cr.accept(cv, attrs, 0);
    if (modTargets[0] != null) {
        return new ModuleTarget(modTargets[0].targetPlatform());
    }

    return null;
}
 
Example 5
@Override
public ResourcePool transform(ResourcePool in, ResourcePoolBuilder out) {
    //remove *.diz files as well as debug attributes.
    in.transformAndCopy((resource) -> {
        ResourcePoolEntry res = resource;
        if (resource.type().equals(ResourcePoolEntry.Type.CLASS_OR_RESOURCE)) {
            String path = resource.path();
            if (path.endsWith(".class")) {
                if (path.endsWith("module-info.class")) {
                    // XXX. Do we have debug info? Is Asm ready for module-info?
                } else {
                    ClassReader reader = new ClassReader(resource.contentBytes());
                    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
                    reader.accept(writer, ClassReader.SKIP_DEBUG);
                    byte[] content = writer.toByteArray();
                    res = resource.copyWithContent(content);
                }
            }
        } else if (predicate.test(res.path())) {
            res = null;
        }
        return res;
    }, out);

    return out.build();
}
 
Example 6
Source Project: openjdk-jdk9   Source File: Main.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static boolean hasModuleTarget(InputStream in) throws IOException {
    ModuleTargetAttribute[] modTargets = new ModuleTargetAttribute[1];
    ClassVisitor cv = new ClassVisitor(Opcodes.ASM5) {
        @Override
        public void visitAttribute(Attribute attr) {
            if (attr instanceof ModuleTargetAttribute) {
                modTargets[0] = (ModuleTargetAttribute)attr;
            }
        }
    };

    // prototype of attributes that should be parsed
    Attribute[] attrs = new Attribute[] {
        new ModuleTargetAttribute()
    };

    // parse module-info.class
    ClassReader cr = new ClassReader(in);
    cr.accept(cv, attrs, 0);
    return modTargets[0] != null && modTargets[0].targetPlatform() != null;
}
 
Example 7
public byte[] transform(
        ClassLoader classLoader, String className, Class<?> classBeingRedefined,
        ProtectionDomain pd, byte[] bytes) throws IllegalClassFormatException {
    // Check if this class should be instrumented.
    if (!instrClassesTarget.contains(className)) {
        return null;
    }

    boolean isRedefinition = classBeingRedefined != null;
    log("instrument class(" + className + ") " + (isRedefinition ? "redef" : "load"));

    ClassReader reader = new ClassReader(bytes);
    ClassWriter writer = new ClassWriter(
            reader, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    CallbackClassVisitor classVisitor = new CallbackClassVisitor(writer);
    reader.accept(classVisitor, 0);
    instrClassesDone.add(className);
    return writer.toByteArray();
}
 
Example 8
@Override
public ResourcePool transform(ResourcePool in, ResourcePoolBuilder out) {
    in.transformAndCopy((resource) -> {
        if (resource.moduleName().equals(MODULENAME)) {
            String path = resource.path();
            resource = predicate.test(path) ? resource: null;
            if (resource != null &&
                resource.type().equals(ResourcePoolEntry.Type.CLASS_OR_RESOURCE)) {
                byte[] bytes = resource.contentBytes();
                ClassReader cr = new ClassReader(bytes);
                if (Arrays.stream(cr.getInterfaces())
                    .anyMatch(i -> i.contains(METAINFONAME)) &&
                    stripUnsupportedLocales(bytes, cr)) {
                    resource = resource.copyWithContent(bytes);
                }
            }
        }
        return resource;
    }, out);

    return out.build();
}
 
Example 9
static byte[] generateBytes(Class<?> clz, byte[] oldBytes) throws IOException {
    InputStream in = new ByteArrayInputStream(oldBytes);
    ClassReader cr = new ClassReader(in);
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ConstructorTracerWriter ctw = new ConstructorTracerWriter(cw, clz);
    cr.accept(ctw, 0);
    return cw.toByteArray();
}
 
Example 10
/**
 * External entry point for ScriptClassInfoCollector if invoked from the command line
 * @param args argument vector, args contains a class for which to collect info
 * @throws IOException if there were problems parsing args or class
 */
public static void main(final String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Usage: " + ScriptClassInfoCollector.class.getName() + " <class>");
        System.exit(1);
    }

    args[0] = args[0].replace('.', '/');
    final ScriptClassInfoCollector scic = new ScriptClassInfoCollector();
    try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0] + ".class"))) {
        final ClassReader reader = new ClassReader(bis);
        reader.accept(scic, 0);
    }
    final ScriptClassInfo sci = scic.getScriptClassInfo();
    final PrintStream out = System.out;
    if (sci != null) {
        out.println("script class: " + sci.getName());
        out.println("===================================");
        for (final MemberInfo memInfo : sci.getMembers()) {
            out.println("kind : " + memInfo.getKind());
            out.println("name : " + memInfo.getName());
            out.println("attributes: " + memInfo.getAttributes());
            out.println("javaName: " + memInfo.getJavaName());
            out.println("javaDesc: " + memInfo.getJavaDesc());
            out.println("where: " + memInfo.getWhere());
            out.println("=====================================");
        }
    } else {
        out.println(args[0] + " is not a @ScriptClass");
    }
}
 
Example 11
/**
 * Disassemble an array of byte code.
 * @param bytecode  byte array representing bytecode
 * @return disassembly as human readable string
 */
static String disassemble(final byte[] bytecode) {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (final PrintWriter pw = new PrintWriter(baos)) {
        new ClassReader(bytecode).accept(new TraceClassVisitor(pw), 0);
    }
    return new String(baos.toByteArray());
}
 
Example 12
Source Project: jdk8u-jdk   Source File: CheckClassAdapter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks a given class.
 *
 * @param cr
 *            a <code>ClassReader</code> that contains bytecode for the
 *            analysis.
 * @param loader
 *            a <code>ClassLoader</code> which will be used to load
 *            referenced classes. This is useful if you are verifiying
 *            multiple interdependent classes.
 * @param dump
 *            true if bytecode should be printed out not only when errors
 *            are found.
 * @param pw
 *            write where results going to be printed
 */
public static void verify(final ClassReader cr, final ClassLoader loader,
        final boolean dump, final PrintWriter pw) {
    ClassNode cn = new ClassNode();
    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

    Type syperType = cn.superName == null ? null : Type
            .getObjectType(cn.superName);
    List<MethodNode> methods = cn.methods;

    List<Type> interfaces = new ArrayList<Type>();
    for (Iterator<String> i = cn.interfaces.iterator(); i.hasNext();) {
        interfaces.add(Type.getObjectType(i.next()));
    }

    for (int i = 0; i < methods.size(); ++i) {
        MethodNode method = methods.get(i);
        SimpleVerifier verifier = new SimpleVerifier(
                Type.getObjectType(cn.name), syperType, interfaces,
                (cn.access & Opcodes.ACC_INTERFACE) != 0);
        Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifier);
        if (loader != null) {
            verifier.setClassLoader(loader);
        }
        try {
            a.analyze(cn.name, method);
            if (!dump) {
                continue;
            }
        } catch (Exception e) {
            e.printStackTrace(pw);
        }
        printAnalyzerResult(method, a, pw);
    }
    pw.flush();
}
 
Example 13
/**
 * Checks a given class.
 *
 * @param cr
 *            a <code>ClassReader</code> that contains bytecode for the
 *            analysis.
 * @param loader
 *            a <code>ClassLoader</code> which will be used to load
 *            referenced classes. This is useful if you are verifiying
 *            multiple interdependent classes.
 * @param dump
 *            true if bytecode should be printed out not only when errors
 *            are found.
 * @param pw
 *            write where results going to be printed
 */
public static void verify(final ClassReader cr, final ClassLoader loader,
        final boolean dump, final PrintWriter pw) {
    ClassNode cn = new ClassNode();
    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

    Type syperType = cn.superName == null ? null : Type
            .getObjectType(cn.superName);
    List<MethodNode> methods = cn.methods;

    List<Type> interfaces = new ArrayList<Type>();
    for (Iterator<String> i = cn.interfaces.iterator(); i.hasNext();) {
        interfaces.add(Type.getObjectType(i.next()));
    }

    for (int i = 0; i < methods.size(); ++i) {
        MethodNode method = methods.get(i);
        SimpleVerifier verifier = new SimpleVerifier(
                Type.getObjectType(cn.name), syperType, interfaces,
                (cn.access & Opcodes.ACC_INTERFACE) != 0);
        Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifier);
        if (loader != null) {
            verifier.setClassLoader(loader);
        }
        try {
            a.analyze(cn.name, method);
            if (!dump) {
                continue;
            }
        } catch (Exception e) {
            e.printStackTrace(pw);
        }
        printAnalyzerResult(method, a, pw);
    }
    pw.flush();
}
 
Example 14
static byte[] generateBytes(Class<?> clz, byte[] oldBytes) throws IOException {
    InputStream in = new ByteArrayInputStream(oldBytes);
    ClassReader cr = new ClassReader(in);
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    ConstructorTracerWriter ctw = new ConstructorTracerWriter(cw, clz);
    cr.accept(ctw, 0);
    return cw.toByteArray();
}
 
Example 15
private byte[] makeBytecode() throws IOException, ClassNotFoundException {

        // Find the methods to instrument and inline

        final List<Method> instrumentationMethods = new ArrayList<>();
        for (final Method m : instrumentor.getDeclaredMethods()) {
            JIInstrumentationMethod im = m.getAnnotation(JIInstrumentationMethod.class);
            if (im != null) {
                instrumentationMethods.add(m);
            }
        }

        // We begin by inlining the target's methods into the instrumentor

        ClassNode temporary = new ClassNode();
        ClassVisitor inliner = new JIInliner(
                Opcodes.ASM5,
                temporary,
                targetName,
                instrumentorName,
                targetClassReader,
                instrumentationMethods);
        instrClassReader.accept(inliner, ClassReader.EXPAND_FRAMES);

        // Now we have the target's methods inlined into the instrumentation code (in 'temporary').
        // We now need to replace the target's method with the code in the
        // instrumentation method.

        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        JIMethodMergeAdapter ma = new JIMethodMergeAdapter(
                cw,
                temporary,
                instrumentationMethods,
                instrumentor.getAnnotationsByType(JITypeMapping.class));
        targetClassReader.accept(ma, ClassReader.EXPAND_FRAMES);

       return cw.toByteArray();
    }
 
Example 16
Source Project: TencentKona-8   Source File: ASMToolkit.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void logASM(String className, byte[] bytes) {
    Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.INFO, "Generated bytecode for class " + className);
    Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.TRACE, () -> {
        ClassReader cr = new ClassReader(bytes);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintWriter w = new PrintWriter(baos);
        w.println("Bytecode:");
        cr.accept(new TraceClassVisitor(w), 0);
        return baos.toString();
    });
}
 
Example 17
/**
 * Checks a given class.
 *
 * @param cr
 *            a <code>ClassReader</code> that contains bytecode for the
 *            analysis.
 * @param loader
 *            a <code>ClassLoader</code> which will be used to load
 *            referenced classes. This is useful if you are verifiying
 *            multiple interdependent classes.
 * @param dump
 *            true if bytecode should be printed out not only when errors
 *            are found.
 * @param pw
 *            write where results going to be printed
 */
public static void verify(final ClassReader cr, final ClassLoader loader,
        final boolean dump, final PrintWriter pw) {
    ClassNode cn = new ClassNode();
    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

    Type syperType = cn.superName == null ? null : Type
            .getObjectType(cn.superName);
    List<MethodNode> methods = cn.methods;

    List<Type> interfaces = new ArrayList<Type>();
    for (Iterator<String> i = cn.interfaces.iterator(); i.hasNext();) {
        interfaces.add(Type.getObjectType(i.next()));
    }

    for (int i = 0; i < methods.size(); ++i) {
        MethodNode method = methods.get(i);
        SimpleVerifier verifier = new SimpleVerifier(
                Type.getObjectType(cn.name), syperType, interfaces,
                (cn.access & Opcodes.ACC_INTERFACE) != 0);
        Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifier);
        if (loader != null) {
            verifier.setClassLoader(loader);
        }
        try {
            a.analyze(cn.name, method);
            if (!dump) {
                continue;
            }
        } catch (Exception e) {
            e.printStackTrace(pw);
        }
        printAnalyzerResult(method, a, pw);
    }
    pw.flush();
}
 
Example 18
Source Project: openjdk-jdk9   Source File: JImageTask.java    License: GNU General Public License v2.0 5 votes vote down vote up
void verify(BasicImageReader reader, String name, ImageLocation location) {
    if (name.endsWith(".class") && !name.endsWith("module-info.class")) {
        try {
            byte[] bytes = reader.getResource(location);
            ClassReader cr = new ClassReader(bytes);
            ClassNode cn = new ClassNode();
            cr.accept(cn, 0);
        } catch (Exception ex) {
            log.println("Error(s) in Class: " + name);
        }
    }
}
 
Example 19
/**
 * External entry point for ScriptClassInfoCollector if invoked from the command line
 * @param args argument vector, args contains a class for which to collect info
 * @throws IOException if there were problems parsing args or class
 */
public static void main(final String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Usage: " + ScriptClassInfoCollector.class.getName() + " <class>");
        System.exit(1);
    }

    args[0] = args[0].replace('.', '/');
    final ScriptClassInfoCollector scic = new ScriptClassInfoCollector();
    try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0] + ".class"))) {
        final ClassReader reader = new ClassReader(bis);
        reader.accept(scic, 0);
    }
    final ScriptClassInfo sci = scic.getScriptClassInfo();
    final PrintStream out = System.out;
    if (sci != null) {
        out.println("script class: " + sci.getName());
        out.println("===================================");
        for (final MemberInfo memInfo : sci.getMembers()) {
            out.println("kind : " + memInfo.getKind());
            out.println("name : " + memInfo.getName());
            out.println("attributes: " + memInfo.getAttributes());
            out.println("javaName: " + memInfo.getJavaName());
            out.println("javaDesc: " + memInfo.getJavaDesc());
            out.println("where: " + memInfo.getWhere());
            out.println("=====================================");
        }
    } else {
        out.println(args[0] + " is not a @ScriptClass");
    }
}
 
Example 20
/**
 * External entry point for ScriptClassInfoCollector if run from the command line
 *
 * @param args arguments - one argument is needed, the name of the class to collect info from
 *
 * @throws IOException if there are problems reading class
 */
public static void main(final String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Usage: " + ScriptClassInstrumentor.class.getName() + " <class>");
        System.exit(1);
    }

    final String fileName = args[0].replace('.', '/') + ".class";
    final ScriptClassInfo sci = ClassGenerator.getScriptClassInfo(fileName);
    if (sci == null) {
        System.err.println("No @ScriptClass in " + fileName);
        System.exit(2);
        throw new AssertionError(); //guard against warning that sci is null below
    }

    try {
        sci.verify();
    } catch (final Exception e) {
        System.err.println(e.getMessage());
        System.exit(3);
    }

    final ClassWriter writer = ClassGenerator.makeClassWriter();
    try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName))) {
        final ClassReader reader = new ClassReader(bis);
        final CheckClassAdapter checker = new CheckClassAdapter(writer);
        final ScriptClassInstrumentor instr = new ScriptClassInstrumentor(checker, sci);
        reader.accept(instr, 0);
    }

    try (FileOutputStream fos = new FileOutputStream(fileName)) {
        fos.write(writer.toByteArray());
    }
}
 
Example 21
Source Project: jdk8u60   Source File: CheckClassAdapter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks a given class.
 *
 * @param cr
 *            a <code>ClassReader</code> that contains bytecode for the
 *            analysis.
 * @param loader
 *            a <code>ClassLoader</code> which will be used to load
 *            referenced classes. This is useful if you are verifiying
 *            multiple interdependent classes.
 * @param dump
 *            true if bytecode should be printed out not only when errors
 *            are found.
 * @param pw
 *            write where results going to be printed
 */
public static void verify(final ClassReader cr, final ClassLoader loader,
        final boolean dump, final PrintWriter pw) {
    ClassNode cn = new ClassNode();
    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

    Type syperType = cn.superName == null ? null : Type
            .getObjectType(cn.superName);
    List<MethodNode> methods = cn.methods;

    List<Type> interfaces = new ArrayList<Type>();
    for (Iterator<String> i = cn.interfaces.iterator(); i.hasNext();) {
        interfaces.add(Type.getObjectType(i.next()));
    }

    for (int i = 0; i < methods.size(); ++i) {
        MethodNode method = methods.get(i);
        SimpleVerifier verifier = new SimpleVerifier(
                Type.getObjectType(cn.name), syperType, interfaces,
                (cn.access & Opcodes.ACC_INTERFACE) != 0);
        Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifier);
        if (loader != null) {
            verifier.setClassLoader(loader);
        }
        try {
            a.analyze(cn.name, method);
            if (!dump) {
                continue;
            }
        } catch (Exception e) {
            e.printStackTrace(pw);
        }
        printAnalyzerResult(method, a, pw);
    }
    pw.flush();
}
 
Example 22
Source Project: hottub   Source File: RedefineAnnotations.java    License: GNU General Public License v2.0 5 votes vote down vote up
public byte[] asm(ClassLoader loader, String className,
        Class<?> classBeingRedefined,
        ProtectionDomain protectionDomain, byte[] classfileBuffer)
    throws IllegalClassFormatException {

    ClassWriter cw = new ClassWriter(0);
    ClassVisitor cv = new ReAddDummyFieldsClassVisitor(ASM5, cw) { };
    ClassReader cr = new ClassReader(classfileBuffer);
    cr.accept(cv, 0);
    return cw.toByteArray();
}
 
Example 23
/**
 * External entry point for ScriptClassInfoCollector if invoked from the command line
 * @param args argument vector, args contains a class for which to collect info
 * @throws IOException if there were problems parsing args or class
 */
public static void main(final String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Usage: " + ScriptClassInfoCollector.class.getName() + " <class>");
        System.exit(1);
    }

    args[0] = args[0].replace('.', '/');
    final ScriptClassInfoCollector scic = new ScriptClassInfoCollector();
    try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0] + ".class"))) {
        final ClassReader reader = new ClassReader(bis);
        reader.accept(scic, 0);
    }
    final ScriptClassInfo sci = scic.getScriptClassInfo();
    final PrintStream out = System.out;
    if (sci != null) {
        out.println("script class: " + sci.getName());
        out.println("===================================");
        for (final MemberInfo memInfo : sci.getMembers()) {
            out.println("kind : " + memInfo.getKind());
            out.println("name : " + memInfo.getName());
            out.println("attributes: " + memInfo.getAttributes());
            out.println("javaName: " + memInfo.getJavaName());
            out.println("javaDesc: " + memInfo.getJavaDesc());
            out.println("where: " + memInfo.getWhere());
            out.println("=====================================");
        }
    } else {
        out.println(args[0] + " is not a @ScriptClass");
    }
}
 
Example 24
/**
 * External entry point for ScriptClassInfoCollector if run from the command line
 *
 * @param args arguments - one argument is needed, the name of the class to collect info from
 *
 * @throws IOException if there are problems reading class
 */
public static void main(final String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Usage: " + ScriptClassInfoCollector.class.getName() + " <class>");
        System.exit(1);
    }

    final String fileName = args[0].replace('.', '/') + ".class";
    final ScriptClassInfo sci = ClassGenerator.getScriptClassInfo(fileName);
    if (sci == null) {
        System.err.println("No @ScriptClass in " + fileName);
        System.exit(2);
        throw new AssertionError(); //guard against warning that sci is null below
    }

    try {
        sci.verify();
    } catch (final Exception e) {
        System.err.println(e.getMessage());
        System.exit(3);
    }

    final ClassWriter writer = ClassGenerator.makeClassWriter();
    try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName))) {
        final ClassReader reader = new ClassReader(bis);
        final CheckClassAdapter checker = new CheckClassAdapter(writer);
        final ScriptClassInstrumentor instr = new ScriptClassInstrumentor(checker, sci);
        reader.accept(instr, 0);
    }

    try (FileOutputStream fos = new FileOutputStream(fileName)) {
        fos.write(writer.toByteArray());
    }
}
 
Example 25
/**
 * Checks a given class.
 *
 * @param cr
 *            a <code>ClassReader</code> that contains bytecode for the
 *            analysis.
 * @param loader
 *            a <code>ClassLoader</code> which will be used to load
 *            referenced classes. This is useful if you are verifiying
 *            multiple interdependent classes.
 * @param dump
 *            true if bytecode should be printed out not only when errors
 *            are found.
 * @param pw
 *            write where results going to be printed
 */
public static void verify(final ClassReader cr, final ClassLoader loader,
        final boolean dump, final PrintWriter pw) {
    ClassNode cn = new ClassNode();
    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

    Type syperType = cn.superName == null ? null : Type
            .getObjectType(cn.superName);
    List<MethodNode> methods = cn.methods;

    List<Type> interfaces = new ArrayList<Type>();
    for (Iterator<String> i = cn.interfaces.iterator(); i.hasNext();) {
        interfaces.add(Type.getObjectType(i.next()));
    }

    for (int i = 0; i < methods.size(); ++i) {
        MethodNode method = methods.get(i);
        SimpleVerifier verifier = new SimpleVerifier(
                Type.getObjectType(cn.name), syperType, interfaces,
                (cn.access & Opcodes.ACC_INTERFACE) != 0);
        Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifier);
        if (loader != null) {
            verifier.setClassLoader(loader);
        }
        try {
            a.analyze(cn.name, method);
            if (!dump) {
                continue;
            }
        } catch (Exception e) {
            e.printStackTrace(pw);
        }
        printAnalyzerResult(method, a, pw);
    }
    pw.flush();
}
 
Example 26
/**
 * External entry point for ScriptClassInfoCollector if invoked from the command line
 * @param args argument vector, args contains a class for which to collect info
 * @throws IOException if there were problems parsing args or class
 */
public static void main(final String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Usage: " + ScriptClassInfoCollector.class.getName() + " <class>");
        System.exit(1);
    }

    args[0] = args[0].replace('.', '/');
    final ScriptClassInfoCollector scic = new ScriptClassInfoCollector();
    try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0] + ".class"))) {
        final ClassReader reader = new ClassReader(bis);
        reader.accept(scic, 0);
    }
    final ScriptClassInfo sci = scic.getScriptClassInfo();
    final PrintStream out = System.out;
    if (sci != null) {
        out.println("script class: " + sci.getName());
        out.println("===================================");
        for (final MemberInfo memInfo : sci.getMembers()) {
            out.println("kind : " + memInfo.getKind());
            out.println("name : " + memInfo.getName());
            out.println("attributes: " + memInfo.getAttributes());
            out.println("javaName: " + memInfo.getJavaName());
            out.println("javaDesc: " + memInfo.getJavaDesc());
            out.println("where: " + memInfo.getWhere());
            out.println("=====================================");
        }
    } else {
        out.println(args[0] + " is not a @ScriptClass");
    }
}
 
Example 27
Source Project: openjdk-jdk8u   Source File: JIInliner.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * A ClassVisitor which will check all methods of the class it visits against the instrumentationMethods
 * list. If a method is on that list, the method will be further processed for inlining into that
 * method.
 */
JIInliner(int api, ClassVisitor cv, String targetClassName, String instrumentationClassName,
        ClassReader targetClassReader,
        List<Method> instrumentationMethods) {
    super(api, cv);
    this.targetClassName = targetClassName;
    this.instrumentationClassName = instrumentationClassName;
    this.instrumentationMethods = instrumentationMethods;

    ClassNode cn = new ClassNode(Opcodes.ASM5);
    targetClassReader.accept(cn, ClassReader.EXPAND_FRAMES);
    this.targetClassNode = cn;
}
 
Example 28
Source Project: openjdk-jdk8u   Source File: ASMToolkit.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void logASM(String className, byte[] bytes) {
    Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.INFO, "Generated bytecode for class " + className);
    Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.TRACE, () -> {
        ClassReader cr = new ClassReader(bytes);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintWriter w = new PrintWriter(baos);
        w.println("Bytecode:");
        cr.accept(new TraceClassVisitor(w), 0);
        return baos.toString();
    });
}
 
Example 29
/**
 * Checks a given class.
 *
 * @param cr
 *            a <code>ClassReader</code> that contains bytecode for the
 *            analysis.
 * @param loader
 *            a <code>ClassLoader</code> which will be used to load
 *            referenced classes. This is useful if you are verifiying
 *            multiple interdependent classes.
 * @param dump
 *            true if bytecode should be printed out not only when errors
 *            are found.
 * @param pw
 *            write where results going to be printed
 */
public static void verify(final ClassReader cr, final ClassLoader loader,
        final boolean dump, final PrintWriter pw) {
    ClassNode cn = new ClassNode();
    cr.accept(new CheckClassAdapter(cn, false), ClassReader.SKIP_DEBUG);

    Type syperType = cn.superName == null ? null : Type
            .getObjectType(cn.superName);
    List<MethodNode> methods = cn.methods;

    List<Type> interfaces = new ArrayList<Type>();
    for (Iterator<String> i = cn.interfaces.iterator(); i.hasNext();) {
        interfaces.add(Type.getObjectType(i.next()));
    }

    for (int i = 0; i < methods.size(); ++i) {
        MethodNode method = methods.get(i);
        SimpleVerifier verifier = new SimpleVerifier(
                Type.getObjectType(cn.name), syperType, interfaces,
                (cn.access & Opcodes.ACC_INTERFACE) != 0);
        Analyzer<BasicValue> a = new Analyzer<BasicValue>(verifier);
        if (loader != null) {
            verifier.setClassLoader(loader);
        }
        try {
            a.analyze(cn.name, method);
            if (!dump) {
                continue;
            }
        } catch (Exception e) {
            e.printStackTrace(pw);
        }
        printAnalyzerResult(method, a, pw);
    }
    pw.flush();
}
 
Example 30
/**
 * External entry point for ScriptClassInfoCollector if run from the command line
 *
 * @param args arguments - one argument is needed, the name of the class to collect info from
 *
 * @throws IOException if there are problems reading class
 */
public static void main(final String[] args) throws IOException {
    if (args.length != 1) {
        System.err.println("Usage: " + ScriptClassInfoCollector.class.getName() + " <class>");
        System.exit(1);
    }

    final String fileName = args[0].replace('.', '/') + ".class";
    final ScriptClassInfo sci = ClassGenerator.getScriptClassInfo(fileName);
    if (sci == null) {
        System.err.println("No @ScriptClass in " + fileName);
        System.exit(2);
        throw new AssertionError(); //guard against warning that sci is null below
    }

    try {
        sci.verify();
    } catch (final Exception e) {
        System.err.println(e.getMessage());
        System.exit(3);
    }

    final ClassWriter writer = ClassGenerator.makeClassWriter();
    try (final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName))) {
        final ClassReader reader = new ClassReader(bis);
        final CheckClassAdapter checker = new CheckClassAdapter(writer);
        final ScriptClassInstrumentor instr = new ScriptClassInstrumentor(checker, sci);
        reader.accept(instr, 0);
    }

    try (FileOutputStream fos = new FileOutputStream(fileName)) {
        fos.write(writer.toByteArray());
    }
}