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

The following examples show how to use org.apache.bcel.generic.InstructionHandle#getPrev() . 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: ValueNumberSourceInfo.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static LocalVariableAnnotation findLocalAnnotationFromValueNumber(Method method, Location location,
        ValueNumber valueNumber, ValueNumberFrame vnaFrame) {

    if (vnaFrame == null || vnaFrame.isBottom() || vnaFrame.isTop()) {
        return null;
    }

    LocalVariableAnnotation localAnnotation = null;
    for (int i = 0; i < vnaFrame.getNumLocals(); i++) {
        if (valueNumber.equals(vnaFrame.getValue(i))) {
            InstructionHandle handle = location.getHandle();
            InstructionHandle prev = handle.getPrev();
            if (prev == null) {
                continue;
            }
            int position1 = prev.getPosition();
            int position2 = handle.getPosition();
            localAnnotation = LocalVariableAnnotation.getLocalVariableAnnotation(method, i, position1, position2);
            if (localAnnotation != null) {
                return localAnnotation;
            }
        }
    }
    return null;
}
 
Example 2
Source File: CFG.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Location getPreviousLocation(Location loc) {
    InstructionHandle handle = loc.getHandle();

    BasicBlock basicBlock = loc.getBasicBlock();
    if (basicBlock.getFirstInstruction().equals(handle)) {
        BasicBlock prevBlock = basicBlock;

        while (true) {
            prevBlock = getPredecessorWithEdgeType(prevBlock, EdgeTypes.FALL_THROUGH_EDGE);
            if (prevBlock == null) {
                return loc;
            }

            handle = prevBlock.getLastInstruction();
            if (handle != null) {
                return new Location(handle, prevBlock);
            }
        }

    } else {
        handle = handle.getPrev();
        return new Location(handle, basicBlock);

    }

}
 
Example 3
Source File: BetterCFGBuilder2.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @param handle instruction handle which loads the object for further GETFIELD/PUTFIELD operation
 * @return true if this object is known to be non-null
 */
private boolean isSafeFieldSource(InstructionHandle handle) {
    while (handle != null && handle.getInstruction().getOpcode() == Const.DUP) {
        // Some compilers generate DUP for field increment code like
        // ALOAD_0 / DUP / GETFIELD x / ICONST_1 / IADD / PUTFIELD x
        handle = handle.getPrev();
    }
    if (handle == null) {
        return false;
    }
    Instruction inst = handle.getInstruction();
    if (inst.getOpcode() == Const.ALOAD_0) {
        return true;
    }
    return inst instanceof GETFIELD && ((GETFIELD) inst).getFieldName(cpg).startsWith("this$");
}
 
Example 4
Source File: FindSqlInjection.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private @CheckForNull InstructionHandle getPreviousInstruction(InstructionHandle handle, boolean skipNops) {
    while (handle.getPrev() != null) {
        handle = handle.getPrev();
        Instruction prevIns = handle.getInstruction();
        if (!(prevIns instanceof NOP && skipNops)) {
            return handle;
        }
    }
    return null;
}
 
Example 5
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 6
Source File: XmlStreamReaderDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    if (seen != Constants.INVOKEVIRTUAL) {
        return;
    }
    String fullClassName = getClassConstantOperand();
    String method = getNameConstantOperand();

    //The method call is doing XML parsing (see class javadoc)
    if (fullClassName.equals("javax/xml/stream/XMLInputFactory") &&
            method.equals("createXMLStreamReader")) {
        ClassContext classCtx = getClassContext();
        ConstantPoolGen cpg = classCtx.getConstantPoolGen();
        CFG cfg;
        try {
            cfg = classCtx.getCFG(getMethod());
        } catch (CFGBuilderException e) {
            AnalysisContext.logError("Cannot get CFG", e);
            return;
        }
        for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
            Location location = i.next();
            Instruction inst = location.getHandle().getInstruction();

            //DTD disallow
            //XMLInputFactory.setProperty
            if (inst instanceof org.apache.bcel.generic.INVOKEVIRTUAL) {
                InvokeInstruction invoke = (InvokeInstruction) inst;
                if ("setProperty".equals(invoke.getMethodName(cpg))) {
                    org.apache.bcel.generic.LDC loadConst = ByteCode.getPrevInstruction(location.getHandle(), LDC.class);
                    if (loadConst != null) {
                        if (PROPERTY_SUPPORT_DTD.equals(loadConst.getValue(cpg)) || PROPERTY_IS_SUPPORTING_EXTERNAL_ENTITIES.equals(loadConst.getValue(cpg))){
                            InstructionHandle prev1 = location.getHandle().getPrev();
                            InstructionHandle prev2 = prev1.getPrev();
                            //Case where the boolean is wrapped like : Boolean.valueOf(true) : 2 instructions
                            if (invokeInstruction().atClass("java.lang.Boolean").atMethod("valueOf").matches(prev1.getInstruction(),cpg)) {
                                if (prev2.getInstruction() instanceof ICONST) {
                                    Integer valueWrapped = ByteCode.getConstantInt(prev2);
                                    if (valueWrapped != null && valueWrapped.equals(0)) { //Value is false
                                        return; //Safe feature is disable
                                    }
                                }
                            }
                            //Case where the boolean is declared as : Boolean.FALSE
                            else if (prev1.getInstruction() instanceof org.apache.bcel.generic.GETSTATIC) {
                                org.apache.bcel.generic.GETSTATIC getstatic = (org.apache.bcel.generic.GETSTATIC) prev1.getInstruction();
                                if (getstatic.getClassType(cpg).getClassName().equals("java.lang.Boolean") &&
                                        getstatic.getFieldName(cpg).equals("FALSE")) {
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        }
        //Raise a bug
        bugReporter.reportBug(new BugInstance(this, XXE_XMLSTREAMREADER_TYPE, Priorities.NORMAL_PRIORITY) //
                .addClass(this).addMethod(this).addSourceLine(this));
    }
}
 
Example 7
Source File: DuplicateBranches.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void findIfElseDuplicates(CFG cfg, Method method, BasicBlock bb) {
    BasicBlock thenBB = null, elseBB = null;

    Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb);
    while (iei.hasNext()) {
        Edge e = iei.next();
        if (e.getType() == EdgeTypes.IFCMP_EDGE) {
            elseBB = e.getTarget();
        } else if (e.getType() == EdgeTypes.FALL_THROUGH_EDGE) {
            thenBB = e.getTarget();
        }
    }

    if ((thenBB == null) || (elseBB == null)) {
        return;
    }
    InstructionHandle thenStartHandle = getDeepFirstInstruction(cfg, thenBB);
    InstructionHandle elseStartHandle = getDeepFirstInstruction(cfg, elseBB);
    if ((thenStartHandle == null) || (elseStartHandle == null)) {
        return;
    }

    int thenStartPos = thenStartHandle.getPosition();
    int elseStartPos = elseStartHandle.getPosition();

    InstructionHandle thenFinishIns = findThenFinish(cfg, thenBB, elseStartPos);
    int thenFinishPos = thenFinishIns.getPosition();

    if (!(thenFinishIns.getInstruction() instanceof GotoInstruction)) {
        return;
    }

    InstructionHandle elseFinishHandle = ((GotoInstruction) thenFinishIns.getInstruction()).getTarget();
    int elseFinishPos = elseFinishHandle.getPosition();

    if (thenFinishPos >= elseStartPos) {
        return;
    }

    if ((thenFinishPos - thenStartPos) != (elseFinishPos - elseStartPos)) {
        return;
    }

    if (thenFinishPos <= thenStartPos) {
        return;
    }

    byte[] thenBytes = getCodeBytes(method, thenStartPos, thenFinishPos);
    byte[] elseBytes = getCodeBytes(method, elseStartPos, elseFinishPos);

    if (!Arrays.equals(thenBytes, elseBytes)) {
        return;
    }

    // adjust elseFinishPos to be inclusive (for source line attribution)
    InstructionHandle elseLastIns = elseFinishHandle.getPrev();
    if (elseLastIns != null) {
        elseFinishPos = elseLastIns.getPosition();
    }

    pendingBugs.add(new BugInstance(this, "DB_DUPLICATE_BRANCHES", NORMAL_PRIORITY)
            .addClassAndMethod(classContext.getJavaClass(), method)
            .addSourceLineRange(classContext, this, thenStartPos, thenFinishPos)
            .addSourceLineRange(classContext, this, elseStartPos, elseFinishPos));
}
 
Example 8
Source File: BetterCFGBuilder2.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Return whether or not the given instruction can throw exceptions.
 *
 * @param handle
 *            the instruction
 * @return true if the instruction can throw an exception, false otherwise
 * @throws CFGBuilderException
 */
private boolean isPEI(InstructionHandle handle) throws CFGBuilderException {
    Instruction ins = handle.getInstruction();

    if (!(ins instanceof ExceptionThrower)) {
        return false;
    }

    if (ins instanceof NEW) {
        return false;
    }
    // if (ins instanceof ATHROW) return false;
    if (ins instanceof GETSTATIC) {
        return false;
    }
    if (ins instanceof PUTSTATIC) {
        return false;
    }
    if (ins instanceof ReturnInstruction) {
        return false;
    }
    if (ins instanceof INSTANCEOF) {
        return false;
    }
    if (ins instanceof MONITOREXIT) {
        return false;
    }
    if (ins instanceof LDC) {
        return false;
    }
    if (ins instanceof GETFIELD && !methodGen.isStatic()) {
        // Assume that GETFIELD on this object is not PEI
        return !isSafeFieldSource(handle.getPrev());
    }
    if (ins instanceof PUTFIELD && !methodGen.isStatic()) {
        // Assume that PUTFIELD on this object is not PEI
        int depth = ins.consumeStack(cpg);
        for (InstructionHandle prev = handle.getPrev(); prev != null; prev = prev.getPrev()) {
            Instruction prevInst = prev.getInstruction();
            if (prevInst instanceof BranchInstruction) {
                if (prevInst instanceof GotoInstruction) {
                    // Currently we support only jumps to the PUTFIELD itself
                    // This will cover simple cases like this.a = flag ? foo : bar
                    if (((BranchInstruction) prevInst).getTarget() == handle) {
                        depth = ins.consumeStack(cpg);
                    } else {
                        return true;
                    }
                } else if (!(prevInst instanceof IfInstruction)) {
                    // As IF instructions may fall through then the stack depth remains unchanged
                    // Actually we should not go here for normal Java bytecode: switch or jsr should not appear in this context
                    return true;
                }
            }
            depth = depth - prevInst.produceStack(cpg) + prevInst.consumeStack(cpg);
            if (depth < 1) {
                throw new CFGBuilderException("Invalid stack at " + prev + " when checking " + handle);
            }
            if (depth == 1) {
                InstructionHandle prevPrev = prev.getPrev();
                if (prevPrev != null && prevPrev.getInstruction() instanceof BranchInstruction) {
                    continue;
                }
                return !isSafeFieldSource(prevPrev);
            }
        }
    }
    return true;
}
 
Example 9
Source File: BasicBlock.java    From spotbugs with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Get the predecessor of given instruction within the basic block.
 *
 * @param handle
 *            the instruction
 * @return the instruction's predecessor, or null if the instruction is the
 *         first in the basic block
 */
public InstructionHandle getPredecessorOf(InstructionHandle handle) {
    if (VERIFY_INTEGRITY && !containsInstruction(handle)) {
        throw new IllegalStateException();
    }
    return handle == firstInstruction ? null : handle.getPrev();
}