Example usage for org.objectweb.asm Opcodes INVOKESPECIAL

List of usage examples for org.objectweb.asm Opcodes INVOKESPECIAL

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes INVOKESPECIAL.

Prototype

int INVOKESPECIAL

To view the source code for org.objectweb.asm Opcodes INVOKESPECIAL.

Click Source Link

Usage

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

License:Open Source License

@Override
public boolean transform() {
    MethodNode callOrig = getMethod(ConstantMembers.callOrig);
    InsnList instructions = new InsnList();

    Type[] args = Type.getArgumentTypes(callOrig.desc);
    addInstructionsForLoadArguments(instructions, args, false);

    instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, superClassName,
            ConstantMembers.callOrig.getName(), ConstantMembers.callOrig.getSignature()));
    instructions.add(new InsnNode(Opcodes.ARETURN));
    addNewLabelToSwitch(callOrig.instructions, instructions, joinpointId);
    callOrig.maxStack = Math.max(callOrig.maxStack, args.length + 1);
    return true;//from  w  ww.  j a v a 2s .c o m
}

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

License:Open Source License

@Override
protected void addInstructionForDefaultLabel(MethodNode method) {
    if (superClassName.equals("java/lang/Object")) {
        method.instructions.add(new TypeInsnNode(Opcodes.NEW, "org/objectteams/NoSuchMethodError"));
        method.instructions.add(new InsnNode(Opcodes.DUP));
        method.instructions.add(new IntInsnNode(Opcodes.ILOAD, getFirstArgIndex())); // accessId
        method.instructions.add(new LdcInsnNode(clazz.getName())); // current class
        method.instructions.add(new LdcInsnNode("decapsulating access")); // access reason
        method.instructions.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, "org/objectteams/NoSuchMethodError",
                "<init>", "(ILjava/lang/String;Ljava/lang/String;)V", false));
        method.instructions.add(new InsnNode(Opcodes.ATHROW));
    } else {/*w w  w .  j  av a2s  . c  om*/
        Type[] args = Type.getArgumentTypes(method.desc);
        addInstructionsForLoadArguments(method.instructions, args, getMethod().isStatic());

        int opcode = Opcodes.INVOKESPECIAL;
        if (getMethod().isStatic()) {
            opcode = Opcodes.INVOKESTATIC;
        }
        method.instructions.add(
                new MethodInsnNode(opcode, superClassName, getMethod().getName(), getMethod().getSignature()));
        method.instructions.add(new InsnNode(Opcodes.ARETURN));
    }
}

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://  w w w .  j a  v  a 2s  .c  om
    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.evosuite.graphs.cfg.ASMWrapper.java

License:Open Source License

/**
 * <p>/*from ww w. j  av  a 2 s . co  m*/
 * isInvokeSpecial
 * </p>
 * 
 * @return a boolean.
 */
public boolean isInvokeSpecial() {
    return asmNode.getOpcode() == Opcodes.INVOKESPECIAL;
}

From source file:org.evosuite.graphs.cfg.BytecodeInstructionPool.java

License:Open Source License

/**
 * Determine how many bytes the current instruction occupies together with
 * its operands//  www.j  a va  2 s .  c o  m
 * 
 * @return
 */
private int getBytecodeIncrement(AbstractInsnNode instructionNode) {
    int opcode = instructionNode.getOpcode();
    switch (opcode) {
    case Opcodes.ALOAD: // index
    case Opcodes.ASTORE: // index
    case Opcodes.DLOAD:
    case Opcodes.DSTORE:
    case Opcodes.FLOAD:
    case Opcodes.FSTORE:
    case Opcodes.ILOAD:
    case Opcodes.ISTORE:
    case Opcodes.LLOAD:
    case Opcodes.LSTORE:
        VarInsnNode varNode = (VarInsnNode) instructionNode;
        if (varNode.var > 3)
            return 1;
        else
            return 0;
    case Opcodes.BIPUSH: // byte
    case Opcodes.NEWARRAY:
    case Opcodes.RET:
        return 1;
    case Opcodes.LDC:
        LdcInsnNode ldcNode = (LdcInsnNode) instructionNode;
        if (ldcNode.cst instanceof Double || ldcNode.cst instanceof Long)
            return 2; // LDC2_W
        else
            return 1;
    case 19: //LDC_W
    case 20: //LDC2_W
        return 2;
    case Opcodes.ANEWARRAY: // indexbyte1, indexbyte2
    case Opcodes.CHECKCAST: // indexbyte1, indexbyte2
    case Opcodes.GETFIELD:
    case Opcodes.GETSTATIC:
    case Opcodes.GOTO:
    case Opcodes.IF_ACMPEQ:
    case Opcodes.IF_ACMPNE:
    case Opcodes.IF_ICMPEQ:
    case Opcodes.IF_ICMPNE:
    case Opcodes.IF_ICMPGE:
    case Opcodes.IF_ICMPGT:
    case Opcodes.IF_ICMPLE:
    case Opcodes.IF_ICMPLT:
    case Opcodes.IFLE:
    case Opcodes.IFLT:
    case Opcodes.IFGE:
    case Opcodes.IFGT:
    case Opcodes.IFNE:
    case Opcodes.IFEQ:
    case Opcodes.IFNONNULL:
    case Opcodes.IFNULL:
    case Opcodes.IINC:
    case Opcodes.INSTANCEOF:
    case Opcodes.INVOKESPECIAL:
    case Opcodes.INVOKESTATIC:
    case Opcodes.INVOKEVIRTUAL:
    case Opcodes.JSR:
    case Opcodes.NEW:
    case Opcodes.PUTFIELD:
    case Opcodes.PUTSTATIC:
    case Opcodes.SIPUSH:
        // case Opcodes.LDC_W
        // case Opcodes.LDC2_W

        return 2;
    case Opcodes.MULTIANEWARRAY:
        return 3;
    case Opcodes.INVOKEDYNAMIC:
    case Opcodes.INVOKEINTERFACE:
        return 4;

    case Opcodes.LOOKUPSWITCH:
    case Opcodes.TABLESWITCH:
        // TODO: Could be more
        return 4;
    // case Opcodes.GOTO_W 
    // case Opcodes.JSR_W
    }
    return 0;
}

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

License:Open Source License

/** {@inheritDoc} */
@Override/*from w  ww . j a v  a2  s  . c  om*/
public void visitIntInsn(int opcode, int operand) {
    if (opcode == Opcodes.NEWARRAY) {
        Label origTarget = new Label();
        visitInsn(Opcodes.DUP);
        visitFieldInsn(Opcodes.GETSTATIC, PackageInfo.getNameWithSlash(org.evosuite.Properties.class),
                "ARRAY_LIMIT", "I");
        super.visitJumpInsn(Opcodes.IF_ICMPLT, origTarget);
        super.visitTypeInsn(Opcodes.NEW, PackageInfo.getNameWithSlash(TestCaseExecutor.TimeoutExceeded.class));
        super.visitInsn(Opcodes.DUP);
        super.visitMethodInsn(Opcodes.INVOKESPECIAL,
                PackageInfo.getNameWithSlash(TestCaseExecutor.TimeoutExceeded.class), "<init>", "()V", false);
        super.visitInsn(Opcodes.ATHROW);
        super.visitLabel(origTarget);

    }
    super.visitIntInsn(opcode, operand);
}

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

License:Open Source License

/** {@inheritDoc} */
@Override/*from   w w w  .  ja  va  2 s. c o  m*/
public void visitTypeInsn(int opcode, String type) {

    if (opcode == Opcodes.ANEWARRAY) {
        Label origTarget = new Label();
        visitInsn(Opcodes.DUP);
        visitFieldInsn(Opcodes.GETSTATIC, PackageInfo.getNameWithSlash(org.evosuite.Properties.class),
                "ARRAY_LIMIT", "I");
        super.visitJumpInsn(Opcodes.IF_ICMPLT, origTarget);
        super.visitTypeInsn(Opcodes.NEW, PackageInfo.getNameWithSlash(TestCaseExecutor.TimeoutExceeded.class));
        super.visitInsn(Opcodes.DUP);
        super.visitMethodInsn(Opcodes.INVOKESPECIAL,
                PackageInfo.getNameWithSlash(TestCaseExecutor.TimeoutExceeded.class), "<init>", "()V", false);
        super.visitInsn(Opcodes.ATHROW);
        super.visitLabel(origTarget);

    }
    super.visitTypeInsn(opcode, type);
}

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

License:Open Source License

/** {@inheritDoc} */
@Override//from w  w  w . j a v  a  2s .co  m
public void visitMultiANewArrayInsn(String desc, int dims) {

    Label origTarget = new Label();
    Label errorTarget = new Label();

    // Multidimensional arrays can only have max 256 dimensions
    if (Properties.ARRAY_LIMIT < 256) {
        push(dims);
        visitFieldInsn(Opcodes.GETSTATIC, PackageInfo.getNameWithSlash(org.evosuite.Properties.class),
                "ARRAY_LIMIT", "I");
        super.visitJumpInsn(Opcodes.IF_ICMPGE, errorTarget);
    }

    // Check each of the dimensions
    Map<Integer, Integer> to = new HashMap<Integer, Integer>();
    for (int i = dims - 1; i >= 0; i--) {
        int loc = newLocal(Type.INT_TYPE);
        storeLocal(loc);
        to.put(i, loc);
    }
    for (int i = 0; i < dims; i++) {
        loadLocal(to.get(i));
        visitFieldInsn(Opcodes.GETSTATIC, "org/evosuite/Properties", "ARRAY_LIMIT", "I");
        super.visitJumpInsn(Opcodes.IF_ICMPGE, errorTarget);
    }
    goTo(origTarget);
    super.visitLabel(errorTarget);
    super.visitTypeInsn(Opcodes.NEW, PackageInfo.getNameWithSlash(TestCaseExecutor.TimeoutExceeded.class));
    super.visitInsn(Opcodes.DUP);
    super.visitMethodInsn(Opcodes.INVOKESPECIAL,
            PackageInfo.getNameWithSlash(TestCaseExecutor.TimeoutExceeded.class), "<init>", "()V", false);
    super.visitInsn(Opcodes.ATHROW);
    super.visitLabel(origTarget);

    // Restore original dimensions
    for (int i = 0; i < dims; i++) {
        loadLocal(to.get(i));
    }

    super.visitMultiANewArrayInsn(desc, dims);
}

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

License:Open Source License

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
//using external lib
@Override/*  w  w  w  . ja va2  s.  c o  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;
}