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:com.microsoft.Malmo.OverclockingClassTransformer.java

License:Open Source License

private static void overclockRenderer(ClassNode node, boolean isObfuscated) {
    // We're attempting to turn this line from Minecraft.runGameLoop:
    //          this.updateDisplay();
    // into this:
    //          TimeHelper.updateDisplay();
    // TimeHelper's method then decides whether or not to pass the call on to Minecraft.updateDisplay().

    final String methodName = isObfuscated ? "as" : "runGameLoop";
    final String methodDescriptor = "()V"; // No params, returns void.

    System.out.println("MALMO: Found Minecraft, attempting to transform it");

    for (MethodNode method : node.methods) {
        if (method.name.equals(methodName) && method.desc.equals(methodDescriptor)) {
            System.out.println("MALMO: Found Minecraft.runGameLoop() method, attempting to transform it");
            for (AbstractInsnNode instruction : method.instructions.toArray()) {
                if (instruction.getOpcode() == Opcodes.INVOKEVIRTUAL) {
                    MethodInsnNode visitMethodNode = (MethodInsnNode) instruction;
                    if (visitMethodNode.name.equals(isObfuscated ? "h" : "updateDisplay")) {
                        visitMethodNode.owner = "com/microsoft/Malmo/Utils/TimeHelper";
                        if (isObfuscated) {
                            visitMethodNode.name = "updateDisplay";
                        }/*from w  w w  . j a va  2 s  . c o m*/
                        visitMethodNode.setOpcode(Opcodes.INVOKESTATIC);
                        method.instructions.remove(visitMethodNode.getPrevious()); // ALOAD 0 not needed for static invocation.
                        System.out.println("MALMO: Hooked into call to Minecraft.updateDisplay()");
                    }
                }
            }
        }
    }
}

From source file:com.mogujie.instantrun.IncrementalChangeVisitor.java

License:Apache License

private void insnMachine(AbstractInsnNode node, List<AbstractInsnNode> removeList) {
    if (node.getOpcode() == Opcodes.NEW) {
        if (status == INIT) {
            status = FIND_NEW;/*from w w  w  .  j  ava  2 s  . c om*/
            removeList.add(node);
        } else {
            throw new RuntimeException("find new in status " + status);
        }
    }

    if (node.getOpcode() == Opcodes.DUP) {
        if (status == FIND_NEW) {
            status = INIT;
            removeList.add(node);
        }
    }

    if (node.getOpcode() == Opcodes.INVOKESPECIAL && node instanceof MethodInsnNode) {
        if (status == INIT) {
            MethodInsnNode methodInsnNode = (MethodInsnNode) node;
            if ("<init>".equals(methodInsnNode.name)) {
                if (getMethodAccessRight(methodInsnNode.owner, methodInsnNode.name,
                        methodInsnNode.desc) == AccessRight.PUBLIC) {
                    int removeSize = removeList.size();
                    removeList.remove(removeSize - 1);
                    removeList.remove(removeSize - 2);
                }
            }

        }
    }

}

From source file:com.navercorp.pinpoint.profiler.instrument.ASMMethodNodeAdapter.java

License:Apache License

public void addAfterInterceptor(final int interceptorId, final InterceptorDefinition interceptorDefinition,
        final int apiId) {
    initInterceptorLocalVariables(interceptorId, interceptorDefinition, apiId);

    // add try catch block.
    final ASMTryCatch tryCatch = new ASMTryCatch(this.methodNode);
    this.methodNode.instructions.insertBefore(this.methodVariables.getEnterInsnNode(),
            tryCatch.getStartLabelNode());
    this.methodNode.instructions.insert(this.methodVariables.getExitInsnNode(), tryCatch.getEndLabelNode());

    // find return.
    AbstractInsnNode insnNode = this.methodNode.instructions.getFirst();
    while (insnNode != null) {
        final int opcode = insnNode.getOpcode();
        if (this.methodVariables.isReturnCode(opcode)) {
            final InsnList instructions = new InsnList();
            this.methodVariables.storeResultVar(instructions, opcode);
            invokeAfterInterceptor(instructions, interceptorDefinition, false);
            this.methodNode.instructions.insertBefore(insnNode, instructions);
        }/*from ww w. j  a va  2  s. c  om*/
        insnNode = insnNode.getNext();
    }

    // try catch handler.
    InsnList instructions = new InsnList();
    this.methodVariables.storeThrowableVar(instructions);
    invokeAfterInterceptor(instructions, interceptorDefinition, true);
    // throw exception.
    this.methodVariables.loadInterceptorThrowVar(instructions);
    this.methodNode.instructions.insert(tryCatch.getEndLabelNode(), instructions);
    tryCatch.sort();
}

From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtils.java

License:Open Source License

/**
 * Clones a monitorenter/monitorexit node and returns it as an instruction list.
 * @param insnNode instruction to clone//from   w  w w .  j  a  v a 2  s .  co  m
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if node isn't of invoke type
 * @return instruction list with cloned instruction
 */
public static InsnList cloneMonitorNode(AbstractInsnNode insnNode) {
    Validate.notNull(insnNode);
    Validate.isTrue(insnNode instanceof InsnNode);
    Validate.isTrue(
            insnNode.getOpcode() == Opcodes.MONITORENTER || insnNode.getOpcode() == Opcodes.MONITOREXIT);

    InsnList ret = new InsnList();
    ret.add(insnNode.clone(new HashMap<>()));

    return ret;
}

From source file:com.offbynull.coroutines.instrumenter.asm.SearchUtils.java

License:Open Source License

/**
 * Find instructions in a certain class that are of a certain set of opcodes.
 * @param insnList instruction list to search through
 * @param opcodes opcodes to search for//from w  ww  . j av  a 2s .co  m
 * @return list of instructions that contain the opcodes being searched for
 * @throws NullPointerException if any argument is {@code null}
 * @throws IllegalArgumentException if {@code opcodes} is empty
 */
public static List<AbstractInsnNode> searchForOpcodes(InsnList insnList, int... opcodes) {
    Validate.notNull(insnList);
    Validate.notNull(opcodes);
    Validate.isTrue(opcodes.length > 0);

    List<AbstractInsnNode> ret = new LinkedList<>();

    Set<Integer> opcodeSet = new HashSet<>();
    Arrays.stream(opcodes).forEach((x) -> opcodeSet.add(x));

    Iterator<AbstractInsnNode> it = insnList.iterator();
    while (it.hasNext()) {
        AbstractInsnNode insnNode = it.next();
        if (opcodeSet.contains(insnNode.getOpcode())) {
            ret.add(insnNode);
        }
    }

    return ret;
}

From source file:com.offbynull.coroutines.instrumenter.MethodInstrumenter.java

License:Open Source License

public void instrument(MethodNode methodNode, MethodAttributes attrs) {
    Validate.notNull(methodNode);//  ww  w . j a v  a 2s .co m
    Validate.notNull(attrs);

    // These sanity checks need to exist. The methodNode.instructions.insertBefore/remove methods don't actually check to make sure the
    // instructions they're operating on belong to the method. This is here to make sure that the properties and methodNode match.
    attrs.getContinuationPoints().stream().map(x -> x.getInvokeInstruction())
            .forEach(x -> methodNode.instructions.contains(x));
    attrs.getSynchronizationPoints().stream().map(x -> x.getMonitorInstruction())
            .forEach(x -> methodNode.instructions.contains(x));

    // Add trycatch nodes
    attrs.getContinuationPoints().stream().filter(x -> x instanceof TryCatchInvokeContinuationPoint)
            .map(x -> (TryCatchInvokeContinuationPoint) x).map(x -> x.getTryCatchBlock())
            .forEach(x -> methodNode.tryCatchBlocks.add(0, x));

    // Add loading code (this includes continuation restore points)
    InsnList entryPoint = entryPointLoader(attrs);
    methodNode.instructions.insert(entryPoint);

    // Add continuation save points
    List<ContinuationPoint> continuationPoints = attrs.getContinuationPoints();
    for (int i = 0; i < continuationPoints.size(); i++) {
        ContinuationPoint cp = continuationPoints.get(i);

        AbstractInsnNode nodeToReplace = cp.getInvokeInstruction();
        InsnList insnsToReplaceWith = saveState(attrs, i);

        methodNode.instructions.insertBefore(nodeToReplace, insnsToReplaceWith);
        methodNode.instructions.remove(nodeToReplace);
    }

    // Add synchronization save points
    List<SynchronizationPoint> synchPoints = attrs.getSynchronizationPoints();
    MarkerType markerType = attrs.getSettings().getMarkerType();
    LockVariables lockVars = attrs.getLockVariables();
    for (int i = 0; i < synchPoints.size(); i++) {
        SynchronizationPoint sp = synchPoints.get(i);

        InsnNode nodeToReplace = sp.getMonitorInstruction();
        InsnList insnsToReplaceWith;
        switch (nodeToReplace.getOpcode()) {
        case Opcodes.MONITORENTER:
            insnsToReplaceWith = enterMonitorAndStore(markerType, lockVars);
            break;
        case Opcodes.MONITOREXIT:
            insnsToReplaceWith = exitMonitorAndDelete(markerType, lockVars);
            break;
        default:
            throw new IllegalStateException(); //should never happen
        }

        methodNode.instructions.insertBefore(nodeToReplace, insnsToReplaceWith);
        methodNode.instructions.remove(nodeToReplace);
    }
}

From source file:com.sun.tdk.jcov.instrument.BlockCodeMethodAdapter.java

License:Open Source License

private SimpleBasicBlock[] completeComputationOfCodeLabelNodes() {
    MethodNode methodNode = (MethodNode) mv;
    InsnList instructions = methodNode.instructions;
    int[] allToReal = new int[instructions.size()];
    int allIdx = 0;
    int insnIdx = 0;
    ListIterator iit = instructions.iterator();

    // Create the method entry block and basic block
    AbstractInsnNode insnFirst = peek(iit);
    SimpleBasicBlock bbFirst = getBB(insnFirst, 0);
    // DataBlock blockFirst = new DataBlockMethEnter();
    // bbFirst.add(blockFirst);

    while (iit.hasNext()) {
        AbstractInsnNode insn = (AbstractInsnNode) iit.next();
        allToReal[allIdx++] = insnIdx;//from  www.  j  a  v  a 2 s  . c om
        int bci = bcis[insnIdx];
        int opcode = insn.getOpcode();
        if (opcode < 0) {
            // a pseudo-instruction
            if (insn.getType() == AbstractInsnNode.LINE) {
                LineNumberNode lineNode = (LineNumberNode) insn;
                method().addLineEntry(bci, lineNode.line);
            }
        } else {
            // a real instruction
            ++insnIdx; // advance the real instruction index

            //System.out.println( "#" + (insnIdx - 1) +
            //        " bci: " + bci + "  " +
            //        instr.toString().replace("org.objectweb.asm.tree.", "").replace("@", " @ ") +
            //        " [" + (opcode>=0? Constants.opcNames[opcode] : " pseudo") +"]");
            switch (opcode) {
            case IFEQ:
            case IFNE:
            case IFLT:
            case IFGE:
            case IFGT:
            case IFLE:
            case IF_ICMPEQ:
            case IF_ICMPNE:
            case IF_ICMPLT:
            case IF_ICMPGE:
            case IF_ICMPGT:
            case IF_ICMPLE:
            case IF_ACMPEQ:
            case IF_ACMPNE:
            case IFNULL:
            case IFNONNULL:
            case JSR: {
                JumpInsnNode jumpInsn = (JumpInsnNode) insn;
                LabelNode insnTrue = jumpInsn.label;
                int bciFalse = bcis[insnIdx]; // fall-through

                DataBranchCond branch = new DataBranchCond(method.rootId, bci, bciFalse - 1);
                /* DataBlockTarget blockTrue = new DataBlockTargetCond(true);
                 DataBlockTarget blockFalse = new DataBlockTargetCond(false);
                 branch.addTarget(blockTrue);
                 branch.addTarget(blockFalse);
                 */
                AbstractInsnNode insnFalse = peek(iit);
                assert (insnFalse != null); // must be fall-through code
                SimpleBasicBlock bbTrue = getBB(insnTrue);
                SimpleBasicBlock bbFalse = getBB(insnFalse, bciFalse);

                exits.add(branch);

                // assign a new label for branch counting
                // LabelNode nlab = new LabelNode();
                // jumpInsn.label = nlab;  // branch to new label
                //  bbTrue.add(blockTrue, nlab);

                //bbFalse.add(blockFalse);
                break;
            }

            case TABLESWITCH: {
                TableSwitchInsnNode switchInsn = (TableSwitchInsnNode) insn;

                // Create a block and basic-block the "default:" case
                LabelNode insnDflt = switchInsn.dflt;
                SimpleBasicBlock bbDefault = getBB(insnDflt);
                DataBlockTargetDefault blockDefault = new DataBlockTargetDefault(bbDefault.rootId());

                // assign a new default label for branch counting
                //LabelNode nlab = new LabelNode();
                //switchInsn.dflt = nlab;  // branch to new label
                //bbDefault.add(blockDefault, nlab);

                // Create the branch information
                int bciEnd = bcis[insnIdx] - 1; // end of the switch
                DataBranchSwitch branch = new DataBranchSwitch(method.rootId, bci, bciEnd, blockDefault);
                // branch.addTarget(blockDefault);
                exits.add(branch);

                // Process the other cases
                ListIterator lit = switchInsn.labels.listIterator();
                int key = switchInsn.min;
                while (lit.hasNext()) {
                    // Create a block and basic-block the case
                    LabelNode labCase = (LabelNode) lit.next();
                    SimpleBasicBlock bbCase = getBB(labCase);
                    //DataBlockTargetCase blockCase = new DataBlockTargetCase(key++);
                    //branch.addTarget(blockCase);

                    // assign a new label to the case for branch counting
                    //nlab = new LabelNode();
                    //  lit.set(nlab);
                    // bbCase.add(blockCase, nlab);
                }
                break;
            }

            case LOOKUPSWITCH: {
                LookupSwitchInsnNode switchInsn = (LookupSwitchInsnNode) insn;

                // Create a block and basic-block the "default:" case
                LabelNode insnDflt = switchInsn.dflt;
                SimpleBasicBlock bbDefault = getBB(insnDflt);
                DataBlockTargetDefault blockDefault = new DataBlockTargetDefault(bbDefault.rootId());

                // assign a new default label for branch counting
                // LabelNode nlab = new LabelNode();
                // switchInsn.dflt = nlab;  // branch to new label
                // bbDefault.add(blockDefault, nlab);

                // Create the branch information
                int bciEnd = bcis[insnIdx] - 1; // end of the switch
                DataBranchSwitch branch = new DataBranchSwitch(method.rootId, bci, bciEnd, blockDefault);
                // branch.addTarget(blockDefault);
                exits.add(branch);

                // Process the other cases
                ListIterator kit = switchInsn.keys.listIterator();
                ListIterator lit = switchInsn.labels.listIterator();
                while (lit.hasNext()) {
                    // Create a block and basic-block the case
                    LabelNode labCase = (LabelNode) lit.next();
                    SimpleBasicBlock bbCase = getBB(labCase);
                    Integer key = (Integer) kit.next();
                    //                            DataBlockTargetCase blockCase = new DataBlockTargetCase(key.intValue());
                    // branch.addTarget(blockCase);

                    // assign a new label to the case for branch counting
                    //nlab = new LabelNode();
                    //lit.set(nlab);
                    //bbCase.add(blockCase, nlab);
                }
                break;
            }

            case GOTO: {
                JumpInsnNode jumpInsn = (JumpInsnNode) insn;

                // Create origin info, a branch
                int bciEnd = bcis[insnIdx] - 1;
                DataBranchGoto branch = new DataBranchGoto(method.rootId, bci, bciEnd);
                exits.add(branch);

                // Create destination info, a block target
                LabelNode insnTarget = jumpInsn.label;
                SimpleBasicBlock bbTarget = getBB(insnTarget);
                //DataBlockTarget blockTarget = new DataBlockTargetGoto();
                //branch.addTarget(blockTarget);

                // assign a new label for branch counting
                //LabelNode nlab = new LabelNode();
                //jumpInsn.label = nlab;  // branch to new label
                //bbTarget.add(blockTarget, nlab);
                break;
            }
            case ATHROW:
            case RET:
            case IRETURN:
            case LRETURN:
            case FRETURN:
            case DRETURN:
            case ARETURN:
            case RETURN: {
                int bciNext = bcis[insnIdx];
                DataExit exit = new DataExitSimple(method.rootId, bci, bciNext - 1, insn.getOpcode());
                exits.add(exit);

                AbstractInsnNode insnNext = peek(iit);
                if (insnNext != null) {
                    // If there is code after this, it has to be the start of a
                    // new basic block
                    getBB(insnNext, bciNext);
                }
                break;
            }
            default:
                break;
            }
            // try add src block
        }
    }

    // Now go through the try-catch blocks
    LabelNode previousHandler = null;
    for (Iterator tbit = methodNode.tryCatchBlocks.iterator(); tbit.hasNext();) {
        TryCatchBlockNode tcbn = (TryCatchBlockNode) tbit.next();
        LabelNode insnHandler = tcbn.handler;
        if (insnHandler != previousHandler) {
            previousHandler = insnHandler;

            // Create destination info, a block target
            SimpleBasicBlock bbCatch = getBB(insnHandler);

        }
    }

    if (method().getCharacterRangeTable() != null) {
        boolean newBlock = true;
        int skip = 0;
        iit = instructions.iterator();
        while (iit.hasNext()) {
            AbstractInsnNode insn = (AbstractInsnNode) iit.next();
            int index = instructions.indexOf(insn);
            int bci = bcis[allToReal[index]];
            if (bci == skip) {
                continue;
            }

            if (insnToBB.get(insn) != null) {
                skip = bcis[allToReal[instructions.indexOf(insn)]];
            }

            if (insn.getOpcode() < 0) {
                continue;
            }

            for (CharacterRangeTableAttribute.CRTEntry entry : method().getCharacterRangeTable().getEntries()) {
                if (entry.startBCI() == bci) {

                    if ((entry.flags & CRTEntry.CRT_STATEMENT) != 0 /*& newBlock*/) {
                        newBlock = false;
                        if (insnToBB.get(insn) == null) {
                            //System.out.println("Should add block at: " + bci + " in " + method().name +
                            //       " for " + Constants.opcNames[insn.getOpcode()]);
                            getBB(insn);
                            break;
                        }
                    }
                } else {
                    if (entry.endBCI() == index && (entry.flags & CRTEntry.CRT_FLOW_TARGET) != 0) {
                        newBlock = true;
                    }
                }

            }
        }

    }

    // Compute the startBCI for any basic blocks that don't have it'
    SimpleBasicBlock[] basicBlocks = new SimpleBasicBlock[insnToBB.size()];
    int i = 0;
    for (Map.Entry<AbstractInsnNode, SimpleBasicBlock> entry : insnToBB.entrySet()) {
        SimpleBasicBlock bb = entry.getValue();
        if (bb.startBCI() < 0) {
            AbstractInsnNode insn = entry.getKey();
            int index = instructions.indexOf(insn);
            int bci = bcis[allToReal[index]];
            bb.setStartBCI(bci);
        }
        basicBlocks[i++] = bb;
    }
    Arrays.sort(basicBlocks);

    return basicBlocks;
}

From source file:com.sun.tdk.jcov.instrument.BranchCodeMethodAdapter.java

License:Open Source License

/**
 * Do fix ups so that: There are unique CodeLabelNodes at the beginning of
 * each basic block; All branch-mode blocks hang off CodeLabelNodes Misc
 * info, like case values, are attached Fall throughs from one block to
 * another are computed//from  w  w w  .j a v a2s  .  c  om
 *
 */
private BasicBlock[] completeComputationOfCodeLabelNodes() {
    MethodNode methodNode = (MethodNode) mv;
    InsnList instructions = methodNode.instructions;
    int[] allToReal = new int[instructions.size()];
    int allIdx = 0;
    int insnIdx = 0;
    ListIterator iit = instructions.iterator();

    // Create the method entry block and basic block
    AbstractInsnNode insnFirst = peek(iit);
    BasicBlock bbFirst = getBB(insnFirst, 0);
    DataBlock blockFirst = new DataBlockMethEnter(bbFirst.rootId());
    bbFirst.add(blockFirst);

    while (iit.hasNext()) {
        AbstractInsnNode insn = (AbstractInsnNode) iit.next();
        allToReal[allIdx++] = insnIdx;
        int bci = bcis[insnIdx];
        int opcode = insn.getOpcode();
        if (opcode < 0) {
            // a pseudo-instruction
            if (insn.getType() == AbstractInsnNode.LINE) {
                LineNumberNode lineNode = (LineNumberNode) insn;
                method().addLineEntry(bci, lineNode.line);
            }
        } else {
            // a real instruction
            ++insnIdx; // advance the real instruction index

            //System.out.println( "#" + (insnIdx - 1) +
            //        " bci: " + bci + "  " +
            //        instr.toString().replace("org.objectweb.asm.tree.", "").replace("@", " @ ") +
            //        " [" + (opcode>=0? Constants.opcNames[opcode] : " pseudo") +"]");
            switch (opcode) {
            case IFEQ:
            case IFNE:
            case IFLT:
            case IFGE:
            case IFGT:
            case IFLE:
            case IF_ICMPEQ:
            case IF_ICMPNE:
            case IF_ICMPLT:
            case IF_ICMPGE:
            case IF_ICMPGT:
            case IF_ICMPLE:
            case IF_ACMPEQ:
            case IF_ACMPNE:
            case IFNULL:
            case IFNONNULL: //case JSR:
            {
                JumpInsnNode jumpInsn = (JumpInsnNode) insn;
                LabelNode insnTrue = jumpInsn.label;
                int bciFalse = bcis[insnIdx]; // fall-through

                DataBranchCond branch = new DataBranchCond(method.rootId, bci, bciFalse - 1);
                DataBlockTarget blockTrue = new DataBlockTargetCond(branch.rootId(), true);
                DataBlockTarget blockFalse = new DataBlockTargetCond(branch.rootId(), false);
                branch.addTarget(blockTrue);
                branch.addTarget(blockFalse);

                AbstractInsnNode insnFalse = peek(iit);
                assert (insnFalse != null); // must be fall-through code
                BasicBlock bbTrue = getBB(insnTrue);
                BasicBlock bbFalse = getBB(insnFalse, bciFalse);

                exits.add(branch);

                // assign a new label for branch counting
                LabelNode nlab = new LabelNode();
                jumpInsn.label = nlab; // branch to new label
                bbTrue.add(blockTrue, nlab);

                bbFalse.add(blockFalse);
                break;
            }

            case TABLESWITCH: {
                TableSwitchInsnNode switchInsn = (TableSwitchInsnNode) insn;

                // Create a block and basic-block the "default:" case
                LabelNode insnDflt = switchInsn.dflt;
                BasicBlock bbDefault = getBB(insnDflt);
                DataBlockTargetDefault blockDefault = new DataBlockTargetDefault(bbDefault.rootId());

                // assign a new default label for branch counting
                LabelNode nlab = new LabelNode();
                switchInsn.dflt = nlab; // branch to new label
                bbDefault.add(blockDefault, nlab);

                // Create the branch information
                int bciEnd = bcis[insnIdx] - 1; // end of the switch
                DataBranchSwitch branch = new DataBranchSwitch(method.rootId, bci, bciEnd, blockDefault);
                branch.addTarget(blockDefault);
                exits.add(branch);

                // Process the other cases
                ListIterator lit = switchInsn.labels.listIterator();
                int key = switchInsn.min;
                while (lit.hasNext()) {
                    // Create a block and basic-block the case
                    LabelNode labCase = (LabelNode) lit.next();
                    BasicBlock bbCase = getBB(labCase);
                    DataBlockTargetCase blockCase = new DataBlockTargetCase(bbCase.rootId(), key++);
                    branch.addTarget(blockCase);

                    // assign a new label to the case for branch counting
                    nlab = new LabelNode();
                    lit.set(nlab);
                    bbCase.add(blockCase, nlab);
                }
                break;
            }

            case LOOKUPSWITCH: {
                LookupSwitchInsnNode switchInsn = (LookupSwitchInsnNode) insn;

                // Create a block and basic-block the "default:" case
                LabelNode insnDflt = switchInsn.dflt;
                BasicBlock bbDefault = getBB(insnDflt);
                DataBlockTargetDefault blockDefault = new DataBlockTargetDefault(bbDefault.rootId());

                // assign a new default label for branch counting
                LabelNode nlab = new LabelNode();
                switchInsn.dflt = nlab; // branch to new label
                bbDefault.add(blockDefault, nlab);

                // Create the branch information
                int bciEnd = bcis[insnIdx] - 1; // end of the switch
                DataBranchSwitch branch = new DataBranchSwitch(method.rootId, bci, bciEnd, blockDefault);
                branch.addTarget(blockDefault);
                exits.add(branch);

                // Process the other cases
                ListIterator kit = switchInsn.keys.listIterator();
                ListIterator lit = switchInsn.labels.listIterator();
                while (lit.hasNext()) {
                    // Create a block and basic-block the case
                    LabelNode labCase = (LabelNode) lit.next();
                    BasicBlock bbCase = getBB(labCase);
                    Integer key = (Integer) kit.next();
                    DataBlockTargetCase blockCase = new DataBlockTargetCase(branch.rootId(), key.intValue());
                    branch.addTarget(blockCase);

                    // assign a new label to the case for branch counting
                    nlab = new LabelNode();
                    lit.set(nlab);
                    bbCase.add(blockCase, nlab);
                }
                break;
            }

            case GOTO: {
                JumpInsnNode jumpInsn = (JumpInsnNode) insn;

                // Create origin info, a branch
                int bciEnd = bcis[insnIdx] - 1;
                DataBranchGoto branch = new DataBranchGoto(method.rootId, bci, bciEnd);
                exits.add(branch);

                // Create destination info, a block target
                LabelNode insnTarget = jumpInsn.label;
                BasicBlock bbTarget = getBB(insnTarget);
                DataBlockTarget blockTarget = new DataBlockTargetGoto(bbTarget.rootId());
                branch.addTarget(blockTarget);

                // assign a new label for branch counting
                LabelNode nlab = new LabelNode();
                jumpInsn.label = nlab; // branch to new label
                bbTarget.add(blockTarget, nlab);
                break;
            }
            case ATHROW:
            case RET:
            case IRETURN:
            case LRETURN:
            case FRETURN:
            case DRETURN:
            case ARETURN:
            case RETURN: {
                int bciNext = bcis[insnIdx];
                DataExit exit = new DataExitSimple(method.rootId, bci, bciNext - 1, insn.getOpcode());
                exits.add(exit);

                AbstractInsnNode insnNext = peek(iit);
                if (insnNext != null) {
                    // If there is code after this, it has to be the start of a
                    // new basic block
                    getBB(insnNext, bciNext);
                }
                break;
            }
            default:
                break;
            }
            // try add src block
        }
    }

    // Now go through the try-catch blocks
    LabelNode previousHandler = null;
    for (Iterator tbit = methodNode.tryCatchBlocks.iterator(); tbit.hasNext();) {
        TryCatchBlockNode tcbn = (TryCatchBlockNode) tbit.next();
        LabelNode insnHandler = tcbn.handler;
        if (insnHandler != previousHandler) {
            previousHandler = insnHandler;

            // Create destination info, a block target
            BasicBlock bbCatch = getBB(insnHandler);
            DataBlockCatch blockCatch = new DataBlockCatch(bbCatch.rootId());

            // assign a new label for catch counting
            LabelNode nlab = new LabelNode();
            tcbn.handler = nlab; // change handler
            bbCatch.add(blockCatch, nlab);
        }
    }
    if (method().getCharacterRangeTable() != null) {
        boolean newBlock = true;
        int skip = 0;
        iit = instructions.iterator();
        while (iit.hasNext()) {
            AbstractInsnNode insn = (AbstractInsnNode) iit.next();
            int index = instructions.indexOf(insn);
            int bci = bcis[allToReal[index]];
            if (bci == skip) {
                continue;
            }

            if (insnToBB.get(insn) != null) {
                skip = bcis[allToReal[instructions.indexOf(insn)]];
            }

            if (insn.getOpcode() < 0) {
                continue;
            }

            for (CharacterRangeTableAttribute.CRTEntry entry : method().getCharacterRangeTable().getEntries()) {
                if (entry.startBCI() == bci) {

                    if ((entry.flags & CRTEntry.CRT_STATEMENT) != 0 /*& newBlock*/) {
                        newBlock = false;
                        if (insnToBB.get(insn) == null) {
                            //System.out.println("Should add block at: " + bci + " in " + method().name +
                            //       " for " + Constants.opcNames[insn.getOpcode()]);
                            getBB(insn);
                            break;
                        }
                    }
                } else {
                    if (entry.endBCI() == index && (entry.flags & CRTEntry.CRT_FLOW_TARGET) != 0) {
                        newBlock = true;
                    }
                }

            }
        }

    }

    // Compute the startBCI for any basic blocks that don't have it'
    BasicBlock[] basicBlocks = new BasicBlock[insnToBB.size()];
    int i = 0;
    for (Map.Entry<AbstractInsnNode, BasicBlock> entry : insnToBB.entrySet()) {
        BasicBlock bb = entry.getValue();

        if (bb.startBCI() < 0) {
            AbstractInsnNode insn = entry.getKey();
            int index = instructions.indexOf(insn);
            int bci = bcis[allToReal[index]];
            bb.setStartBCI(bci);
        }
        basicBlocks[i++] = bb;
    }
    Arrays.sort(basicBlocks);

    return basicBlocks;
}

From source file:com.sun.tdk.jcov.instrument.BranchCodeMethodAdapter.java

License:Open Source License

private void debugDump() {
    /* Opcode Names */

    MethodNode methodNode = (MethodNode) mv;
    InsnList instructions = methodNode.instructions;
    ListIterator iit = instructions.iterator();

    System.out.println(methodNode.name + "  ----");
    while (iit.hasNext()) {
        AbstractInsnNode instr = (AbstractInsnNode) iit.next();
        int opcode = instr.getOpcode();
        if (opcode >= 0) {
            System.out.print("        ");
            System.out.print(Constants.opcNames[opcode]);
            System.out.print("  ");
        }//w w  w .  j  av a2  s .co m
        switch (instr.getType()) {
        case LINE:
            System.out.print(((LineNumberNode) instr).line);
            System.out.print("#");
            break;
        case LABEL:
            System.out.print(labelString(((LabelNode) instr)));
            System.out.print(":");
            break;
        case FRAME:
            System.out.print("frame-");
            break;
        case JUMP_INSN:
            System.out.print(labelString(((JumpInsnNode) instr).label));
            break;
        case LOOKUPSWITCH: {
            LookupSwitchInsnNode node = (LookupSwitchInsnNode) instr;
            System.out.println();
            System.out.print("            default: ");
            System.out.print(labelString(node.dflt));
            int len = node.labels.size();
            for (int i = 0; i < len; ++i) {
                LabelNode lnode = (LabelNode) (node.labels.get(i));
                Integer key = (Integer) (node.keys.get(i));
                System.out.println();
                System.out.print("            ");
                System.out.print(key);
                System.out.print(": ");
                System.out.print(labelString(lnode));
            }
            break;
        }
        case TABLESWITCH_INSN: {
            TableSwitchInsnNode node = (TableSwitchInsnNode) instr;
            System.out.println();
            System.out.print("            default: ");
            System.out.print(labelString(node.dflt));
            int len = node.labels.size();
            int key = node.min;
            for (int i = 0; i < len; ++i) {
                LabelNode lnode = (LabelNode) (node.labels.get(i));
                System.out.println();
                System.out.print("            ");
                System.out.print(key++);
                System.out.print(": ");
                System.out.print(labelString(lnode));
            }
            break;
        }
        default:
            break;
        }
        if (insnToBB.get(instr) != null) {
            System.out.println(
                    "  block [" + insnToBB.get(instr).startBCI() + ", " + insnToBB.get(instr).endBCI() + "]");
        } else {
            System.out.println();
        }
    }
}

From source file:com.thomas15v.packetlib.codegenerator.asm.ASMHelper.java

License:MIT License

/**
 * Uses reflection to find an approximate constant name match for the
 * supplied node's opcode/*from  www . j  a v  a2  s . co m*/
 * 
 * @param node Node to query for opcode
 * @return Approximate opcode name (approximate because some constants in
 *      the {@link Opcodes} class have the same value as opcodes
 */
public static String getOpcodeName(AbstractInsnNode node) {
    return ASMHelper.getOpcodeName(node.getOpcode());
}