Search in sources :

Example 1 with TraceMethodVisitor

use of org.objectweb.asm.util.TraceMethodVisitor in project evosuite by EvoSuite.

the class RegressionClassDiff method getClassInstructions.

/*
   * Get bytecode instructions for the class based on the following format: Method -> List of
   * instructions
   */
private static Map<String, List<Integer>> getClassInstructions(InputStream classAsInputStream) {
    HashMap<String, List<Integer>> methodInstructionsMap = new HashMap<>();
    try {
        ClassReader reader = new ClassReader(classAsInputStream);
        ClassNode classNode = new ClassNode();
        reader.accept(classNode, 0);
        @SuppressWarnings("unchecked") final List<MethodNode> methods = classNode.methods;
        Printer printer = new Textifier();
        TraceMethodVisitor mp = new TraceMethodVisitor(printer);
        for (MethodNode m : methods) {
            List<Integer> instructions = new ArrayList<>();
            InsnList inList = m.instructions;
            String mathodID = m.name + ": " + m.desc;
            System.out.println(mathodID);
            int[] methodInstructions = new int[inList.size()];
            for (int i = 0; i < inList.size(); i++) {
                int op = inList.get(i).getOpcode();
                methodInstructions[i] = op;
                AbstractInsnNode insn = inList.get(i);
                insn.accept(mp);
                // logger.warn("{} -> {}", sw.toString(), op);
                if (op != -1)
                    instructions.add(op);
            }
            methodInstructionsMap.put(mathodID, instructions);
        }
    } catch (IOException e) {
        // Will fail if ClassReader fails
        e.printStackTrace();
    }
    return methodInstructionsMap;
}
Also used : ClassNode(org.objectweb.asm.tree.ClassNode) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Printer(org.objectweb.asm.util.Printer) Textifier(org.objectweb.asm.util.Textifier) InsnList(org.objectweb.asm.tree.InsnList) AbstractInsnNode(org.objectweb.asm.tree.AbstractInsnNode) TraceMethodVisitor(org.objectweb.asm.util.TraceMethodVisitor) MethodNode(org.objectweb.asm.tree.MethodNode) ClassReader(org.objectweb.asm.ClassReader) ArrayList(java.util.ArrayList) InsnList(org.objectweb.asm.tree.InsnList) List(java.util.List) ResourceList(org.evosuite.classpath.ResourceList)

Example 2 with TraceMethodVisitor

use of org.objectweb.asm.util.TraceMethodVisitor in project CodeChickenLib by Chicken-Bones.

the class InsnListSection method toString.

public String toString() {
    Textifier t = new Textifier();
    accept(new TraceMethodVisitor(t));
    StringWriter sw = new StringWriter();
    t.print(new PrintWriter(sw));
    return sw.toString();
}
Also used : StringWriter(java.io.StringWriter) Textifier(org.objectweb.asm.util.Textifier) TraceMethodVisitor(org.objectweb.asm.util.TraceMethodVisitor) PrintWriter(java.io.PrintWriter)

Example 3 with TraceMethodVisitor

use of org.objectweb.asm.util.TraceMethodVisitor in project neo4j by neo4j.

the class ByteCodeVerifier method detailedMessage.

private static String detailedMessage(String errorMessage, MethodNode method, Frame[] frames, AbstractInsnNode errorLocation) {
    StringWriter message = new StringWriter();
    try (PrintWriter out = new PrintWriter(message)) {
        List<Integer> localLengths = new ArrayList<>();
        List<Integer> stackLengths = new ArrayList<>();
        for (Frame frame : frames) {
            if (frame != null) {
                for (int i = 0; i < frame.getLocals(); i++) {
                    insert(i, frame.getLocal(i), localLengths);
                }
                for (int i = 0; i < frame.getStackSize(); i++) {
                    insert(i, frame.getStack(i), stackLengths);
                }
            }
        }
        Textifier formatted = new Textifier();
        TraceMethodVisitor mv = new TraceMethodVisitor(formatted);
        out.println(errorMessage);
        out.append("\t\tin ").append(method.name).append(method.desc).println();
        for (int i = 0; i < method.instructions.size(); i++) {
            AbstractInsnNode insn = method.instructions.get(i);
            insn.accept(mv);
            Frame frame = frames[i];
            out.append("\t\t");
            out.append(insn == errorLocation ? ">>> " : "    ");
            out.format("%05d [", i);
            if (frame == null) {
                padding(out, localLengths.listIterator(), '?');
                out.append(" : ");
                padding(out, stackLengths.listIterator(), '?');
            } else {
                emit(out, localLengths, frame::getLocal, frame.getLocals());
                padding(out, localLengths.listIterator(frame.getLocals()), '-');
                out.append(" : ");
                emit(out, stackLengths, frame::getStack, frame.getStackSize());
                padding(out, stackLengths.listIterator(frame.getStackSize()), ' ');
            }
            out.print("] : ");
            out.print(formatted.text.get(formatted.text.size() - 1));
        }
        for (int j = 0; j < method.tryCatchBlocks.size(); j++) {
            method.tryCatchBlocks.get(j).accept(mv);
            out.print(" " + formatted.text.get(formatted.text.size() - 1));
        }
    }
    return message.toString();
}
Also used : Frame(org.objectweb.asm.tree.analysis.Frame) StringWriter(java.io.StringWriter) ArrayList(java.util.ArrayList) Textifier(org.objectweb.asm.util.Textifier) AbstractInsnNode(org.objectweb.asm.tree.AbstractInsnNode) TraceMethodVisitor(org.objectweb.asm.util.TraceMethodVisitor) PrintWriter(java.io.PrintWriter)

Example 4 with TraceMethodVisitor

use of org.objectweb.asm.util.TraceMethodVisitor in project groovy by apache.

the class AsmClassGenerator method visitConstructorOrMethod.

@Override
protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
    Parameter[] parameters = node.getParameters();
    MethodVisitor mv = classVisitor.visitMethod(node.getModifiers() | (isVargs(parameters) ? ACC_VARARGS : 0), node.getName(), BytecodeHelper.getMethodDescriptor(node.getReturnType(), parameters), BytecodeHelper.getGenericsMethodSignature(node), buildExceptions(node.getExceptions()));
    controller.setMethodVisitor(mv);
    controller.resetLineNumber();
    visitAnnotations(node, mv);
    visitTypeParameters(node, mv);
    // ideally following statement would be in visitMethod but mv not visible there
    if (!(node instanceof ConstructorNode)) {
        visitType(node.getReturnType(), mv, newTypeReference(METHOD_RETURN), "", true);
    }
    // add parameter names to the MethodVisitor (JDK8+)
    if (Optional.ofNullable(controller.getClassNode().getCompileUnit()).orElseGet(context::getCompileUnit).getConfig().getParameters()) {
        for (Parameter parameter : parameters) {
            mv.visitParameter(parameter.getName(), parameter.getModifiers());
        }
    }
    for (int i = 0, n = parameters.length; i < n; i += 1) {
        visitParameterAnnotations(parameters[i], i, mv);
        ClassNode paramType = parameters[i].getType();
        if (paramType.isGenericsPlaceHolder()) {
            visitTypeAnnotations(paramType, mv, newFormalParameterReference(i), "", true);
        } else {
            visitType(parameters[i].getType(), mv, newFormalParameterReference(i), "", true);
        }
    }
    if (node.getExceptions() != null) {
        for (int i = 0, n = node.getExceptions().length; i < n; i += 1) {
            visitTypeAnnotations(node.getExceptions()[i], mv, newExceptionReference(i), "", true);
        }
    }
    if (controller.getClassNode().isAnnotationDefinition() && !node.isStaticConstructor()) {
        visitAnnotationDefault(node, mv);
    } else if (!node.isAbstract()) {
        mv.visitCode();
        Statement code = node.getCode();
        // fast path for getters, setters, etc.
        BytecodeInstruction instruction;
        if (code instanceof BytecodeSequence && (instruction = ((BytecodeSequence) code).getBytecodeInstruction()) != null) {
            instruction.visit(mv);
        } else {
            visitStdMethod(node, isConstructor, parameters, code);
        }
        try {
            mv.visitMaxs(0, 0);
        } catch (Exception e) {
            Writer writer = null;
            if (mv instanceof TraceMethodVisitor) {
                writer = new StringBuilderWriter();
                PrintWriter p = new PrintWriter(writer);
                ((TraceMethodVisitor) mv).p.print(p);
                p.flush();
            }
            StringBuilder message = new StringBuilder(64);
            message.append("ASM reporting processing error for ");
            message.append(controller.getClassNode().toString(false)).append('#').append(node.getName());
            message.append(" with signature ").append(node.getTypeDescriptor());
            message.append(" in ").append(sourceFile).append(':').append(node.getLineNumber());
            if (writer != null) {
                message.append("\nLast known generated bytecode in last generated method or constructor:\n");
                message.append(writer);
            }
            throw new GroovyRuntimeException(message.toString(), e);
        }
    }
    mv.visitEnd();
}
Also used : InterfaceHelperClassNode(org.codehaus.groovy.ast.InterfaceHelperClassNode) ClassNode(org.codehaus.groovy.ast.ClassNode) InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) AssertStatement(org.codehaus.groovy.ast.stmt.AssertStatement) ExpressionStatement(org.codehaus.groovy.ast.stmt.ExpressionStatement) BreakStatement(org.codehaus.groovy.ast.stmt.BreakStatement) ReturnStatement(org.codehaus.groovy.ast.stmt.ReturnStatement) ForStatement(org.codehaus.groovy.ast.stmt.ForStatement) IfStatement(org.codehaus.groovy.ast.stmt.IfStatement) ThrowStatement(org.codehaus.groovy.ast.stmt.ThrowStatement) SynchronizedStatement(org.codehaus.groovy.ast.stmt.SynchronizedStatement) TryCatchStatement(org.codehaus.groovy.ast.stmt.TryCatchStatement) CaseStatement(org.codehaus.groovy.ast.stmt.CaseStatement) WhileStatement(org.codehaus.groovy.ast.stmt.WhileStatement) CatchStatement(org.codehaus.groovy.ast.stmt.CatchStatement) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement) Statement(org.codehaus.groovy.ast.stmt.Statement) DoWhileStatement(org.codehaus.groovy.ast.stmt.DoWhileStatement) ContinueStatement(org.codehaus.groovy.ast.stmt.ContinueStatement) SwitchStatement(org.codehaus.groovy.ast.stmt.SwitchStatement) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) TraceMethodVisitor(org.objectweb.asm.util.TraceMethodVisitor) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) RuntimeParserException(org.codehaus.groovy.syntax.RuntimeParserException) TraceMethodVisitor(org.objectweb.asm.util.TraceMethodVisitor) MethodVisitor(org.objectweb.asm.MethodVisitor) ConstructorNode(org.codehaus.groovy.ast.ConstructorNode) Parameter(org.codehaus.groovy.ast.Parameter) OptimizingStatementWriter(org.codehaus.groovy.classgen.asm.OptimizingStatementWriter) MopWriter(org.codehaus.groovy.classgen.asm.MopWriter) StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) PrintWriter(java.io.PrintWriter)

Example 5 with TraceMethodVisitor

use of org.objectweb.asm.util.TraceMethodVisitor in project groovy by apache.

the class VerifyClass method readClass.

private boolean readClass(String clazz) throws IOException {
    ClassNode ca;
    try (final InputStream inputStream = new BufferedInputStream(new FileInputStream(clazz))) {
        ClassReader cr = new ClassReader(inputStream);
        ca = new ClassNode() {

            @Override
            public void visitEnd() {
            // accept(cv);
            }
        };
        cr.accept(new CheckClassAdapter(ca), ClassWriter.COMPUTE_MAXS);
    }
    boolean failed = false;
    List<MethodNode> methods = ca.methods;
    for (MethodNode method : methods) {
        if (method.instructions.size() > 0) {
            Analyzer<?> a = new Analyzer<>(new SimpleVerifier());
            try {
                a.analyze(ca.name, method);
                continue;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!failed) {
                failed = true;
                log("verifying of class " + clazz + " failed");
            }
            if (verbose)
                log(method.name + method.desc);
            TraceMethodVisitor mv = new TraceMethodVisitor(null);
            for (int j = 0; j < method.instructions.size(); ++j) {
                AbstractInsnNode insn = method.instructions.get(j);
                if (insn != null) {
                    insn.accept(mv);
                } else {
                    mv.visitLabel(null);
                }
            }
            mv.visitMaxs(method.maxStack, method.maxLocals);
        }
    }
    return !failed;
}
Also used : ClassNode(org.objectweb.asm.tree.ClassNode) SimpleVerifier(org.objectweb.asm.tree.analysis.SimpleVerifier) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Analyzer(org.objectweb.asm.tree.analysis.Analyzer) AbstractInsnNode(org.objectweb.asm.tree.AbstractInsnNode) TraceMethodVisitor(org.objectweb.asm.util.TraceMethodVisitor) FileInputStream(java.io.FileInputStream) BuildException(org.apache.tools.ant.BuildException) IOException(java.io.IOException) MethodNode(org.objectweb.asm.tree.MethodNode) BufferedInputStream(java.io.BufferedInputStream) CheckClassAdapter(org.objectweb.asm.util.CheckClassAdapter) ClassReader(org.objectweb.asm.ClassReader)

Aggregations

TraceMethodVisitor (org.objectweb.asm.util.TraceMethodVisitor)11 Textifier (org.objectweb.asm.util.Textifier)8 PrintWriter (java.io.PrintWriter)5 StringWriter (java.io.StringWriter)4 AbstractInsnNode (org.objectweb.asm.tree.AbstractInsnNode)4 IOException (java.io.IOException)3 ClassReader (org.objectweb.asm.ClassReader)3 ClassNode (org.objectweb.asm.tree.ClassNode)3 MethodNode (org.objectweb.asm.tree.MethodNode)3 Frame (org.objectweb.asm.tree.analysis.Frame)3 FileInputStream (java.io.FileInputStream)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 BuildException (org.apache.tools.ant.BuildException)2 TryCatchBlockNode (org.objectweb.asm.tree.TryCatchBlockNode)2 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)1 BufferedInputStream (java.io.BufferedInputStream)1 InputStream (java.io.InputStream)1 Writer (java.io.Writer)1 HashMap (java.util.HashMap)1