Example usage for org.objectweb.asm.tree AbstractInsnNode getNext

List of usage examples for org.objectweb.asm.tree AbstractInsnNode getNext

Introduction

In this page you can find the example usage for org.objectweb.asm.tree AbstractInsnNode getNext.

Prototype

public AbstractInsnNode getNext() 

Source Link

Document

Returns the next instruction in the list to which this instruction belongs, if any.

Usage

From source file:org.coldswap.asm.VirtualMethodReplacer.java

License:Open Source License

@Override
public MethodNode replaceInvoke(MethodNode methodNode) {
    InsnList instructions = methodNode.instructions;
    Iterator it = instructions.iterator();
    while (it.hasNext()) {
        AbstractInsnNode code = (AbstractInsnNode) it.next();
        if (code.getOpcode() == Opcodes.INVOKEVIRTUAL) {
            // check if methodToReplace is called
            final boolean[] callFounded = new boolean[] { false };
            code.accept(new MethodVisitor(Opcodes.ASM5) {
                @Override//from w w w. j a  va  2  s  .  c  o  m
                public void visitMethodInsn(int i, String s, String s2, String s3) {
                    if (s.equals(classContainer) && s2.equals(methodName)) {
                        callFounded[0] = true;
                    }
                    super.visitMethodInsn(i, s, s2, s3);
                }
            });

            if (callFounded[0]) {
                // if the return type is primitive and the value is not discarded, unbox
                if (AutoBoxing.isPrimitive(retType.getDescriptor())) {
                    AbstractInsnNode codeNext = code.getNext();
                    boolean discarded = false;
                    // if returning primitive double or long and it is discarded with a pop2 than discard with
                    // simple pop, because we use an Object as return value.
                    if (codeNext.getOpcode() == Opcodes.POP2
                            && (retType.getDescriptor().equals("D") || retType.getDescriptor().equals("J"))) {
                        instructions.set(codeNext, new InsnNode(Opcodes.POP));

                    }
                    if (codeNext.getOpcode() == Opcodes.POP || codeNext.getOpcode() == Opcodes.POP2) {
                        discarded = true;
                    }
                    if (!discarded) {
                        instructions.insert(code, AutoBoxing.unbox(retType));
                    }
                }

                // replace call with a custom call
                String newMethodName;
                AbstractInsnNode newInvoke = null;
                if (Constants.VAROBJECT.equals(methodType)) {
                    newMethodName = TransformerNameGenerator.getObjectMethodNameWithCounter(classContainer,
                            methodNumber);
                    newInvoke = new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classContainer, newMethodName,
                            "([Ljava/lang/Object;)Ljava/lang/Object;");
                } else if (Constants.INT.equals(methodType)) {
                    newMethodName = TransformerNameGenerator.getIntMethodNameWithCounter(classContainer,
                            methodNumber);
                    newInvoke = new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classContainer, newMethodName,
                            "(I)Ljava/lang/Object;");
                } else if (Constants.FLOAT.equals(methodType)) {
                    newMethodName = TransformerNameGenerator.getFloatMethodNameWithCounter(classContainer,
                            methodNumber);
                    newInvoke = new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classContainer, newMethodName,
                            "(F)Ljava/lang/Object;");
                } else if (Constants.STRING.equals(methodType)) {
                    newMethodName = TransformerNameGenerator.getStringMethodNameWithCounter(classContainer,
                            methodNumber);
                    newInvoke = new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classContainer, newMethodName,
                            "(Ljava/lang/String;)Ljava/lang/Object;");
                } else if (Constants.LONG.equals(methodType)) {
                    newMethodName = TransformerNameGenerator.getLongMethodNameWithCounter(classContainer,
                            methodNumber);
                    newInvoke = new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classContainer, newMethodName,
                            "(J)Ljava/lang/Object;");
                }
                if (newInvoke != null) {
                    instructions.set(code, newInvoke);
                }
            }
        }
    }
    return methodNode;
}

From source file:org.copperengine.core.instrument.TryCatchBlockHandler.java

License:Apache License

@SuppressWarnings("unchecked")
public void instrument(ClassNode cn) {
    // if (1 == 1) return;

    for (MethodNode m : (List<MethodNode>) cn.methods) {
        if (!m.exceptions.contains(INTERRUPT_EXCEPTION_NAME) || m.tryCatchBlocks.isEmpty()) {
            continue;
        }/*  w  ww .  j a  va 2 s.  c o  m*/
        logger.info("Instrument " + cn.name + "." + m.name);
        HashSet<Label> labels = new HashSet<Label>();
        for (TryCatchBlockNode catchNode : (List<TryCatchBlockNode>) m.tryCatchBlocks) {
            if (labels.contains(catchNode.handler.getLabel())) {
                // some handlers share their handling code - check it out to prevent double instrumentation
                logger.info("skipping node");
                continue;
            }
            labels.add(catchNode.handler.getLabel());

            LabelNode labelNode = catchNode.handler;
            AbstractInsnNode lineNumberNode = labelNode.getNext() instanceof LineNumberNode
                    ? labelNode.getNext()
                    : labelNode;
            FrameNode frameNode = (FrameNode) lineNumberNode.getNext();
            VarInsnNode varInsnNode = (VarInsnNode) frameNode.getNext();
            AbstractInsnNode insertPoint = varInsnNode;

            if (catchNode.type == null) {
                // this is probably a finally block;
                if (insertPoint.getNext() != null && insertPoint.getNext() instanceof LabelNode) {
                    insertPoint = insertPoint.getNext();
                }
            }

            LabelNode labelNode4ifeg = new LabelNode();
            InsnList newCode = new InsnList();
            newCode.add(new VarInsnNode(Opcodes.ALOAD, varInsnNode.var));
            newCode.add(new TypeInsnNode(Opcodes.INSTANCEOF, INTERRUPT_EXCEPTION_NAME));
            newCode.add(new JumpInsnNode(Opcodes.IFEQ, labelNode4ifeg));
            newCode.add(new VarInsnNode(Opcodes.ALOAD, varInsnNode.var));
            newCode.add(new TypeInsnNode(Opcodes.CHECKCAST, INTERRUPT_EXCEPTION_NAME));
            newCode.add(new InsnNode(Opcodes.ATHROW));
            newCode.add(labelNode4ifeg);
            m.instructions.insert(insertPoint, newCode);
        }
    }
}

From source file:org.diorite.inject.controller.Transformer.java

License:Open Source License

private void findReturns(TransformerInitMethodData initPair) {
    MethodNode init = initPair.node;//from  ww  w .j  a  v  a2 s .com
    AbstractInsnNode node = init.instructions.getFirst();
    while (node != null) {
        if ((node instanceof InsnNode) && AsmUtils.isReturnCode(node.getOpcode())) {
            initPair.returns.add((InsnNode) node);
        }
        node = node.getNext();
        if (node == null) {
            break;
        }
    }
}

From source file:org.diorite.inject.controller.TransformerFieldInjector.java

License:Open Source License

private void injectFieldsIn(MethodNode rootNode) {
    InsnList instructions = rootNode.instructions;
    if (instructions.size() == 0) {
        return;/*www . ja va2 s.  c  o m*/
    }
    AbstractInsnNode node = instructions.getFirst();
    while (node != null) {
        while (!(node instanceof FieldInsnNode) || !AsmUtils.isPutField(node.getOpcode())) {
            node = node.getNext();
            if (node == null) {
                return;
            }
        }
        this.trackFieldToInject((FieldInsnNode) node, rootNode.instructions);
        node = node.getNext();
    }
}

From source file:org.diorite.inject.controller.TransformerInjectTracker.java

License:Open Source License

private AbstractInsnNode trackMethod(MethodNode methodNode) {
    // get first instruction and go down until invoke is found.
    AbstractInsnNode node = methodNode.instructions.getFirst();
    do {//  w  ww  .  j  a v  a  2s .  com
        if (node == null) {
            throw new AnalyzeError("Can't track given field in delegated method (" + methodNode.name + " "
                    + methodNode.desc
                    + ")! Missing invoke placeholder! Remember that you can't use multiple method delegations!");
        }
        node = node.getNext();
        if (Transformer.isInjectPlaceholder(node) != PlaceholderType.INVALID) {
            this.resultNodeList = methodNode.instructions;
            return node;
        }
    } while (true);
}

From source file:org.evosuite.instrumentation.BooleanTestabilityTransformation.java

License:Open Source License

/**
 * This helper function determines whether the boolean on the stack at the
 * current position will be stored in a Boolean variable
 * /*  ww w  .ja  v a  2s.c o  m*/
 * @param position
 * @param mn
 * @return
 */
public boolean isBooleanAssignment(AbstractInsnNode position, MethodNode mn) {
    AbstractInsnNode node = position.getNext();
    logger.info("Checking for ISTORE after boolean");
    boolean done = false;
    while (!done) {

        if (node.getOpcode() == Opcodes.PUTFIELD || node.getOpcode() == Opcodes.PUTSTATIC) {
            // TODO: Check whether field is static
            logger.info("Checking field assignment");
            FieldInsnNode fn = (FieldInsnNode) node;
            if (Type.getType(DescriptorMapping.getInstance().getFieldDesc(fn.owner, fn.name,
                    fn.desc)) == Type.BOOLEAN_TYPE) {
                return true;
            } else {
                return false;
            }
        } else if (node.getOpcode() == Opcodes.ISTORE) {
            logger.info("Found ISTORE after boolean");

            VarInsnNode vn = (VarInsnNode) node;
            // TODO: Check whether variable at this position is a boolean
            if (isBooleanVariable(vn.var, mn)) {
                logger.info("Assigning boolean to variable ");
                return true;
            } else {
                logger.info("Variable is not a bool");
                return false;
            }
        } else if (node.getOpcode() == Opcodes.IRETURN) {
            logger.info("Checking return value of method {}.{}", cn.name, mn.name);
            if (DescriptorMapping.getInstance().isTransformedOrBooleanMethod(cn.name, mn.name, mn.desc)) {
                logger.info("Method returns a bool");
                return true;
            } else {
                logger.info("Method does not return a bool");
                return false;
            }
        } else if (node.getOpcode() == Opcodes.BASTORE) {
            // We remove all bytes, so BASTORE is only used for booleans
            AbstractInsnNode start = position.getNext();
            boolean reassignment = false;
            while (start != node) {
                if (node instanceof InsnNode) {
                    reassignment = true;
                }
                start = start.getNext();
            }
            logger.info("Possible assignment to array?");
            if (reassignment)
                return false;
            else
                return true;

        } else if (node instanceof MethodInsnNode) {
            // if it is a boolean parameter of a converted method, then it needs to be converted
            // Problem: How do we know which parameter it represents?
            MethodInsnNode methodNode = (MethodInsnNode) node;
            String desc = DescriptorMapping.getInstance().getMethodDesc(methodNode.owner, methodNode.name,
                    methodNode.desc);
            Type[] types = Type.getArgumentTypes(desc);
            if (types.length > 0 && types[types.length - 1] == Type.BOOLEAN_TYPE) {
                return true;
            } else {
                return false;
            }

        } else if (node.getOpcode() == Opcodes.GOTO || node.getOpcode() == Opcodes.ICONST_0
                || node.getOpcode() == Opcodes.ICONST_1 || node.getOpcode() == -1) {
            logger.info("Continuing search");

            // continue search
        } else if (!(node instanceof LineNumberNode || node instanceof FrameNode)) {
            logger.info("Search ended with opcode {}", node.getOpcode());

            return false;
        }
        if (node != mn.instructions.getLast())
            node = node.getNext();
        else
            done = true;
    }

    return false;
}

From source file:org.evosuite.instrumentation.ComparisonTransformation.java

License:Open Source License

/**
 * <p>transformMethod</p>//from  w w  w  . jav  a  2 s . c  om
 *
 * @param mn a {@link org.objectweb.asm.tree.MethodNode} object.
 */
public void transformMethod(MethodNode mn) {
    AbstractInsnNode node = mn.instructions.getFirst();
    while (node != mn.instructions.getLast()) {
        AbstractInsnNode next = node.getNext();
        if (node instanceof InsnNode) {
            InsnNode in = (InsnNode) node;
            if (in.getOpcode() == Opcodes.LCMP) {
                insertLongComparison(in, mn.instructions);
                TransformationStatistics.transformedComparison();
            } else if (in.getOpcode() == Opcodes.DCMPG) {
                // TODO: Check treatment of NaN
                TransformationStatistics.transformedComparison();
                insertDoubleComparison(in, mn.instructions);
            } else if (in.getOpcode() == Opcodes.DCMPL) {
                TransformationStatistics.transformedComparison();
                insertDoubleComparison(in, mn.instructions);
            } else if (in.getOpcode() == Opcodes.FCMPG) {
                TransformationStatistics.transformedComparison();
                insertFloatComparison(in, mn.instructions);
            } else if (in.getOpcode() == Opcodes.FCMPL) {
                TransformationStatistics.transformedComparison();
                insertFloatComparison(in, mn.instructions);
            }
        }
        node = next;
    }
}

From source file:org.evosuite.instrumentation.NodeRegularExpression.java

License:Open Source License

/**
 * <p>matches</p>/*from  www  . j av a  2s  . c om*/
 *
 * @param instructions a {@link org.objectweb.asm.tree.InsnList} object.
 * @return a boolean.
 */
public boolean matches(InsnList instructions) {
    int match = 0;

    AbstractInsnNode node = instructions.getFirst();
    while (node != instructions.getLast()) {
        if (node.getType() == AbstractInsnNode.FRAME || node.getType() == AbstractInsnNode.LABEL
                || node.getType() == AbstractInsnNode.LINE) {
            node = node.getNext();
            continue;
        } else {
            boolean found = false;
            for (int opcode : pattern[match]) {
                if (node.getOpcode() == opcode) {
                    match++;
                    found = true;
                    break;
                }
            }
            if (!found)
                match = 0;
        }
        if (match == pattern.length)
            return true;

        node = node.getNext();
    }

    return false;
}

From source file:org.evosuite.instrumentation.NodeRegularExpression.java

License:Open Source License

/**
 * <p>getNextMatch</p>//  w  w  w . ja  va  2  s  .c  o  m
 *
 * @param start a {@link org.objectweb.asm.tree.AbstractInsnNode} object.
 * @param instructions a {@link org.objectweb.asm.tree.InsnList} object.
 * @return a {@link org.objectweb.asm.tree.AbstractInsnNode} object.
 */
public AbstractInsnNode getNextMatch(AbstractInsnNode start, InsnList instructions) {
    int match = 0;

    AbstractInsnNode node = start;
    AbstractInsnNode startNode = start;
    while (node != instructions.getLast()) {
        if (node.getType() == AbstractInsnNode.FRAME || node.getType() == AbstractInsnNode.LABEL
                || node.getType() == AbstractInsnNode.LINE) {
            node = node.getNext();
            continue;
        } else {
            boolean found = false;
            for (int opcode : pattern[match]) {
                if (node.getOpcode() == opcode) {
                    if (match == 0)
                        startNode = node;
                    match++;
                    found = true;
                    break;
                }
            }
            if (!found)
                match = 0;
        }
        if (match == pattern.length) {
            return startNode;
        }

        node = node.getNext();
    }

    return null;

}

From source file:org.evosuite.instrumentation.StringTransformation.java

License:Open Source License

/**
 * <p>//from w  w w. j  a v a  2  s.c o m
 * transformMethod
 * </p>
 * 
 * @param mn
 *            a {@link org.objectweb.asm.tree.MethodNode} object.
 * @return a boolean.
 */
public boolean transformMethod(MethodNode mn) {
    boolean changed = transformStrings(mn);
    if (changed) {
        try {
            mn.maxStack++;
            Analyzer a = new Analyzer(new StringBooleanInterpreter());
            a.analyze(cn.name, mn);
            Frame[] frames = a.getFrames();
            AbstractInsnNode node = mn.instructions.getFirst();
            boolean done = false;
            while (!done) {
                if (node == mn.instructions.getLast())
                    done = true;
                AbstractInsnNode next = node.getNext();
                int index = mn.instructions.indexOf(node);
                if (index >= frames.length)
                    break;
                Frame current = frames[index];
                if (current == null)
                    break;
                int size = current.getStackSize();
                if (node.getOpcode() == Opcodes.IFNE) {
                    JumpInsnNode branch = (JumpInsnNode) node;
                    if (current.getStack(size - 1) == StringBooleanInterpreter.STRING_BOOLEAN
                            || isStringMethod(node.getPrevious())) {
                        logger.info("IFNE -> IFGT");
                        branch.setOpcode(Opcodes.IFGT);
                        // branch.setOpcode(Opcodes.IFGE);
                    }
                } else if (node.getOpcode() == Opcodes.IFEQ) {
                    JumpInsnNode branch = (JumpInsnNode) node;
                    if (current.getStack(size - 1) == StringBooleanInterpreter.STRING_BOOLEAN
                            || isStringMethod(node.getPrevious())) {
                        logger.info("IFEQ -> IFLE");
                        branch.setOpcode(Opcodes.IFLE);
                        // branch.setOpcode(Opcodes.IFNE);
                    }
                } else if (node.getOpcode() == Opcodes.IF_ICMPEQ) {
                    JumpInsnNode branch = (JumpInsnNode) node;
                    if (current.getStack(size - 2) == StringBooleanInterpreter.STRING_BOOLEAN
                            || isStringMethod(node.getPrevious().getPrevious())) {
                        if (node.getPrevious().getOpcode() == Opcodes.ICONST_0) {
                            branch.setOpcode(Opcodes.IFLE);
                            mn.instructions.remove(node.getPrevious());
                        } else if (node.getPrevious().getOpcode() == Opcodes.ICONST_1) {
                            branch.setOpcode(Opcodes.IFGT);
                            mn.instructions.remove(node.getPrevious());
                        }
                    }
                } else if (node.getOpcode() == Opcodes.IF_ICMPNE) {
                    JumpInsnNode branch = (JumpInsnNode) node;
                    if (current.getStack(size - 2) == StringBooleanInterpreter.STRING_BOOLEAN
                            || isStringMethod(node.getPrevious().getPrevious())) {
                        if (node.getPrevious().getOpcode() == Opcodes.ICONST_0) {
                            branch.setOpcode(Opcodes.IFGT);
                            mn.instructions.remove(node.getPrevious());
                        } else if (node.getPrevious().getOpcode() == Opcodes.ICONST_1) {
                            branch.setOpcode(Opcodes.IFLE);
                            mn.instructions.remove(node.getPrevious());
                        }
                    }
                } else if (node.getOpcode() == Opcodes.IRETURN) {
                    if (current.getStack(size - 1) == StringBooleanInterpreter.STRING_BOOLEAN
                            || isStringMethod(node.getPrevious())) {
                        logger.info("IFEQ -> IFLE");
                        MethodInsnNode n = new MethodInsnNode(Opcodes.INVOKESTATIC,
                                Type.getInternalName(BooleanHelper.class), "intToBoolean",
                                Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[] { Type.INT_TYPE }));

                        mn.instructions.insertBefore(node, n);
                    }
                }
                node = next;
            }
        } catch (Exception e) {
            logger.warn("EXCEPTION DURING STRING TRANSFORMATION: {}", e);
            e.printStackTrace();
            return changed;
        }
    }
    return changed;
}