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

The following examples show how to use jdk.internal.org.objectweb.asm.ClassReader. 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
Source File: TestInstrumentation.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 File: Utils.java    From TencentKona-8 with 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
Source File: TestInstrumentation.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: Main.java    From openjdk-jdk9 with 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 #5
Source File: ModuleTargetHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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 #6
Source File: IncludeLocalesPlugin.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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 #7
Source File: CheckClassAdapter.java    From dragonwell8_jdk with GNU General Public License v2.0 6 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 #8
Source File: StripDebugPlugin.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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 #9
Source File: TestInstrumentation.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 #10
Source File: ScriptClassInfoCollector.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
Source File: ConstructorTracerWriter.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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 #12
Source File: CheckClassAdapter.java    From openjdk-8-source with 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
Source File: RedefineAnnotations.java    From hottub with 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 #14
Source File: ScriptClassInfoCollector.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #15
Source File: ScriptClassInstrumentor.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #16
Source File: CheckClassAdapter.java    From jdk8u60 with 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 #17
Source File: Printer.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
  * Prints a the given class to the standard output.
  *
  * <p>Command line arguments: [-debug] &lt;binary class name or class file name &gt;
  *
  * @param usage the help message to show when command line arguments are incorrect.
  * @param printer the printer to convert the class into text.
  * @param args the command line arguments.
  * @throws IOException if the class cannot be found, or if an IOException occurs.
  */
static void main(final String usage, final Printer printer, final String[] args)
        throws IOException {
    if (args.length < 1 || args.length > 2 || (args[0].equals("-debug") && args.length != 2)) {
        System.err.println(usage);
        return;
    }

    TraceClassVisitor traceClassVisitor =
            new TraceClassVisitor(null, printer, new PrintWriter(System.out));

    String className;
    int parsingOptions;
    if (args[0].equals("-debug")) {
        className = args[1];
        parsingOptions = ClassReader.SKIP_DEBUG;
    } else {
        className = args[0];
        parsingOptions = 0;
    }

    if (className.endsWith(".class")
            || className.indexOf('\\') != -1
            || className.indexOf('/') != -1) {
        InputStream inputStream =
                new FileInputStream(className); // NOPMD(AvoidFileStream): can't fix for 1.5 compatibility
        new ClassReader(inputStream).accept(traceClassVisitor, parsingOptions);
    } else {
        new ClassReader(className).accept(traceClassVisitor, parsingOptions);
    }
}
 
Example #18
Source File: ASMToolkit.java    From TencentKona-8 with 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 #19
Source File: CheckClassAdapter.java    From jdk8u-dev-jdk with 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 #20
Source File: CheckClassAdapter.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
  * Checks the given class.
  *
  * @param classReader the class to be checked.
  * @param loader a <code>ClassLoader</code> which will be used to load referenced classes. May be
  *     {@literal null}.
  * @param printResults whether to print the results of the bytecode verification.
  * @param printWriter where the results (or the stack trace in case of error) must be printed.
  */
public static void verify(
        final ClassReader classReader,
        final ClassLoader loader,
        final boolean printResults,
        final PrintWriter printWriter) {
    ClassNode classNode = new ClassNode();
    classReader.accept(
            new CheckClassAdapter(Opcodes.ASM7, classNode, false) {}, ClassReader.SKIP_DEBUG);

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

    List<Type> interfaces = new ArrayList<Type>();
    for (String interfaceName : classNode.interfaces) {
        interfaces.add(Type.getObjectType(interfaceName));
    }

    for (MethodNode method : methods) {
        SimpleVerifier verifier =
                new SimpleVerifier(
                        Type.getObjectType(classNode.name),
                        syperType,
                        interfaces,
                        (classNode.access & Opcodes.ACC_INTERFACE) != 0);
        Analyzer<BasicValue> analyzer = new Analyzer<BasicValue>(verifier);
        if (loader != null) {
            verifier.setClassLoader(loader);
        }
        try {
            analyzer.analyze(classNode.name, method);
        } catch (AnalyzerException e) {
            e.printStackTrace(printWriter);
        }
        if (printResults) {
            printAnalyzerResult(method, analyzer, printWriter);
        }
    }
    printWriter.flush();
}
 
Example #21
Source File: ScriptClassInstrumentor.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #22
Source File: ScriptClassInfoCollector.java    From nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #23
Source File: JIInliner.java    From openjdk-jdk8u with 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 #24
Source File: ASMToolkit.java    From openjdk-jdk8u with 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 #25
Source File: ModuleHashesAttribute.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Override
protected Attribute read(
        final ClassReader classReader,
        final int offset,
        final int length,
        final char[] charBuffer,
        final int codeAttributeOffset,
        final Label[] labels) {
    int currentOffset = offset;

    String hashAlgorithm = classReader.readUTF8(currentOffset, charBuffer);
    currentOffset += 2;

    int numModules = classReader.readUnsignedShort(currentOffset);
    currentOffset += 2;

    ArrayList<String> moduleList = new ArrayList<String>(numModules);
    ArrayList<byte[]> hashList = new ArrayList<byte[]>(numModules);

    for (int i = 0; i < numModules; ++i) {
        String module = classReader.readModule(currentOffset, charBuffer);
        currentOffset += 2;
        moduleList.add(module);

        int hashLength = classReader.readUnsignedShort(currentOffset);
        currentOffset += 2;
        byte[] hash = new byte[hashLength];
        for (int j = 0; j < hashLength; ++j) {
            hash[j] = (byte) (classReader.readByte(currentOffset) & 0xFF);
            currentOffset += 1;
        }
        hashList.add(hash);
    }
    return new ModuleHashesAttribute(hashAlgorithm, moduleList, hashList);
}
 
Example #26
Source File: CheckClassAdapter.java    From openjdk-jdk8u with 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 #27
Source File: ScriptClassInfoCollector.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #28
Source File: ScriptClassInstrumentor.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #29
Source File: CheckClassAdapter.java    From jdk8u_jdk with 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 #30
Source File: CheckClassAdapter.java    From openjdk-jdk9 with 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();
}