Example usage for org.objectweb.asm.tree InsnList iterator

List of usage examples for org.objectweb.asm.tree InsnList iterator

Introduction

In this page you can find the example usage for org.objectweb.asm.tree InsnList iterator.

Prototype

@Override
public ListIterator<AbstractInsnNode> iterator() 

Source Link

Document

Returns an iterator over the instructions in this list.

Usage

From source file:org.eclipse.objectteams.otredyn.bytecode.asm.AbstractTransformableClassNode.java

License:Open Source License

/**
 * Replace all return statements in the given instructions with new 
 * statements that convert the real return value to {@link Object}
 * and return this new {@link Object}//www .  j  a va 2 s .c  o  m
 * 
 * @param instructions
 * @param returnType
 */
protected void replaceReturn(InsnList instructions, Type returnType) {
    if (returnType.getSort() != Type.OBJECT && returnType.getSort() != Type.ARRAY
            && returnType.getSort() != Type.VOID) {
        ListIterator<AbstractInsnNode> orgMethodIter = instructions.iterator();
        while (orgMethodIter.hasNext()) {
            AbstractInsnNode orgMethodNode = orgMethodIter.next();
            if (orgMethodNode.getOpcode() == returnType.getOpcode(Opcodes.IRETURN)) {
                instructions.insertBefore(orgMethodNode, AsmTypeHelper.getBoxingInstructionForType(returnType));
                instructions.insertBefore(orgMethodNode, new InsnNode(Opcodes.ARETURN));
                instructions.remove(orgMethodNode);
            }
        }
    } else if (returnType.getSort() == Type.VOID) {
        ListIterator<AbstractInsnNode> orgMethodIter = instructions.iterator();
        while (orgMethodIter.hasNext()) {
            AbstractInsnNode orgMethodNode = orgMethodIter.next();
            if (orgMethodNode.getOpcode() == Opcodes.RETURN) {
                instructions.insertBefore(orgMethodNode, new InsnNode(Opcodes.ACONST_NULL));
                instructions.insertBefore(orgMethodNode, new InsnNode(Opcodes.ARETURN));
                instructions.remove(orgMethodNode);
            }
        }
    }
}

From source file:org.eclipse.objectteams.otredyn.bytecode.asm.MoveCodeToCallOrigAdapter.java

License:Open Source License

/** To avoid infinite recursion, calls super.m(a1, a2) must be translated to super.callOrig(boundMethodId, new Object[] {a1, a2}). */
private void adjustSuperCalls(InsnList instructions, String selector, Type[] args, Type returnType,
        int boundMethodIdSlot) {
    // search://from   w  w w.j a v  a  2  s. c o  m
    List<MethodInsnNode> toReplace = new ArrayList<MethodInsnNode>();
    ListIterator<AbstractInsnNode> orgMethodIter = instructions.iterator();
    while (orgMethodIter.hasNext()) {
        AbstractInsnNode orgMethodNode = orgMethodIter.next();
        if (orgMethodNode.getOpcode() == Opcodes.INVOKESPECIAL
                && ((MethodInsnNode) orgMethodNode).name.equals(selector))
            toReplace.add((MethodInsnNode) orgMethodNode);
    }
    if (toReplace.isEmpty())
        return;
    // replace:
    for (MethodInsnNode oldNode : toReplace) {
        // we need to insert into the loading sequence before the invocation, find the insertion points:
        AbstractInsnNode[] insertionPoints = StackBalanceAnalyzer.findInsertionPointsBefore(oldNode, args);
        AbstractInsnNode firstInsert = insertionPoints.length > 0 ? insertionPoints[0] : oldNode;

        // push first arg to _OT$callOrig():
        instructions.insertBefore(firstInsert, new IntInsnNode(Opcodes.ILOAD, boundMethodIdSlot));

        // prepare array as second arg to _OT$callOrig():
        instructions.insertBefore(firstInsert, new IntInsnNode(Opcodes.BIPUSH, args.length));
        instructions.insertBefore(firstInsert, new TypeInsnNode(Opcodes.ANEWARRAY, "java/lang/Object"));

        for (int i = 0; i < insertionPoints.length; i++) {
            // NB: each iteration has an even stack balance, where the top is the Object[].
            instructions.insertBefore(insertionPoints[i], new InsnNode(Opcodes.DUP));
            instructions.insertBefore(insertionPoints[i], new IntInsnNode(Opcodes.BIPUSH, i));
            // leave the original loading sequence in tact and continue at the next point:
            AbstractInsnNode insertAt = (i + 1 < insertionPoints.length) ? insertionPoints[i + 1] : oldNode;
            instructions.insertBefore(insertAt, AsmTypeHelper.getBoxingInstructionForType(args[i]));
            instructions.insertBefore(insertAt, new InsnNode(Opcodes.AASTORE));
        }

        if (returnType == Type.VOID_TYPE)
            instructions.insert(oldNode, new InsnNode(Opcodes.POP));
        else
            instructions.insert(oldNode, AsmTypeHelper.getUnboxingInstructionForType(returnType));

        instructions.set(oldNode, new MethodInsnNode(Opcodes.INVOKESPECIAL, ((MethodInsnNode) oldNode).owner,
                callOrig.getName(), callOrig.getSignature()));
    }
}

From source file:org.epoxide.surge.asm.ASMUtils.java

License:Creative Commons License

private static String infod(InsnList needle, InsnList hayStack) {

    final StringBuilder builder = new StringBuilder();
    builder.append(SystemUtils.LINE_SEPARATOR);
    builder.append("Printing Needle" + SystemUtils.LINE_SEPARATOR);

    ListIterator<AbstractInsnNode> i = needle.iterator();

    while (i.hasNext()) {
        builder.append(getInstructionString(i.next()) + SystemUtils.LINE_SEPARATOR);
    }//from  w w w.  j ava  2  s .  c o  m

    builder.append("Printing Haystack" + SystemUtils.LINE_SEPARATOR);
    i = hayStack.iterator();

    while (i.hasNext()) {
        builder.append(getInstructionString(i.next()) + SystemUtils.LINE_SEPARATOR);
    }

    builder.append("fuffff");
    return builder.toString();
}

From source file:org.evosuite.instrumentation.mutation.ReplaceVariable.java

License:Open Source License

/**
 * <p>//from  ww  w  .  j  a v a 2  s .  c  o  m
 * copy
 * </p>
 *
 * @param orig
 *            a {@link org.objectweb.asm.tree.InsnList} object.
 * @return a {@link org.objectweb.asm.tree.InsnList} object.
 */
public static InsnList copy(InsnList orig) {
    Iterator<?> it = orig.iterator();
    InsnList copy = new InsnList();
    while (it.hasNext()) {
        AbstractInsnNode node = (AbstractInsnNode) it.next();

        if (node instanceof VarInsnNode) {
            VarInsnNode vn = (VarInsnNode) node;
            copy.add(new VarInsnNode(vn.getOpcode(), vn.var));
        } else if (node instanceof FieldInsnNode) {
            FieldInsnNode fn = (FieldInsnNode) node;
            copy.add(new FieldInsnNode(fn.getOpcode(), fn.owner, fn.name, fn.desc));
        } else if (node instanceof InsnNode) {
            if (node.getOpcode() != Opcodes.POP)
                copy.add(new InsnNode(node.getOpcode()));
        } else if (node instanceof LdcInsnNode) {
            copy.add(new LdcInsnNode(((LdcInsnNode) node).cst));
        } else {
            throw new RuntimeException("Unexpected node type: " + node.getClass());
        }
    }
    return copy;
}

From source file:org.evosuite.instrumentation.testability.transformer.ImplicitElseTransformer.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//ww w .  j  a v  a  2  s.  com
protected AbstractInsnNode transformFieldInsnNode(MethodNode mn, FieldInsnNode fieldNode) {

    if ((fieldNode.getOpcode() == Opcodes.PUTFIELD || fieldNode.getOpcode() == Opcodes.PUTSTATIC)
            && DescriptorMapping.getInstance().isTransformedOrBooleanField(fieldNode.owner, fieldNode.name,
                    fieldNode.desc)) {

        if (addedInsns.contains(fieldNode))
            return fieldNode;

        // Can only handle cases where the field owner is loaded directly before the field
        // TODO: We could pop the top of the stack and DUP the owner, but would need to take care
        // whether we need to pop one or two words
        if (fieldNode.getOpcode() == Opcodes.PUTFIELD) {
            AbstractInsnNode previous = fieldNode.getPrevious();
            while (previous instanceof LineNumberNode || previous instanceof FrameNode
                    || previous.getOpcode() == Opcodes.ICONST_0 || previous.getOpcode() == Opcodes.ICONST_1)
                previous = previous.getPrevious();
            if (previous.getOpcode() != Opcodes.ALOAD) {
                BooleanTestabilityTransformation.logger.info("Can't handle case of " + previous);
                return fieldNode;
            }
            VarInsnNode varNode = (VarInsnNode) previous;
            if (varNode.var != 0) {
                BooleanTestabilityTransformation.logger.info("Can't handle case of " + previous);
                return fieldNode;
            }
        }
        BooleanTestabilityTransformation.logger.info("Handling PUTFIELD case!");

        // Check if ICONST_0 or ICONST_1 are on the stack
        ControlDependenceGraph cdg = GraphPool.getInstance(this.booleanTestabilityTransformation.classLoader)
                .getCDG(this.booleanTestabilityTransformation.className.replace("/", "."), mn.name + mn.desc);
        int index = mn.instructions.indexOf(fieldNode);
        BooleanTestabilityTransformation.logger.info("Getting bytecode instruction for " + fieldNode.name + "/"
                + ((FieldInsnNode) mn.instructions.get(index)).name);
        InsnList nodes = mn.instructions;
        ListIterator<AbstractInsnNode> it = nodes.iterator();
        while (it.hasNext()) {
            BytecodeInstruction in = new BytecodeInstruction(this.booleanTestabilityTransformation.classLoader,
                    this.booleanTestabilityTransformation.className, mn.name, 0, 0, it.next());
            BooleanTestabilityTransformation.logger.info(in.toString());
        }
        BytecodeInstruction insn = BytecodeInstructionPool
                .getInstance(this.booleanTestabilityTransformation.classLoader)
                .getInstruction(this.booleanTestabilityTransformation.className.replace("/", "."),
                        mn.name + mn.desc, index);
        if (insn == null)
            insn = BytecodeInstructionPool.getInstance(this.booleanTestabilityTransformation.classLoader)
                    .getInstruction(this.booleanTestabilityTransformation.className.replace("/", "."),
                            mn.name + mn.desc, fieldNode);
        //varNode);
        if (insn == null) {
            // TODO: Find out why
            BooleanTestabilityTransformation.logger.info("ERROR: Could not find node");
            return fieldNode;
        }
        if (insn.getASMNode().getOpcode() != fieldNode.getOpcode()) {
            BooleanTestabilityTransformation.logger.info("Found wrong bytecode instruction at this index!");
            BytecodeInstructionPool.getInstance(this.booleanTestabilityTransformation.classLoader)
                    .getInstruction(this.booleanTestabilityTransformation.className, mn.name + mn.desc,
                            fieldNode);
        }
        if (insn.getBasicBlock() == null) {
            BooleanTestabilityTransformation.logger.info("ERROR: Problematic node found");
            return fieldNode;
        }
        Set<ControlDependency> dependencies = insn.getControlDependencies();
        BooleanTestabilityTransformation.logger.info("Found flag assignment: " + insn + ", checking "
                + dependencies.size() + " control dependencies");

        for (ControlDependency dep : dependencies) {
            if (!addedNodes.contains(dep))
                handleDependency(dep, cdg, mn, fieldNode, insn);
        }
    }
    return fieldNode;
}

From source file:org.evosuite.junit.DetermineSUT.java

License:Open Source License

@SuppressWarnings("unchecked")
private void handleMethodNode(Set<String> calledClasses, ClassNode cn, MethodNode mn, Set<String> targetClasses)
        throws IOException {
    InsnList instructions = mn.instructions;
    Iterator<AbstractInsnNode> iterator = instructions.iterator();

    while (iterator.hasNext()) {
        AbstractInsnNode insn = iterator.next();
        if (insn instanceof MethodInsnNode) {
            String name = ResourceList.getClassNameFromResourcePath(((MethodInsnNode) insn).owner);
            if (!targetClasses.contains(name))
                continue;

            if (isValidClass(name))
                calledClasses.add(name);
        }//  w ww .  j a v  a 2  s. co m
    }
}

From source file:org.evosuite.seeding.CastClassAnalyzer.java

License:Open Source License

/**
 * Add all possible calls for a given method
 * /*from w  w  w  . java  2  s .c  o m*/
 * @param callGraph
 * @param mn
 */
@SuppressWarnings("unchecked")
public void handleMethodNode(ClassNode cn, MethodNode mn, int depth) {

    if (mn.signature != null) {
        logger.debug("Visiting signature: " + mn.signature);
        CollectParameterTypesVisitor visitor = new CollectParameterTypesVisitor(cn.name);
        new SignatureReader(mn.signature).accept(visitor);
        for (Type castType : visitor.getClasses()) {
            if (!castClassMap.containsKey(castType)) {
                logger.debug("Adding new cast class from signature visitor: " + castType);
                castClassMap.put(castType, depth + 1);
            }
        }
    }

    InsnList instructions = mn.instructions;
    Iterator<AbstractInsnNode> iterator = instructions.iterator();

    // TODO: This really shouldn't be here but in its own class
    while (iterator.hasNext()) {
        AbstractInsnNode insn = iterator.next();
        if (insn.getOpcode() == Opcodes.CHECKCAST) {
            TypeInsnNode typeNode = (TypeInsnNode) insn;
            Type castType = Type.getObjectType(typeNode.desc);
            while (castType.getSort() == Type.ARRAY) {
                castType = castType.getElementType();
            }
            logger.debug("Adding new cast class from cast: " + castType);
            if (!castClassMap.containsKey(castType))
                castClassMap.put(castType, depth + 1);
        } else if (insn.getOpcode() == Opcodes.INSTANCEOF) {
            TypeInsnNode typeNode = (TypeInsnNode) insn;
            Type castType = Type.getObjectType(typeNode.desc);
            while (castType.getSort() == Type.ARRAY) {
                castType = castType.getElementType();
            }
            logger.debug("Adding new cast class from instanceof: " + castType);
            if (!castClassMap.containsKey(castType))
                castClassMap.put(castType, depth + 1);
        } else if (insn.getOpcode() == Opcodes.LDC) {
            LdcInsnNode ldcNode = (LdcInsnNode) insn;
            if (ldcNode.cst instanceof Type) {
                Type type = (Type) ldcNode.cst;
                while (type.getSort() == Type.ARRAY) {
                    type = type.getElementType();
                }
                if (!castClassMap.containsKey(type))
                    castClassMap.put(type, depth + 1);
            }

        }
    }
}

From source file:org.evosuite.setup.callgraph.CallGraphGenerator.java

License:Open Source License

/**
 * Add all possible calls for a given method
 * /*  w  w w .j a  va  2s .c  o  m*/
 * @param callGraph
 * @param mn
 */
@SuppressWarnings("unchecked")
private static void handleMethodNode(CallGraph callGraph, ClassNode cn, MethodNode mn, int depth) {
    handlePublicMethodNode(callGraph, cn, mn);

    // TODO: Integrate this properly - it is currently an unexpected side-effect
    if (!ExceptionTransformationClassAdapter.methodExceptionMap.containsKey(cn.name))
        ExceptionTransformationClassAdapter.methodExceptionMap.put(cn.name, new LinkedHashMap<>());

    String methodNameDesc = mn.name + mn.desc;
    Set<Type> exceptionTypes = new LinkedHashSet<>();
    if (mn.exceptions != null) {
        for (String exceptionName : ((List<String>) mn.exceptions)) {
            exceptionTypes.add(Type.getType(exceptionName));
        }
    }
    ExceptionTransformationClassAdapter.methodExceptionMap.get(cn.name).put(methodNameDesc, exceptionTypes);

    InsnList instructions = mn.instructions;
    Iterator<AbstractInsnNode> iterator = instructions.iterator();

    // TODO: This really shouldn't be here but in its own class
    while (iterator.hasNext()) {
        AbstractInsnNode insn = iterator.next();
        if (insn instanceof MethodInsnNode) {
            handleMethodInsnNode(callGraph, cn, mn, (MethodInsnNode) insn, depth + 1);
        }
    }
}

From source file:org.evosuite.setup.CallTreeGenerator.java

License:Open Source License

/**
 * Add all possible calls for a given method
 * //from ww w .  j av  a 2  s  . c o m
 * @param callGraph
 * @param mn
 */
@SuppressWarnings("unchecked")
private static void handleMethodNode(CallTree callTree, ClassNode cn, MethodNode mn, int depth) {
    handlePublicMethodNode(callTree, cn, mn);

    InsnList instructions = mn.instructions;
    Iterator<AbstractInsnNode> iterator = instructions.iterator();

    // TODO: This really shouldn't be here but in its own class
    while (iterator.hasNext()) {
        AbstractInsnNode insn = iterator.next();
        if (insn instanceof MethodInsnNode) {
            handleMethodInsnNode(callTree, cn, mn, (MethodInsnNode) insn, depth + 1);
        }
    }
}

From source file:org.evosuite.setup.GetStaticGraphGenerator.java

License:Open Source License

/**
 * Add all possible calls for a given method
 * //w w  w  . ja  v  a2s.c o  m
 * @param callGraph
 * @param mn
 */
@SuppressWarnings("unchecked")
private static void handleMethodNode(GetStaticGraph staticUsageTree, ClassNode cn, MethodNode mn, int depth) {

    InsnList instructions = mn.instructions;
    Iterator<AbstractInsnNode> iterator = instructions.iterator();

    // TODO: This really shouldn't be here but in its own class
    while (iterator.hasNext()) {
        AbstractInsnNode insn = iterator.next();
        if (insn instanceof MethodInsnNode) {
            handleMethodInsnNode(staticUsageTree, cn, mn, (MethodInsnNode) insn, depth + 1);
        } else if (insn instanceof FieldInsnNode) {
            handleFieldInsnNode(staticUsageTree, cn, mn, (FieldInsnNode) insn, depth + 1);
        }

    }
}