jdk.internal.org.objectweb.asm.tree.MethodNode Java Examples

The following examples show how to use jdk.internal.org.objectweb.asm.tree.MethodNode. 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: JIMethodMergeAdapter.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visitEnd() {
    SimpleRemapper remapper = new SimpleRemapper(typeMap);
    for (MethodNode mn : cn.methods) {
        // Check if the method is in the list of methods to copy
        if (methodInFilter(mn.name, mn.desc)) {
            Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.DEBUG, "Copying method: " + mn.name + mn.desc);
            Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.DEBUG,  "   with mapper: " + typeMap);

            String[] exceptions = new String[mn.exceptions.size()];
            mn.exceptions.toArray(exceptions);
            MethodVisitor mv = cv.visitMethod(mn.access, mn.name, mn.desc, mn.signature, exceptions);
            mn.instructions.resetLabels();
            mn.accept(new RemappingMethodAdapter(mn.access, mn.desc, mv, remapper));
        }
    }
    super.visitEnd();
}
 
Example #2
Source File: JIMethodMergeAdapter.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visitEnd() {
    SimpleRemapper remapper = new SimpleRemapper(typeMap);
    for (MethodNode mn : cn.methods) {
        // Check if the method is in the list of methods to copy
        if (methodInFilter(mn.name, mn.desc)) {
            Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.DEBUG, "Copying method: " + mn.name + mn.desc);
            Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.DEBUG,  "   with mapper: " + typeMap);

            String[] exceptions = new String[mn.exceptions.size()];
            mn.exceptions.toArray(exceptions);
            MethodVisitor mv = cv.visitMethod(mn.access, mn.name, mn.desc, mn.signature, exceptions);
            mn.instructions.resetLabels();
            mn.accept(new RemappingMethodAdapter(mn.access, mn.desc, mv, remapper));
        }
    }
    super.visitEnd();
}
 
Example #3
Source File: JIInliner.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

    if (isInstrumentationMethod(name, desc)) {
        MethodNode methodToInline = findTargetMethodNode(name, desc);
        if (methodToInline == null) {
            throw new IllegalArgumentException("Could not find the method to instrument in the target class");
        }
        if (Modifier.isNative(methodToInline.access)) {
            throw new IllegalArgumentException("Cannot instrument native methods: " + targetClassNode.name + "." + methodToInline.name + methodToInline.desc);
        }

        Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.DEBUG, "Inliner processing method " + name + desc);

        JIMethodCallInliner mci = new JIMethodCallInliner(access,
                desc,
                mv,
                methodToInline,
                targetClassName,
                instrumentationClassName);
        return mci;
    }

    return mv;
}
 
Example #4
Source File: JIInliner.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

    if (isInstrumentationMethod(name, desc)) {
        MethodNode methodToInline = findTargetMethodNode(name, desc);
        if (methodToInline == null) {
            throw new IllegalArgumentException("Could not find the method to instrument in the target class");
        }
        if (Modifier.isNative(methodToInline.access)) {
            throw new IllegalArgumentException("Cannot instrument native methods: " + targetClassNode.name + "." + methodToInline.name + methodToInline.desc);
        }

        Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.DEBUG, "Inliner processing method " + name + desc);

        JIMethodCallInliner mci = new JIMethodCallInliner(access,
                desc,
                mv,
                methodToInline,
                targetClassName,
                instrumentationClassName);
        return mci;
    }

    return mv;
}
 
Example #5
Source File: JIMethodMergeAdapter.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void visitEnd() {
    SimpleRemapper remapper = new SimpleRemapper(typeMap);
    for (MethodNode mn : cn.methods) {
        // Check if the method is in the list of methods to copy
        if (methodInFilter(mn.name, mn.desc)) {
            Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.DEBUG, "Copying method: " + mn.name + mn.desc);
            Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.DEBUG,  "   with mapper: " + typeMap);

            String[] exceptions = new String[mn.exceptions.size()];
            mn.exceptions.toArray(exceptions);
            MethodVisitor mv = cv.visitMethod(mn.access, mn.name, mn.desc, mn.signature, exceptions);
            mn.instructions.resetLabels();
            mn.accept(new RemappingMethodAdapter(mn.access, mn.desc, mv, remapper));
        }
    }
    super.visitEnd();
}
 
Example #6
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 #7
Source File: JIInliner.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
    MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

    if (isInstrumentationMethod(name, desc)) {
        MethodNode methodToInline = findTargetMethodNode(name, desc);
        if (methodToInline == null) {
            throw new IllegalArgumentException("Could not find the method to instrument in the target class");
        }
        if (Modifier.isNative(methodToInline.access)) {
            throw new IllegalArgumentException("Cannot instrument native methods: " + targetClassNode.name + "." + methodToInline.name + methodToInline.desc);
        }

        Logger.log(LogTag.JFR_SYSTEM_BYTECODE, LogLevel.DEBUG, "Inliner processing method " + name + desc);

        JIMethodCallInliner mci = new JIMethodCallInliner(access,
                desc,
                mv,
                methodToInline,
                targetClassName,
                instrumentationClassName);
        return mci;
    }

    return mv;
}
 
Example #8
Source File: TinyInstrumentor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return a {@link MethodNode} called {@code methodName} in the given class.
 */
private static MethodNode getMethodNode(Class<?> clazz, String methodName) throws IOException {
    ClassReader classReader = new ClassReader(clazz.getName());
    ClassNode classNode = new ClassNode();
    classReader.accept(classNode, ClassReader.SKIP_FRAMES);

    for (MethodNode methodNode : classNode.methods) {
        if (methodNode.name.equals(methodName)) {
            return methodNode;
        }
    }
    return null;
}
 
Example #9
Source File: FieldOn.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
private Field readFieldFromByteCode() {
    try {
        ClassNode classNode = Asm.classNode(getClass());
        MethodNode constructor = classNode.methods.get(0);
        FieldInsnNode fieldInsnNode = Asm.instructions(constructor).safeCast(FieldInsnNode.class).last();
        Class<?> aClass = forName(fieldInsnNode.owner.replace('/', '.'));
        return fields(aClass).
                find(where(name, is(fieldInsnNode.name))).
                get();
    } catch (Exception e) {
        throw lazyException(e);
    }
}
 
Example #10
Source File: CheckMethodAdapter.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a new {@link CheckMethodAdapter} object. This method adapter
 * will perform basic data flow checks. For instance in a method whose
 * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the
 * invalid sequence IADD L2I will be detected.
 *
 * @param access
 *            the method's access flags.
 * @param name
 *            the method's name.
 * @param desc
 *            the method's descriptor (see {@link Type Type}).
 * @param cmv
 *            the method visitor to which this adapter must delegate calls.
 * @param labels
 *            a map of already visited labels (in other methods).
 */
public CheckMethodAdapter(final int access, final String name,
        final String desc, final MethodVisitor cmv,
        final Map<Label, Integer> labels) {
    this(new MethodNode(Opcodes.ASM5, access, name, desc, null, null) {
        @Override
        public void visitEnd() {
            Analyzer<BasicValue> a = new Analyzer<BasicValue>(
                    new BasicVerifier());
            try {
                a.analyze("dummy", this);
            } catch (Exception e) {
                if (e instanceof IndexOutOfBoundsException
                        && maxLocals == 0 && maxStack == 0) {
                    throw new RuntimeException(
                            "Data flow checking option requires valid, non zero maxLocals and maxStack values.");
                }
                e.printStackTrace();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                CheckClassAdapter.printAnalyzerResult(this, a, pw);
                pw.close();
                throw new RuntimeException(e.getMessage() + ' '
                        + sw.toString());
            }
            accept(cmv);
        }
    }, labels);
    this.access = access;
}
 
Example #11
Source File: CheckMethodAdapter.java    From nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a new {@link CheckMethodAdapter} object. This method adapter
 * will perform basic data flow checks. For instance in a method whose
 * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the
 * invalid sequence IADD L2I will be detected.
 *
 * @param access the method's access flags.
 * @param name the method's name.
 * @param desc the method's descriptor (see {@link Type Type}).
 * @param cmv the method visitor to which this adapter must delegate calls.
 * @param labels a map of already visited labels (in other methods).
 */
public CheckMethodAdapter(
    final int access,
    final String name,
    final String desc,
    final MethodVisitor cmv,
    final Map<Label, Integer> labels)
{
    this(new MethodNode(access, name, desc, null, null) {
        @Override
        public void visitEnd() {
            Analyzer<BasicValue> a = new Analyzer<BasicValue>(new BasicVerifier());
            try {
                a.analyze("dummy", this);
            } catch (Exception e) {
                if (e instanceof IndexOutOfBoundsException
                        && maxLocals == 0 && maxStack == 0)
                {
                    throw new RuntimeException("Data flow checking option requires valid, non zero maxLocals and maxStack values.");
                }
                e.printStackTrace();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                CheckClassAdapter.printAnalyzerResult(this, a, pw);
                pw.close();
                throw new RuntimeException(e.getMessage() + ' '
                        + sw.toString());
            }
            accept(cmv);
        }
    },
            labels);
}
 
Example #12
Source File: CheckClassAdapter.java    From openjdk-8 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: CheckClassAdapter.java    From hottub 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 #14
Source File: CheckClassAdapter.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void printAnalyzerResult(MethodNode method, Analyzer<BasicValue> a,
        final PrintWriter pw) {
    Frame<BasicValue>[] frames = a.getFrames();
    Textifier t = new Textifier();
    TraceMethodVisitor mv = new TraceMethodVisitor(t);

    pw.println(method.name + method.desc);
    for (int j = 0; j < method.instructions.size(); ++j) {
        method.instructions.get(j).accept(mv);

        StringBuilder sb = new StringBuilder();
        Frame<BasicValue> f = frames[j];
        if (f == null) {
            sb.append('?');
        } else {
            for (int k = 0; k < f.getLocals(); ++k) {
                sb.append(getShortName(f.getLocal(k).toString()))
                        .append(' ');
            }
            sb.append(" : ");
            for (int k = 0; k < f.getStackSize(); ++k) {
                sb.append(getShortName(f.getStack(k).toString()))
                        .append(' ');
            }
        }
        while (sb.length() < method.maxStack + method.maxLocals + 1) {
            sb.append(' ');
        }
        pw.print(Integer.toString(j + 100000).substring(1));
        pw.print(" " + sb + " : " + t.text.get(t.text.size() - 1));
    }
    for (int j = 0; j < method.tryCatchBlocks.size(); ++j) {
        method.tryCatchBlocks.get(j).accept(mv);
        pw.print(" " + t.text.get(t.text.size() - 1));
    }
    pw.println();
}
 
Example #15
Source File: CheckMethodAdapter.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a new {@link CheckMethodAdapter} object. This method adapter
 * will perform basic data flow checks. For instance in a method whose
 * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the
 * invalid sequence IADD L2I will be detected.
 *
 * @param access
 *            the method's access flags.
 * @param name
 *            the method's name.
 * @param desc
 *            the method's descriptor (see {@link Type Type}).
 * @param cmv
 *            the method visitor to which this adapter must delegate calls.
 * @param labels
 *            a map of already visited labels (in other methods).
 */
public CheckMethodAdapter(final int access, final String name,
        final String desc, final MethodVisitor cmv,
        final Map<Label, Integer> labels) {
    this(new MethodNode(Opcodes.ASM5, access, name, desc, null, null) {
        @Override
        public void visitEnd() {
            Analyzer<BasicValue> a = new Analyzer<BasicValue>(
                    new BasicVerifier());
            try {
                a.analyze("dummy", this);
            } catch (Exception e) {
                if (e instanceof IndexOutOfBoundsException
                        && maxLocals == 0 && maxStack == 0) {
                    throw new RuntimeException(
                            "Data flow checking option requires valid, non zero maxLocals and maxStack values.");
                }
                e.printStackTrace();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                CheckClassAdapter.printAnalyzerResult(this, a, pw);
                pw.close();
                throw new RuntimeException(e.getMessage() + ' '
                        + sw.toString());
            }
            accept(cmv);
        }
    }, labels);
    this.access = access;
}
 
Example #16
Source File: CheckMethodAdapter.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a new {@link CheckMethodAdapter} object. This method adapter
 * will perform basic data flow checks. For instance in a method whose
 * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the
 * invalid sequence IADD L2I will be detected.
 *
 * @param access
 *            the method's access flags.
 * @param name
 *            the method's name.
 * @param desc
 *            the method's descriptor (see {@link Type Type}).
 * @param cmv
 *            the method visitor to which this adapter must delegate calls.
 * @param labels
 *            a map of already visited labels (in other methods).
 */
public CheckMethodAdapter(final int access, final String name,
        final String desc, final MethodVisitor cmv,
        final Map<Label, Integer> labels) {
    this(new MethodNode(Opcodes.ASM5, access, name, desc, null, null) {
        @Override
        public void visitEnd() {
            Analyzer<BasicValue> a = new Analyzer<BasicValue>(
                    new BasicVerifier());
            try {
                a.analyze("dummy", this);
            } catch (Exception e) {
                if (e instanceof IndexOutOfBoundsException
                        && maxLocals == 0 && maxStack == 0) {
                    throw new RuntimeException(
                            "Data flow checking option requires valid, non zero maxLocals and maxStack values.");
                }
                e.printStackTrace();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                CheckClassAdapter.printAnalyzerResult(this, a, pw);
                pw.close();
                throw new RuntimeException(e.getMessage() + ' '
                        + sw.toString());
            }
            accept(cmv);
        }
    }, labels);
    this.access = access;
}
 
Example #17
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 #18
Source File: CheckMethodAdapter.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a new {@link CheckMethodAdapter} object. This method adapter
 * will perform basic data flow checks. For instance in a method whose
 * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the
 * invalid sequence IADD L2I will be detected.
 *
 * @param access
 *            the method's access flags.
 * @param name
 *            the method's name.
 * @param desc
 *            the method's descriptor (see {@link Type Type}).
 * @param cmv
 *            the method visitor to which this adapter must delegate calls.
 * @param labels
 *            a map of already visited labels (in other methods).
 */
public CheckMethodAdapter(final int access, final String name,
        final String desc, final MethodVisitor cmv,
        final Map<Label, Integer> labels) {
    this(new MethodNode(Opcodes.ASM5, access, name, desc, null, null) {
        @Override
        public void visitEnd() {
            Analyzer<BasicValue> a = new Analyzer<BasicValue>(
                    new BasicVerifier());
            try {
                a.analyze("dummy", this);
            } catch (Exception e) {
                if (e instanceof IndexOutOfBoundsException
                        && maxLocals == 0 && maxStack == 0) {
                    throw new RuntimeException(
                            "Data flow checking option requires valid, non zero maxLocals and maxStack values.");
                }
                e.printStackTrace();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                CheckClassAdapter.printAnalyzerResult(this, a, pw);
                pw.close();
                throw new RuntimeException(e.getMessage() + ' '
                        + sw.toString());
            }
            accept(cmv);
        }
    }, labels);
    this.access = access;
}
 
Example #19
Source File: TinyInstrumentor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public Class<?> instrument(Class<?> targetClass, String methodName, int opcode, boolean insertAfter) throws IOException, ClassNotFoundException {
    // create a container class
    String className = targetClass.getName() + "$$" + methodName;
    ClassNode classNode = emptyClass(className);
    // duplicate the target method and add to the container class
    MethodNode methodNode = getMethodNode(targetClass, methodName);
    MethodNode newMethodNode = new MethodNode(methodNode.access, methodNode.name, methodNode.desc, methodNode.signature, methodNode.exceptions.toArray(new String[methodNode.exceptions.size()]));
    methodNode.accept(newMethodNode);
    classNode.methods.add(newMethodNode);
    // perform bytecode instrumentation
    for (AbstractInsnNode instruction : selectAll(newMethodNode.instructions)) {
        if (instruction.getOpcode() == opcode) {
            InsnList instrumentation = cloneInstructions(instrumentationInstructions);
            shiftLocalSlots(instrumentation, newMethodNode.maxLocals);
            newMethodNode.maxLocals += instrumentationMaxLocal;
            if (insertAfter) {
                newMethodNode.instructions.insert(instruction, instrumentation);
            } else {
                newMethodNode.instructions.insertBefore(instruction, instrumentation);
            }
        }
    }
    // dump a byte array and load the class with a dedicated loader to separate the namespace
    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    classNode.accept(classWriter);
    byte[] bytes = classWriter.toByteArray();
    return new Loader(className, bytes).findClass(className);
}
 
Example #20
Source File: CheckClassAdapter.java    From openjdk-jdk8u-backup 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 #21
Source File: CheckClassAdapter.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
static void printAnalyzerResult(
        final MethodNode method, final Analyzer<BasicValue> analyzer, final PrintWriter printWriter) {
    Textifier textifier = new Textifier();
    TraceMethodVisitor traceMethodVisitor = new TraceMethodVisitor(textifier);

    printWriter.println(method.name + method.desc);
    for (int i = 0; i < method.instructions.size(); ++i) {
        method.instructions.get(i).accept(traceMethodVisitor);

        StringBuilder stringBuilder = new StringBuilder();
        Frame<BasicValue> frame = analyzer.getFrames()[i];
        if (frame == null) {
            stringBuilder.append('?');
        } else {
            for (int j = 0; j < frame.getLocals(); ++j) {
                stringBuilder.append(getUnqualifiedName(frame.getLocal(j).toString())).append(' ');
            }
            stringBuilder.append(" : ");
            for (int j = 0; j < frame.getStackSize(); ++j) {
                stringBuilder.append(getUnqualifiedName(frame.getStack(j).toString())).append(' ');
            }
        }
        while (stringBuilder.length() < method.maxStack + method.maxLocals + 1) {
            stringBuilder.append(' ');
        }
        printWriter.print(Integer.toString(i + 100000).substring(1));
        printWriter.print(
                " " + stringBuilder + " : " + textifier.text.get(textifier.text.size() - 1));
    }
    for (TryCatchBlockNode tryCatchBlock : method.tryCatchBlocks) {
        tryCatchBlock.accept(traceMethodVisitor);
        printWriter.print(" " + textifier.text.get(textifier.text.size() - 1));
    }
    printWriter.println();
}
 
Example #22
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 #23
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 #24
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 #25
Source File: CheckClassAdapter.java    From nashorn with GNU General Public License v2.0 5 votes vote down vote up
static void printAnalyzerResult(
    MethodNode method,
    Analyzer<BasicValue> a,
    final PrintWriter pw)
{
    Frame<BasicValue>[] frames = a.getFrames();
    Textifier t = new Textifier();
    TraceMethodVisitor mv = new TraceMethodVisitor(t);

    pw.println(method.name + method.desc);
    for (int j = 0; j < method.instructions.size(); ++j) {
        method.instructions.get(j).accept(mv);

        StringBuffer s = new StringBuffer();
        Frame<BasicValue> f = frames[j];
        if (f == null) {
            s.append('?');
        } else {
            for (int k = 0; k < f.getLocals(); ++k) {
                s.append(getShortName(f.getLocal(k).toString()))
                        .append(' ');
            }
            s.append(" : ");
            for (int k = 0; k < f.getStackSize(); ++k) {
                s.append(getShortName(f.getStack(k).toString()))
                        .append(' ');
            }
        }
        while (s.length() < method.maxStack + method.maxLocals + 1) {
            s.append(' ');
        }
        pw.print(Integer.toString(j + 100000).substring(1));
        pw.print(" " + s + " : " + t.text.get(t.text.size() - 1));
    }
    for (int j = 0; j < method.tryCatchBlocks.size(); ++j) {
        method.tryCatchBlocks.get(j).accept(mv);
        pw.print(" " + t.text.get(t.text.size() - 1));
    }
    pw.println();
}
 
Example #26
Source File: Analyzer.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
  * Computes the initial execution stack frame of the given method.
  *
  * @param owner the internal name of the class to which 'method' belongs.
  * @param method the method to be analyzed.
  * @return the initial execution stack frame of the 'method'.
  */
private Frame<V> computeInitialFrame(final String owner, final MethodNode method) {
    Frame<V> frame = newFrame(method.maxLocals, method.maxStack);
    int currentLocal = 0;
    boolean isInstanceMethod = (method.access & ACC_STATIC) == 0;
    if (isInstanceMethod) {
        Type ownerType = Type.getObjectType(owner);
        frame.setLocal(
                currentLocal, interpreter.newParameterValue(isInstanceMethod, currentLocal, ownerType));
        currentLocal++;
    }
    Type[] argumentTypes = Type.getArgumentTypes(method.desc);
    for (Type argumentType : argumentTypes) {
        frame.setLocal(
                currentLocal,
                interpreter.newParameterValue(isInstanceMethod, currentLocal, argumentType));
        currentLocal++;
        if (argumentType.getSize() == 2) {
            frame.setLocal(currentLocal, interpreter.newEmptyValue(currentLocal));
            currentLocal++;
        }
    }
    while (currentLocal < method.maxLocals) {
        frame.setLocal(currentLocal, interpreter.newEmptyValue(currentLocal));
        currentLocal++;
    }
    frame.setReturn(interpreter.newReturnTypeValue(Type.getReturnType(method.desc)));
    return frame;
}
 
Example #27
Source File: CheckMethodAdapter.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a new {@link CheckMethodAdapter} object. This method adapter
 * will perform basic data flow checks. For instance in a method whose
 * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the
 * invalid sequence IADD L2I will be detected.
 *
 * @param access
 *            the method's access flags.
 * @param name
 *            the method's name.
 * @param desc
 *            the method's descriptor (see {@link Type Type}).
 * @param cmv
 *            the method visitor to which this adapter must delegate calls.
 * @param labels
 *            a map of already visited labels (in other methods).
 */
public CheckMethodAdapter(final int access, final String name,
        final String desc, final MethodVisitor cmv,
        final Map<Label, Integer> labels) {
    this(new MethodNode(Opcodes.ASM5, access, name, desc, null, null) {
        @Override
        public void visitEnd() {
            Analyzer<BasicValue> a = new Analyzer<BasicValue>(
                    new BasicVerifier());
            try {
                a.analyze("dummy", this);
            } catch (Exception e) {
                if (e instanceof IndexOutOfBoundsException
                        && maxLocals == 0 && maxStack == 0) {
                    throw new RuntimeException(
                            "Data flow checking option requires valid, non zero maxLocals and maxStack values.");
                }
                e.printStackTrace();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                CheckClassAdapter.printAnalyzerResult(this, a, pw);
                pw.close();
                throw new RuntimeException(e.getMessage() + ' '
                        + sw.toString());
            }
            accept(cmv);
        }
    }, labels);
    this.access = access;
}
 
Example #28
Source File: CheckMethodAdapter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a new {@link CheckMethodAdapter} object. This method adapter
 * will perform basic data flow checks. For instance in a method whose
 * signature is <tt>void m ()</tt>, the invalid instruction IRETURN, or the
 * invalid sequence IADD L2I will be detected.
 *
 * @param access
 *            the method's access flags.
 * @param name
 *            the method's name.
 * @param desc
 *            the method's descriptor (see {@link Type Type}).
 * @param cmv
 *            the method visitor to which this adapter must delegate calls.
 * @param labels
 *            a map of already visited labels (in other methods).
 */
public CheckMethodAdapter(final int access, final String name,
        final String desc, final MethodVisitor cmv,
        final Map<Label, Integer> labels) {
    this(new MethodNode(Opcodes.ASM5, access, name, desc, null, null) {
        @Override
        public void visitEnd() {
            Analyzer<BasicValue> a = new Analyzer<BasicValue>(
                    new BasicVerifier());
            try {
                a.analyze("dummy", this);
            } catch (Exception e) {
                if (e instanceof IndexOutOfBoundsException
                        && maxLocals == 0 && maxStack == 0) {
                    throw new RuntimeException(
                            "Data flow checking option requires valid, non zero maxLocals and maxStack values.");
                }
                e.printStackTrace();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw, true);
                CheckClassAdapter.printAnalyzerResult(this, a, pw);
                pw.close();
                throw new RuntimeException(e.getMessage() + ' '
                        + sw.toString());
            }
            accept(cmv);
        }
    }, labels);
    this.access = access;
}
 
Example #29
Source File: CheckClassAdapter.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static void printAnalyzerResult(MethodNode method, Analyzer<BasicValue> a,
        final PrintWriter pw) {
    Frame<BasicValue>[] frames = a.getFrames();
    Textifier t = new Textifier();
    TraceMethodVisitor mv = new TraceMethodVisitor(t);

    pw.println(method.name + method.desc);
    for (int j = 0; j < method.instructions.size(); ++j) {
        method.instructions.get(j).accept(mv);

        StringBuilder sb = new StringBuilder();
        Frame<BasicValue> f = frames[j];
        if (f == null) {
            sb.append('?');
        } else {
            for (int k = 0; k < f.getLocals(); ++k) {
                sb.append(getShortName(f.getLocal(k).toString()))
                        .append(' ');
            }
            sb.append(" : ");
            for (int k = 0; k < f.getStackSize(); ++k) {
                sb.append(getShortName(f.getStack(k).toString()))
                        .append(' ');
            }
        }
        while (sb.length() < method.maxStack + method.maxLocals + 1) {
            sb.append(' ');
        }
        pw.print(Integer.toString(j + 100000).substring(1));
        pw.print(" " + sb + " : " + t.text.get(t.text.size() - 1));
    }
    for (int j = 0; j < method.tryCatchBlocks.size(); ++j) {
        method.tryCatchBlocks.get(j).accept(mv);
        pw.print(" " + t.text.get(t.text.size() - 1));
    }
    pw.println();
}
 
Example #30
Source File: CheckClassAdapter.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void printAnalyzerResult(MethodNode method, Analyzer<BasicValue> a,
        final PrintWriter pw) {
    Frame<BasicValue>[] frames = a.getFrames();
    Textifier t = new Textifier();
    TraceMethodVisitor mv = new TraceMethodVisitor(t);

    pw.println(method.name + method.desc);
    for (int j = 0; j < method.instructions.size(); ++j) {
        method.instructions.get(j).accept(mv);

        StringBuilder sb = new StringBuilder();
        Frame<BasicValue> f = frames[j];
        if (f == null) {
            sb.append('?');
        } else {
            for (int k = 0; k < f.getLocals(); ++k) {
                sb.append(getShortName(f.getLocal(k).toString()))
                        .append(' ');
            }
            sb.append(" : ");
            for (int k = 0; k < f.getStackSize(); ++k) {
                sb.append(getShortName(f.getStack(k).toString()))
                        .append(' ');
            }
        }
        while (sb.length() < method.maxStack + method.maxLocals + 1) {
            sb.append(' ');
        }
        pw.print(Integer.toString(j + 100000).substring(1));
        pw.print(" " + sb + " : " + t.text.get(t.text.size() - 1));
    }
    for (int j = 0; j < method.tryCatchBlocks.size(); ++j) {
        method.tryCatchBlocks.get(j).accept(mv);
        pw.print(" " + t.text.get(t.text.size() - 1));
    }
    pw.println();
}