Java Code Examples for org.apache.bcel.generic.InstructionHandle#getNext()

The following examples show how to use org.apache.bcel.generic.InstructionHandle#getNext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NoiseNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isThrower(BasicBlock target) {
    InstructionHandle ins = target.getFirstInstruction();
    int maxCount = 7;
    while (ins != null) {
        if (maxCount-- <= 0) {
            break;
        }
        Instruction i = ins.getInstruction();
        if (i instanceof ATHROW) {
            return true;
        }
        if (i instanceof InstructionTargeter || i instanceof ReturnInstruction) {
            return false;
        }
        ins = ins.getNext();
    }
    return false;
}
 
Example 2
Source File: FindTwoLockWait.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean preScreen(MethodGen mg) {
    ConstantPoolGen cpg = mg.getConstantPool();

    int lockCount = mg.isSynchronized() ? 1 : 0;
    boolean sawWaitOrNotify = false;

    InstructionHandle handle = mg.getInstructionList().getStart();
    while (handle != null && !(lockCount >= 2 && sawWaitOrNotify)) {
        Instruction ins = handle.getInstruction();
        if (ins instanceof MONITORENTER) {
            ++lockCount;
        } else if (ins instanceof INVOKEVIRTUAL) {
            INVOKEVIRTUAL inv = (INVOKEVIRTUAL) ins;
            String methodName = inv.getMethodName(cpg);
            if ("wait".equals(methodName) || methodName.startsWith("notify")) {
                sawWaitOrNotify = true;
            }
        }

        handle = handle.getNext();
    }

    return lockCount >= 2 && sawWaitOrNotify;
}
 
Example 3
Source File: DuplicateBranches.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private InstructionHandle findThenFinish(CFG cfg, BasicBlock thenBB, int elsePos) {
    InstructionHandle inst = thenBB.getFirstInstruction();
    while (inst == null) {
        Iterator<Edge> ie = cfg.outgoingEdgeIterator(thenBB);
        while (ie.hasNext()) {
            Edge e = ie.next();
            if (e.getType() == EdgeTypes.FALL_THROUGH_EDGE) {
                thenBB = e.getTarget();
                break;
            }
        }
        inst = thenBB.getFirstInstruction();
    }

    InstructionHandle lastIns = inst;
    while (inst.getPosition() < elsePos) {
        lastIns = inst;
        inst = inst.getNext();
    }

    return lastIns;
}
 
Example 4
Source File: UnconditionalValueDerefAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isNullCheck(InstructionHandle h, ConstantPoolGen cpg) {
    if (!(h.getInstruction() instanceof IFNONNULL)) {
        return false;
    }
    h = h.getNext();
    final Instruction newInstruction = h.getInstruction();
    if (!(newInstruction instanceof NEW)) {
        return false;
    }
    final ObjectType loadClassType = ((NEW) newInstruction).getLoadClassType(cpg);
    if (!"java.lang.NullPointerException".equals(loadClassType.getClassName())) {
        return false;
    }
    h = h.getNext();
    return check(h, NULLCHECK1) || check(h, NULLCHECK2);

}
 
Example 5
Source File: RedundantConditions.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @param methodGen method
 * @param start instruction to scan
 * @return instruction which consumes value which was on top of stack before start instruction
 * or null if cannot be determined
 */
private InstructionHandle getConsumer(MethodGen methodGen, InstructionHandle start) {
    int depth = 1;
    InstructionHandle cur = start;
    while (cur != null) {
        Instruction inst = cur.getInstruction();
        depth -= inst.consumeStack(methodGen.getConstantPool());
        if (depth <= 0) {
            return cur;
        }
        depth += inst.produceStack(methodGen.getConstantPool());
        if (inst instanceof BranchInstruction) {
            if (inst instanceof GotoInstruction) {
                cur = ((GotoInstruction) inst).getTarget();
                continue;
            }
            if (!(inst instanceof IfInstruction)) {
                return null;
            }
        }
        cur = cur.getNext();
    }
    return null;
}
 
Example 6
Source File: FindNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isThrower(BasicBlock target) {
    InstructionHandle ins = target.getFirstInstruction();
    int maxCount = 7;
    while (ins != null) {
        if (maxCount-- <= 0) {
            break;
        }
        Instruction i = ins.getInstruction();
        if (i instanceof ATHROW) {
            return true;
        }
        if (i instanceof InstructionTargeter || i instanceof ReturnInstruction) {
            return false;
        }
        ins = ins.getNext();
    }
    return false;
}
 
Example 7
Source File: UnconditionalValueDerefAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static boolean check(InstructionHandle h, int[] opcodes) {
    for (int opcode : opcodes) {
        if (h == null) {
            return false;
        }
        short opcode2 = h.getInstruction().getOpcode();
        if (opcode == Const.LDC) {
            switch (opcode2) {
            case Const.LDC:
            case Const.ALOAD:
            case Const.ALOAD_0:
            case Const.ALOAD_1:
            case Const.ALOAD_2:
            case Const.ALOAD_3:
                break;
            default:
                return false;
            }
        } else if (opcode2 != opcode) {
            return false;
        }
        h = h.getNext();
    }
    return true;
}
 
Example 8
Source File: FindNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
boolean callToAssertionMethod(Location loc) {

        InstructionHandle h = loc.getHandle();
        int firstPos = h.getPosition();

        LineNumberTable ln = method.getLineNumberTable();
        int firstLine = ln == null ? -1 : ln.getSourceLine(firstPos);

        while (h != null) {
            int pos = h.getPosition();

            if (ln == null) {
                if (pos > firstPos + 15) {
                    break;
                }
            } else {
                int line = ln.getSourceLine(pos);
                if (line != firstLine) {
                    break;
                }
            }
            Instruction i = h.getInstruction();
            if (i instanceof InvokeInstruction) {
                InvokeInstruction ii = (InvokeInstruction) i;
                String name = ii.getMethodName(classContext.getConstantPoolGen());
                if (name.startsWith("check") || name.startsWith("assert")) {
                    return true;
                }
            }
            h = h.getNext();
        }

        return false;
    }
 
Example 9
Source File: BCELPerfTest.java    From annotation-tools with MIT License 5 votes vote down vote up
byte[] nullAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClass().getBytes();
}
 
Example 10
Source File: BCELPerfTest.java    From annotation-tools with MIT License 5 votes vote down vote up
byte[] nullAdaptClass(final InputStream is, final String name)
        throws Exception
{
    JavaClass jc = new ClassParser(is, name + ".class").parse();
    ClassGen cg = new ClassGen(jc);
    ConstantPoolGen cp = cg.getConstantPool();
    Method[] ms = cg.getMethods();
    for (int j = 0; j < ms.length; ++j) {
        MethodGen mg = new MethodGen(ms[j], cg.getClassName(), cp);
        boolean lv = ms[j].getLocalVariableTable() == null;
        boolean ln = ms[j].getLineNumberTable() == null;
        if (lv) {
            mg.removeLocalVariables();
        }
        if (ln) {
            mg.removeLineNumbers();
        }
        mg.stripAttributes(skipDebug);
        InstructionList il = mg.getInstructionList();
        if (il != null) {
            InstructionHandle ih = il.getStart();
            while (ih != null) {
                ih = ih.getNext();
            }
            if (compute) {
                mg.setMaxStack();
                mg.setMaxLocals();
            }
        }
        cg.replaceMethod(ms[j], mg.getMethod());
    }
    return cg.getJavaClass().getBytes();
}
 
Example 11
Source File: CFG.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void checkIntegrity() {
    // Ensure that basic blocks have only consecutive instructions
    for (Iterator<BasicBlock> i = blockIterator(); i.hasNext();) {
        BasicBlock basicBlock = i.next();
        InstructionHandle prev = null;
        for (Iterator<InstructionHandle> j = basicBlock.instructionIterator(); j.hasNext();) {
            InstructionHandle handle = j.next();
            if (prev != null && prev.getNext() != handle) {
                throw new IllegalStateException("Non-consecutive instructions in block " + basicBlock.getLabel() + ": prev="
                        + prev + ", handle=" + handle);
            }
            prev = handle;
        }
    }
}
 
Example 12
Source File: HandleTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Assert that opposite next/prev pairs always match.
 */
static void checkLinkage(final InstructionHandle ih, final int index) {
    final InstructionHandle prev = ih.getPrev();
    final InstructionHandle next = ih.getNext();
    if ((prev != null && prev.getNext() != ih) || (next != null && next.getPrev() != ih)) {
        final AssertionFailedError error = new AssertionFailedError("corrupt instruction list at index " + index);
        exception = error;
        throw error;
    }
}
 
Example 13
Source File: LoadOfKnownNullValue.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param classContext
 * @param nextHandle
 * @param next
 */
private boolean isNullTestedClose(ClassContext classContext, ALOAD load, InstructionHandle nextHandle, Instruction next) {
    if (!(next instanceof IFNULL)) {
        return false;
    }

    IFNULL ifNull = (IFNULL) next;
    InstructionHandle nextNextHandle = nextHandle.getNext(); // aload
    if (nextNextHandle == null) {
        return false;
    }
    Instruction nextInstruction = nextNextHandle.getInstruction();

    if (!(nextInstruction instanceof ALOAD)) {
        return false;
    }
    ALOAD nextLoad = (ALOAD) nextInstruction;
    if (load.getIndex() != nextLoad.getIndex()) {
        return false;
    }
    InstructionHandle nextNextNextHandle = nextNextHandle.getNext(); // invoke
    if (nextNextNextHandle == null) {
        return false;
    }
    Instruction nextNextNextInstruction = nextNextNextHandle.getInstruction();
    if (!(nextNextNextInstruction instanceof INVOKEVIRTUAL)) {
        return false;
    }
    INVOKEVIRTUAL invokeVirtual = (INVOKEVIRTUAL) nextNextNextInstruction;
    String methodName = invokeVirtual.getMethodName(classContext.getConstantPoolGen());
    String methodSig = invokeVirtual.getSignature(classContext.getConstantPoolGen());
    if (!"close".equals(methodName) || !"()V".equals(methodSig)) {
        return false;
    }
    InstructionHandle nextNextNextNextHandle = nextNextNextHandle.getNext(); // after
    return ifNull.getTarget() == nextNextNextNextHandle;
}
 
Example 14
Source File: FindUnreleasedLock.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void inspectResult(ClassContext classContext, MethodGen methodGen, CFG cfg,
        Dataflow<ResourceValueFrame, ResourceValueAnalysis<Lock>> dataflow, Lock resource) {

    JavaClass javaClass = classContext.getJavaClass();

    ResourceValueFrame exitFrame = dataflow.getResultFact(cfg.getExit());
    if (DEBUG) {
        System.out.println("Resource value at exit: " + exitFrame);
    }
    int exitStatus = exitFrame.getStatus();

    if (exitStatus == ResourceValueFrame.OPEN || exitStatus == ResourceValueFrame.OPEN_ON_EXCEPTION_PATH) {
        String bugType;
        int priority;
        if (exitStatus == ResourceValueFrame.OPEN) {
            bugType = "UL_UNRELEASED_LOCK";
            priority = HIGH_PRIORITY;
        } else {
            bugType = "UL_UNRELEASED_LOCK_EXCEPTION_PATH";
            priority = NORMAL_PRIORITY;
        }

        String sourceFile = javaClass.getSourceFileName();
        Location location = resource.getLocation();
        InstructionHandle handle = location.getHandle();
        InstructionHandle nextInstruction = handle.getNext();
        if (nextInstruction.getInstruction() instanceof RETURN) {
            return; // don't report as error; intentional
        }
        bugAccumulator.accumulateBug(new BugInstance(this, bugType, priority).addClassAndMethod(methodGen, sourceFile),
                SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle));
    }
}
 
Example 15
Source File: FinallyDuplicatesInfoFactory.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private int equalBlocks(InstructionHandle ih1, InstructionHandle ih2, int length, int[] positions) {
    if (length == 0) {
        return -1;
    }
    if (ih1 == null || ih2 == null) {
        return -1;
    }
    int start1 = ih1.getPosition();
    int start2 = ih2.getPosition();
    int startNum1 = getInstructionNumber(positions, start1);
    int startNum2 = getInstructionNumber(positions, start2);
    Map<Integer, Integer> lvMap = new HashMap<>();
    while (true) {
        if (ih1 == null || ih2 == null) {
            return -1;
        }
        Instruction inst1 = ih1.getInstruction();
        Instruction inst2 = ih2.getInstruction();
        if (!inst1.equals(inst2)) {
            if (inst1 instanceof LocalVariableInstruction && inst2 instanceof LocalVariableInstruction) {
                if (inst1.getClass() != inst2.getClass()) {
                    return -1;
                }
                LocalVariableInstruction lvi1 = (LocalVariableInstruction) inst1;
                LocalVariableInstruction lvi2 = (LocalVariableInstruction) inst2;
                int lv1 = lvi1.getIndex();
                int lv2 = lvi2.getIndex();
                Integer targetLV = lvMap.get(lv1);
                if (targetLV == null) {
                    if (!(lvi1 instanceof StoreInstruction)) {
                        return -1;
                    }
                    lvMap.put(lv1, lv2);
                } else if (targetLV != lv2) {
                    return -1;
                }
            } else {
                if (inst1.getOpcode() != inst2.getOpcode()) {
                    return -1;
                }
                if (!(inst1 instanceof BranchInstruction)) {
                    return -1;
                }
                int target1 = ((BranchInstruction) inst1).getTarget().getPosition();
                int target2 = ((BranchInstruction) inst2).getTarget().getPosition();
                if (!(getInstructionNumber(positions, target1) - startNum1 == getInstructionNumber(positions, target2) - startNum2
                        || (target1 == start1 + length))) {
                    return -1;
                }
            }
        }
        if (ih1.getPosition() - start1 + inst1.getLength() >= length) {
            return ih2.getPosition() + inst2.getLength();
        }
        ih1 = ih1.getNext();
        ih2 = ih2.getNext();
    }
}
 
Example 16
Source File: RedundantConditions.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private int getPriority(MethodDescriptor methodDescriptor, RedundantCondition condition) {
    if (condition.isByType()) {
        // Skip reports which should be reported by another detector
        long number = condition.getNumber().longValue();
        switch (condition.getSignature()) {
        case "I":
            if (number == Integer.MIN_VALUE || number == Integer.MAX_VALUE) {
                // Will be reported as INT_VACUOUS_COMPARISON
                return IGNORE_PRIORITY;
            }
            break;
        case "C":
            if (number <= 0) {
                // Will be reported as INT_BAD_COMPARISON_WITH_NONNEGATIVE_VALUE
                return IGNORE_PRIORITY;
            }
            break;
        case "B":
            if (number < Byte.MIN_VALUE || number >= Byte.MAX_VALUE) {
                // Will be reported as INT_BAD_COMPARISON_WITH_SIGNED_BYTE
                return IGNORE_PRIORITY;
            }
            break;
        default:
            break;
        }
    }
    int priority = condition.isDeadCodeUnreachable() ? HIGH_PRIORITY
            : condition.isBorder()
                    || condition.getSignature().equals("Z") ? LOW_PRIORITY : NORMAL_PRIORITY;
    // check for boolean conversion
    if (condition.getDeadCodeLocation() != null && condition.getLiveCodeLocation() != null && condition.isDeadCodeUnreachable()) {
        InstructionHandle deadHandle = condition.getDeadCodeLocation().getHandle();
        InstructionHandle liveHandle = condition.getLiveCodeLocation().getHandle();
        int deadValue = getIntValue(deadHandle);
        int liveValue = getIntValue(liveHandle);
        if ((deadValue == 0 && liveValue == 1) || (deadValue == 1 && liveValue == 0)) {
            InstructionHandle deadNext = deadHandle.getNext();
            InstructionHandle liveNext = liveHandle.getNext();
            if (deadNext != null && liveNext != null) {
                InstructionHandle middle, after;
                if (deadNext.getNext() == liveHandle) {
                    middle = deadNext;
                    after = liveNext;
                } else if (liveNext.getNext() == deadHandle) {
                    middle = liveNext;
                    after = deadNext;
                } else {
                    return priority;
                }
                if (!(middle.getInstruction() instanceof GOTO) || ((GOTO) middle.getInstruction()).getTarget() != after) {
                    return priority;
                }
                MethodGen methodGen;
                try {
                    methodGen = Global.getAnalysisCache().getMethodAnalysis(MethodGen.class, methodDescriptor);
                } catch (CheckedAnalysisException e) {
                    return priority;
                }
                InstructionHandle consumer = getConsumer(methodGen, after);
                Instruction consumerInst = consumer == null ? null : consumer.getInstruction();
                if (consumerInst != null) {
                    short opcode = consumerInst.getOpcode();
                    if (opcode == Const.IADD || opcode == Const.ISUB || opcode == Const.IMUL
                            || opcode == Const.ISHR || opcode == Const.ISHL || opcode == Const.IUSHR) {
                        // It's actually integer expression with explicit ? 1 : 0 or ? 0 : 1 operation
                        return priority;
                    }
                }
                if (condition.getSignature().equals("Z")) {
                    // Ignore !flag when flag value is known
                    return IGNORE_PRIORITY;
                }
                priority = condition.isBorder() ? LOW_PRIORITY : NORMAL_PRIORITY;
                if (consumerInst instanceof InvokeInstruction) {
                    ConstantPoolGen constantPool = methodGen.getConstantPool();
                    String methodName = ((InvokeInstruction) consumerInst).getMethodName(constantPool);
                    // Ignore values conditions used in assertion methods
                    if ((methodName.equals("assertTrue") || methodName.equals("checkArgument") || methodName.equals("isLegal")
                            || methodName.equals("isTrue"))) {
                        return liveValue == 1 ? condition.isBorder() ? IGNORE_PRIORITY : LOW_PRIORITY : HIGH_PRIORITY;
                    }
                    if ((methodName.equals("assertFalse") || methodName.equals("isFalse"))) {
                        return liveValue == 0 ? condition.isBorder() ? IGNORE_PRIORITY : LOW_PRIORITY : HIGH_PRIORITY;
                    }
                }
            }
        }
    }
    return priority;
}
 
Example 17
Source File: LineNumberMap.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Build the line number information. Should be called before any other
 * methods.
 */
public void build() {
    int numGood = 0, numBytecodes = 0;

    if (DEBUG) {
        System.out.println("Method: " + methodGen.getName() + " - " + methodGen.getSignature() + "in class "
                + methodGen.getClassName());
    }

    // Associate line number information with each InstructionHandle
    LineNumberTable table = methodGen.getLineNumberTable(methodGen.getConstantPool());

    if (table != null && table.getTableLength() > 0) {
        checkTable(table);
        InstructionHandle handle = methodGen.getInstructionList().getStart();
        while (handle != null) {
            int bytecodeOffset = handle.getPosition();
            if (bytecodeOffset < 0) {
                throw new IllegalStateException("Bad bytecode offset: " + bytecodeOffset);
            }
            if (DEBUG) {
                System.out.println("Looking for source line for bytecode offset " + bytecodeOffset);
            }
            int sourceLine;
            try {
                sourceLine = table.getSourceLine(bytecodeOffset);
            } catch (ArrayIndexOutOfBoundsException e) {
                if (LINE_NUMBER_BUG) {
                    throw e;
                } else {
                    sourceLine = -1;
                }
            }
            if (sourceLine >= 0) {
                ++numGood;
            }
            lineNumberMap.put(handle, new LineNumber(bytecodeOffset, sourceLine));
            handle = handle.getNext();
            ++numBytecodes;
        }
        hasLineNumbers = true;

        if (DEBUG) {
            System.out.println("\t" + numGood + "/" + numBytecodes + " had valid line numbers");
        }
    }
}
 
Example 18
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * These are the checks for the satisfaction of constraints which are described in the
 * Java Virtual Machine Specification, Second Edition as Static Constraints on
 * the operands of instructions of Java Virtual Machine Code (chapter 4.8.1).
 * BCEL parses the code array to create an InstructionList and therefore has to check
 * some of these constraints. Additional checks are also implemented here.
 *
 * @throws StaticCodeConstraintException if the verification fails.
 */
private void pass3StaticInstructionOperandsChecks() {
    try {
    // When building up the InstructionList, BCEL has already done all those checks
    // mentioned in The Java Virtual Machine Specification, Second Edition, as
    // "static constraints on the operands of instructions in the code array".
    // TODO: see the do_verify() comments. Maybe we should really work on the
    //       byte array first to give more comprehensive messages.
    // TODO: Review Exception API, possibly build in some "offending instruction" thing
    //       when we're ready to insulate the offending instruction by doing the
    //       above thing.

    // TODO: Implement as much as possible here. BCEL does _not_ check everything.

    final ConstantPoolGen cpg = new ConstantPoolGen(Repository.lookupClass(myOwner.getClassName()).getConstantPool());
    final InstOperandConstraintVisitor v = new InstOperandConstraintVisitor(cpg);

    // Checks for the things BCEL does _not_ handle itself.
    InstructionHandle ih = instructionList.getStart();
    while (ih != null) {
        final Instruction i = ih.getInstruction();

        // An "own" constraint, due to JustIce's new definition of what "subroutine" means.
        if (i instanceof JsrInstruction) {
            final InstructionHandle target = ((JsrInstruction) i).getTarget();
            if (target == instructionList.getStart()) {
                throw new StaticCodeInstructionOperandConstraintException(
                    "Due to JustIce's clear definition of subroutines, no JSR or JSR_W may have a top-level instruction"+
                    " (such as the very first instruction, which is targeted by instruction '"+ih+"' as its target.");
            }
            if (!(target.getInstruction() instanceof ASTORE)) {
                throw new StaticCodeInstructionOperandConstraintException(
                    "Due to JustIce's clear definition of subroutines, no JSR or JSR_W may target anything else"+
                    " than an ASTORE instruction. Instruction '"+ih+"' targets '"+target+"'.");
            }
        }

        // vmspec2, page 134-137
        ih.accept(v);

        ih = ih.getNext();
    }

    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 19
Source File: Peephole.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
private static Method removeNOPs(final MethodGen mg) {
    final InstructionList il = mg.getInstructionList();
    final InstructionFinder f = new InstructionFinder(il);
    final String pat = "NOP+"; // Find at least one NOP
    InstructionHandle next = null;
    int count = 0;

    for (final Iterator<InstructionHandle[]> e = f.search(pat); e.hasNext(); ) {
        final InstructionHandle[] match = e.next();
        final InstructionHandle first = match[0];
        final InstructionHandle last = match[match.length - 1];

        // Some nasty Java compilers may add NOP at end of method.
        if ((next = last.getNext()) == null) {
            break;
        }

        count += match.length;

        // Delete NOPs and redirect any references to them to the following (non-nop) instruction.
        try {
            il.delete(first, last);
        } catch (final TargetLostException e2) {
            for (final InstructionHandle target : e2.getTargets()) {
                for (final InstructionTargeter targeter : target.getTargeters()) {
                    targeter.updateTarget(target, next);
                }
            }
        }
    }

    Method m = null;

    if (count > 0) {
        System.out.println("Removed " + count + " NOP instructions from method " + mg.getName());
        m = mg.getMethod();
    }

    il.dispose(); // Reuse instruction handles
    return m;
}
 
Example 20
Source File: BasicBlock.java    From spotbugs with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Get the successor of given instruction within the basic block.
 *
 * @param handle
 *            the instruction
 * @return the instruction's successor, or null if the instruction is the
 *         last in the basic block
 */
public @CheckForNull InstructionHandle getSuccessorOf(InstructionHandle handle) {
    if (VERIFY_INTEGRITY && !containsInstruction(handle)) {
        throw new IllegalStateException();
    }
    return handle == lastInstruction ? null : handle.getNext();
}