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

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

Introduction

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

Prototype

public int getOpcode() 

Source Link

Document

Returns the opcode of this instruction.

Usage

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

License:Open Source License

/** {@inheritDoc} */
@SuppressWarnings("rawtypes")
@Override//from  w  w  w .j  a v  a2s  .c  o  m
public BasicValue naryOperation(AbstractInsnNode insn, List values) throws AnalyzerException {
    if (insn.getOpcode() == INVOKESTATIC || insn.getOpcode() == INVOKEVIRTUAL
            || insn.getOpcode() == INVOKEINTERFACE) {
        MethodInsnNode mn = (MethodInsnNode) insn;

        if (Type.getReturnType(mn.desc).equals(Type.BOOLEAN_TYPE)) {
            return BOOLEAN;
        } else if (mn.desc.equals("[Z")) {
            return BOOLEAN_ARRAY;
        } else if (mn.desc.equals("[B")) {
            return BYTE_ARRAY;
        } else if (mn.desc.equals("[I")) {
            return INT_ARRAY;
        } else if (Type.getReturnType(mn.desc).equals(Type.BYTE_TYPE)) {
            return BYTE;
        } else {
            if (mn.name.equals("clone") && mn.owner.equals("[I"))
                return INT_ARRAY;
            else if (mn.name.equals("clone") && mn.owner.equals("[Z"))
                return BOOLEAN_ARRAY;
            else if (mn.name.equals("clone") && mn.owner.equals("[B"))
                return BYTE_ARRAY;
            else {
                return super.naryOperation(insn, values);
            }
        }
    } else {
        return super.naryOperation(insn, values);
    }
}

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
 * /*from w  ww .j a  v a 2 s .co 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.BooleanValueInterpreter.java

License:Open Source License

/** {@inheritDoc} */
@Override/* w w  w . j av a 2s .  co  m*/
public BasicValue unaryOperation(AbstractInsnNode insn, BasicValue value) throws AnalyzerException {
    if (insn.getOpcode() == Opcodes.INSTANCEOF) {
        return BOOLEAN_VALUE;
    } else if (insn.getOpcode() == Opcodes.GETFIELD) {
        FieldInsnNode fieldNode = (FieldInsnNode) insn;
        if (BooleanTestabilityTransformation.isTransformedField(fieldNode.owner, fieldNode.name,
                fieldNode.desc))
            return BOOLEAN_VALUE;
    }
    return super.unaryOperation(insn, value);
}

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

License:Open Source License

/** {@inheritDoc} */
@Override//from  w w w. jav  a  2 s . co  m
public BasicValue newOperation(AbstractInsnNode insn) throws AnalyzerException {
    if (insn.getOpcode() == ICONST_0) {
        return BOOLEAN_VALUE;
    } else if (insn.getOpcode() == ICONST_1) {
        return BOOLEAN_VALUE;
    } else if (insn.getOpcode() == Opcodes.GETSTATIC) {
        FieldInsnNode fieldNode = (FieldInsnNode) insn;
        if (BooleanTestabilityTransformation.isTransformedField(fieldNode.owner, fieldNode.name,
                fieldNode.desc))
            return BOOLEAN_VALUE;

    }
    return super.newOperation(insn);
}

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

License:Open Source License

/** {@inheritDoc} */
@Override/* ww  w  .  j a v a 2 s. c o m*/
public BasicValue binaryOperation(AbstractInsnNode insn, BasicValue value1, BasicValue value2)
        throws AnalyzerException {
    switch (insn.getOpcode()) {
    case IALOAD:
    case BALOAD:
    case CALOAD:
    case SALOAD:
        if (value1 == BOOLEAN_ARRAY)
            return BOOLEAN_VALUE;
    }
    return super.binaryOperation(insn, value1, value2);
}

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

License:Open Source License

/** {@inheritDoc} */
@Override/*from  w w w .j  a  v a  2s.  com*/
public BasicValue copyOperation(AbstractInsnNode insn, BasicValue value) throws AnalyzerException {
    if (insn.getOpcode() == Opcodes.ILOAD) {
        VarInsnNode varNode = (VarInsnNode) insn;
        if (isStatic) {
            if (varNode.var < types.length) {
                if (types[varNode.var] == Type.BOOLEAN_TYPE) {
                    return BOOLEAN_VALUE;
                }
            }
        } else {
            if (varNode.var > 0 && varNode.var - 1 < types.length) {
                if (types[varNode.var - 1] == Type.BOOLEAN_TYPE) {
                    return BOOLEAN_VALUE;
                }
            }
        }
    }
    return super.copyOperation(insn, value);
}

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

License:Open Source License

/** {@inheritDoc} */
@Override//from  w ww  .  j  ava 2s . c o m
public BasicValue naryOperation(AbstractInsnNode insn, @SuppressWarnings("rawtypes") List values)
        throws AnalyzerException {
    if (insn.getOpcode() == Opcodes.INVOKESTATIC) {
        MethodInsnNode mn = (MethodInsnNode) insn;
        if (mn.owner.equals("org/evosuite/instrumentation/BooleanHelper")
                && (mn.name.startsWith("collection") || mn.name.startsWith("map"))) {
            return CONTAINER_BOOLEAN;
        }
    }
    return super.naryOperation(insn, values);
}

From source file:org.evosuite.instrumentation.coverage.LCSAJsInstrumentation.java

License:Open Source License

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
//using external lib
@Override/*from www. ja  v a 2  s .  co m*/
public void analyze(ClassLoader classLoader, MethodNode mn, String className, String methodName, int access) {

    Queue<LCSAJ> lcsaj_queue = new LinkedList<LCSAJ>();
    HashSet<Integer> targets_reached = new HashSet<Integer>();

    AbstractInsnNode start = mn.instructions.getFirst();
    int startID = 0;

    // TODO: This should replace the hack below
    if (methodName.startsWith("<init>")) {
        Iterator<AbstractInsnNode> j = mn.instructions.iterator();
        boolean constructorInvoked = false;
        while (j.hasNext()) {
            AbstractInsnNode in = j.next();
            startID++;
            if (!constructorInvoked) {
                if (in.getOpcode() == Opcodes.INVOKESPECIAL) {
                    MethodInsnNode cn = (MethodInsnNode) in;
                    Collection<String> superClasses = DependencyAnalysis.getInheritanceTree()
                            .getSuperclasses(className);
                    superClasses.add(className);
                    String classNameWithDots = ResourceList.getClassNameFromResourcePath(cn.owner);
                    if (superClasses.contains(classNameWithDots)) {
                        constructorInvoked = true;
                        break;
                    }
                } else {
                    continue;
                }
            }
        }
    }

    /*
    if (methodName.startsWith("<init>")) {
       if (mn.instructions.size() >= 4) {
    start = mn.instructions.get(4);
    startID = 4;
       }
    }
    */

    LCSAJ a = new LCSAJ(className, methodName, BytecodeInstructionPool.getInstance(classLoader)
            .getInstruction(className, methodName, startID, start));
    lcsaj_queue.add(a);

    targets_reached.add(0);

    ArrayList<TryCatchBlockNode> tc_blocks = (ArrayList<TryCatchBlockNode>) mn.tryCatchBlocks;

    for (TryCatchBlockNode t : tc_blocks) {
        LCSAJ b = new LCSAJ(className, methodName, BytecodeInstructionPool.getInstance(classLoader)
                .getInstruction(className, methodName, mn.instructions.indexOf(t.handler), t.handler));
        lcsaj_queue.add(b);
    }

    while (!lcsaj_queue.isEmpty()) {

        LCSAJ currentLCSAJ = lcsaj_queue.poll();
        int position = mn.instructions.indexOf(currentLCSAJ.getLastNodeAccessed());
        // go to next bytecode instruction
        position++;

        if (position >= mn.instructions.size()) {
            // New LCSAJ for current + return
            LCSAJPool.add_lcsaj(className, methodName, currentLCSAJ);
            continue;
        }

        AbstractInsnNode next = mn.instructions.get(position);
        currentLCSAJ.lookupInstruction(position, BytecodeInstructionPool.getInstance(classLoader)
                .getInstruction(className, methodName, position, next));

        if (next instanceof JumpInsnNode) {

            JumpInsnNode jump = (JumpInsnNode) next;
            // New LCSAJ for current + jump to target
            LCSAJPool.add_lcsaj(className, methodName, currentLCSAJ);
            LabelNode target = jump.label;
            int targetPosition = mn.instructions.indexOf(target);

            if (jump.getOpcode() != Opcodes.GOTO) {

                LCSAJ copy = new LCSAJ(currentLCSAJ);
                lcsaj_queue.add(copy);

            }

            if (!targets_reached.contains(targetPosition)) {
                LCSAJ c = new LCSAJ(className, methodName, BytecodeInstructionPool.getInstance(classLoader)
                        .getInstruction(className, methodName, targetPosition, target));
                lcsaj_queue.add(c);

                targets_reached.add(targetPosition);
            }

        } else if (next instanceof TableSwitchInsnNode) {

            TableSwitchInsnNode tswitch = (TableSwitchInsnNode) next;
            List<LabelNode> allTargets = tswitch.labels;

            for (LabelNode target : allTargets) {

                int targetPosition = mn.instructions.indexOf(target);

                if (!targets_reached.contains(targetPosition)) {

                    LCSAJ b = new LCSAJ(className, methodName, BytecodeInstructionPool.getInstance(classLoader)
                            .getInstruction(className, methodName, targetPosition, target));
                    lcsaj_queue.add(b);

                    targets_reached.add(targetPosition);
                }
            }

        } else if (next instanceof InsnNode) {
            InsnNode insn = (InsnNode) next;
            // New LCSAJ for current + throw / return
            if (insn.getOpcode() == Opcodes.ATHROW || insn.getOpcode() == Opcodes.RETURN
                    || insn.getOpcode() == Opcodes.ARETURN || insn.getOpcode() == Opcodes.IRETURN
                    || insn.getOpcode() == Opcodes.DRETURN || insn.getOpcode() == Opcodes.LRETURN
                    || insn.getOpcode() == Opcodes.FRETURN) {

                LCSAJPool.add_lcsaj(className, methodName, currentLCSAJ);
            } else
                lcsaj_queue.add(currentLCSAJ);
        } else
            lcsaj_queue.add(currentLCSAJ);
    }

    if (Properties.STRATEGY != Strategy.EVOSUITE)
        addInstrumentation(classLoader, mn, className, methodName);

    //      if (Properties.WRITE_CFG)
    //         for (LCSAJ l : LCSAJPool.getLCSAJs(className, methodName)) {
    //            LCSAJGraph graph = new LCSAJGraph(l, false);
    //            String graphDestination = "evosuite-graphs/LCSAJGraphs/" + className
    //                    + "/" + methodName;
    //            File dir = new File(graphDestination);
    //            if (dir.mkdirs())
    //               graph.generate(new File(graphDestination + "/LCSAJGraph no: "
    //                       + l.getID() + ".dot"));
    //            else if (dir.exists())
    //               graph.generate(new File(graphDestination + "/LCSAJGraph no: "
    //                       + l.getID() + ".dot"));
    //         }
}

From source file:org.evosuite.instrumentation.coverage.MutationInstrumentation.java

License:Open Source License

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override/*  ww w  .  jav a 2 s .  co  m*/
public void analyze(ClassLoader classLoader, MethodNode mn, String className, String methodName, int access) {

    if (methodName.startsWith("<clinit>"))
        return;

    if (methodName.startsWith(ClassResetter.STATIC_RESET))
        return;

    RawControlFlowGraph graph = GraphPool.getInstance(classLoader).getRawCFG(className, methodName);
    Iterator<AbstractInsnNode> j = mn.instructions.iterator();

    getFrames(mn, className);

    boolean constructorInvoked = false;
    if (!methodName.startsWith("<init>"))
        constructorInvoked = true;

    logger.info("Applying mutation operators ");
    int frameIndex = 0;
    int numMutants = 0;
    if (frames.length != mn.instructions.size()) {
        logger.error("Number of frames does not match number number of bytecode instructions: " + frames.length
                + "/" + mn.instructions.size());
        logger.error("Skipping mutation of method " + className + "." + methodName);
        return;
    }
    //assert (frames.length == mn.instructions.size()) : "Length " + frames.length
    //        + " vs " + mn.instructions.size();
    while (j.hasNext()) {
        Frame currentFrame = frames[frameIndex++];
        AbstractInsnNode in = j.next();
        if (!constructorInvoked) {
            if (in.getOpcode() == Opcodes.INVOKESPECIAL) {
                if (className.matches(".*\\$\\d+$")) {
                    // We will not find the superclasses of an anonymous class this way
                    // so best not mutate the constructor
                    continue;
                }
                MethodInsnNode cn = (MethodInsnNode) in;
                Set<String> superClasses = new HashSet<String>();
                if (DependencyAnalysis.getInheritanceTree() != null
                        && DependencyAnalysis.getInheritanceTree().hasClass(className))
                    superClasses.addAll(DependencyAnalysis.getInheritanceTree().getSuperclasses(className));
                superClasses.add(className);
                String classNameWithDots = ResourceList.getClassNameFromResourcePath(cn.owner);
                if (superClasses.contains(classNameWithDots)) {
                    constructorInvoked = true;
                }
            } else {
                continue;
            }
        }

        boolean inInstrumentation = false;
        for (BytecodeInstruction v : graph.vertexSet()) {

            // If the bytecode is instrumented by EvoSuite, then don't mutate
            if (v.isLabel()) {
                LabelNode labelNode = (LabelNode) v.getASMNode();

                if (labelNode.getLabel() instanceof AnnotatedLabel) {
                    AnnotatedLabel aLabel = (AnnotatedLabel) labelNode.getLabel();
                    if (aLabel.isStartTag()) {
                        inInstrumentation = true;
                    } else {
                        inInstrumentation = false;
                    }
                }
            }
            if (inInstrumentation) {
                continue;
            }
            // If this is in the CFG
            if (in.equals(v.getASMNode())) {
                logger.info(v.toString());
                List<Mutation> mutations = new LinkedList<Mutation>();

                // TODO: More than one mutation operator might apply to the same instruction
                for (MutationOperator mutationOperator : mutationOperators) {

                    if (numMutants++ > Properties.MAX_MUTANTS_PER_METHOD) {
                        logger.info("Reached maximum number of mutants per method");
                        break;
                    }
                    //logger.info("Checking mutation operator on instruction " + v);
                    if (mutationOperator.isApplicable(v)) {
                        logger.info(
                                "Applying mutation operator " + mutationOperator.getClass().getSimpleName());
                        mutations.addAll(mutationOperator.apply(mn, className, methodName, v, currentFrame));
                    }
                }
                if (!mutations.isEmpty()) {
                    logger.info("Adding instrumentation for mutation");
                    //InsnList instrumentation = getInstrumentation(in, mutations);
                    addInstrumentation(mn, in, mutations);
                }
            }
            if (numMutants > Properties.MAX_MUTANTS_PER_METHOD) {
                break;
            }

        }
    }
    j = mn.instructions.iterator();

    logger.info("Result of mutation: ");
    while (j.hasNext()) {
        AbstractInsnNode in = j.next();
        logger.info(new BytecodeInstruction(classLoader, className, methodName, 0, 0, in).toString());
    }
    logger.info("Done.");
    // mn.maxStack += 3;
}

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

License:Open Source License

/** {@inheritDoc} */
@Override/*  w  w w . jav a 2 s.  co m*/
public boolean isApplicable(BytecodeInstruction instruction) {
    AbstractInsnNode node = instruction.getASMNode();
    switch (node.getOpcode()) {
    case Opcodes.ILOAD:
    case Opcodes.LLOAD:
    case Opcodes.FLOAD:
    case Opcodes.DLOAD:
        return true;
    case Opcodes.GETFIELD:
    case Opcodes.GETSTATIC:
        FieldInsnNode fieldNode = (FieldInsnNode) instruction.getASMNode();
        Type type = Type.getType(fieldNode.desc);
        if (type == Type.BYTE_TYPE || type == Type.SHORT_TYPE || type == Type.LONG_TYPE
                || type == Type.FLOAT_TYPE || type == Type.DOUBLE_TYPE || type == Type.BOOLEAN_TYPE
                || type == Type.INT_TYPE) {
            return true;
        }
    default:
        return false;
    }
}