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

The following examples show how to use org.apache.bcel.generic.InstructionHandle#getPosition() . 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: FinallyDuplicatesInfoFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public List<Edge> getDuplicates(CFG cfg, Edge edge) {
    InstructionHandle ih = edge.getSource().getLastInstruction();
    if (ih == null) {
        return Collections.emptyList();
    }
    BitSet duplicates = getDuplicates(ih.getPosition());
    if (duplicates.isEmpty()) {
        return Collections.emptyList();
    }
    List<Edge> result = new ArrayList<>();
    for (Iterator<Edge> edgeIterator = cfg.edgeIterator(); edgeIterator.hasNext();) {
        Edge next = edgeIterator.next();
        if (next.getType() != edge.getType()) {
            continue;
        }
        InstructionHandle lastInst = next.getSource().getLastInstruction();
        if (lastInst != null && lastInst.getPosition() >= 0 && duplicates.get(lastInst.getPosition())) {
            result.add(next);
        }
    }
    return result;
}
 
Example 2
Source File: BugInstance.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Add a source line annotation describing a range of instructions.
 *
 * @param classContext
 *            the ClassContext
 * @param methodGen
 *            the method
 * @param sourceFile
 *            source file the method is defined in
 * @param start
 *            the start instruction in the range
 * @param end
 *            the end instruction in the range (inclusive)
 * @return this object
 */
@Nonnull
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start,
        InstructionHandle end) {
    // Make sure start and end are really in the right order.
    if (start.getPosition() > end.getPosition()) {
        InstructionHandle tmp = start;
        start = end;
        end = tmp;
    }
    SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen,
            sourceFile, start, end);
    if (sourceLineAnnotation != null) {
        add(sourceLineAnnotation);
    }
    return this;
}
 
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: FindInconsistentSync2.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void addAccess(MethodDescriptor method, InstructionHandle handle, boolean isLocked) {
    if (!interesting) {
        return;
    }
    if (!SYNC_ACCESS && isLocked) {
        return;
    }

    if (!servletField && !isLocked && syncAccessList.size() == 0 && unsyncAccessList.size() > 6) {
        interesting = false;
        syncAccessList = null;
        unsyncAccessList = null;
        return;
    }
    FieldAccess fa = new FieldAccess(method, handle.getPosition());
    if (isLocked) {
        syncAccessList = Util.addTo(syncAccessList, fa);
    } else {
        unsyncAccessList = Util.addTo(unsyncAccessList, fa);
    }
}
 
Example 5
Source File: SourceLineAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Factory method for creating a source line annotation describing the
 * source line number for a visited instruction.
 *
 * @param classContext
 *            the ClassContext
 * @param methodGen
 *            the MethodGen object representing the method
 * @param handle
 *            the InstructionHandle containing the visited instruction
 * @return the SourceLineAnnotation, or null if we do not have line number
 *         information for the instruction
 */
@Nonnull
public static SourceLineAnnotation fromVisitedInstruction(ClassContext classContext, MethodGen methodGen, String sourceFile,
        @Nonnull InstructionHandle handle) {
    LineNumberTable table = methodGen.getLineNumberTable(methodGen.getConstantPool());
    String className = methodGen.getClassName();

    int bytecodeOffset = handle.getPosition();

    if (table == null) {
        return createUnknown(className, sourceFile, bytecodeOffset, bytecodeOffset);
    }

    int lineNumber = table.getSourceLine(handle.getPosition());
    return new SourceLineAnnotation(className, sourceFile, lineNumber, lineNumber, bytecodeOffset, bytecodeOffset);
}
 
Example 6
Source File: BetterCFGBuilder2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Add an instruction to the subroutine. We keep track of which
 * instructions are part of which subroutines. No instruction may be
 * part of more than one subroutine.
 *
 * @param handle
 *            the instruction to be added to the subroutine
 */
public void addInstruction(InstructionHandle handle) throws CFGBuilderException {
    int position = handle.getPosition();
    if (usedInstructionSet.get(position)) {
        throw new CFGBuilderException("Instruction " + handle + " visited in multiple subroutines");
    }
    instructionSet.set(position);
    usedInstructionSet.set(position);
}
 
Example 7
Source File: Dataflow.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String blockId(BasicBlock bb) {
    InstructionHandle handle = bb.getFirstInstruction();
    if (handle == null) {
        return "" + bb.getLabel();
    }
    return bb.getLabel() + ":" + handle.getPosition() + " " + handle.getInstruction();
}
 
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: Edge.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean isBackwardInBytecode() {
    BasicBlock source = getSource();
    BasicBlock target = getTarget();

    InstructionHandle sourceInstruction = source.getLastInstruction();
    InstructionHandle targetInstruction = target.getFirstInstruction();

    if (targetInstruction == null || sourceInstruction == null) {
        return false;
    }
    return targetInstruction.getPosition() < sourceInstruction.getPosition();

}
 
Example 10
Source File: LocalVariableAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static LocalVariableAnnotation getLocalVariableAnnotation(Method method, Location location, IndexedInstruction ins) {
    int local = ins.getIndex();
    InstructionHandle handle = location.getHandle();
    int position1 = handle.getNext().getPosition();
    int position2 = handle.getPosition();
    return getLocalVariableAnnotation(method, local, position1, position2);
}
 
Example 11
Source File: NullDerefAndRedundantComparisonFinder.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void analyzeNullCheck(IsNullValueDataflow invDataflow, BasicBlock basicBlock) throws DataflowAnalysisException,
        CFGBuilderException {
    // Look for null checks where the value checked is definitely
    // null or null on some path.

    InstructionHandle exceptionThrowerHandle = basicBlock.getExceptionThrower();
    Instruction exceptionThrower = exceptionThrowerHandle.getInstruction();

    // Get the stack values at entry to the null check.
    IsNullValueFrame frame = invDataflow.getStartFact(basicBlock);
    if (!frame.isValid()) {
        return;
    }

    // Could the reference be null?
    IsNullValue refValue = frame.getInstance(exceptionThrower, classContext.getConstantPoolGen());
    if (DEBUG) {
        System.out.println("For basic block " + basicBlock + " value is " + refValue);
    }
    if (refValue.isDefinitelyNotNull()) {
        return;
        //        if (false && !refValue.mightBeNull())
        //            return;
    }

    if (!refValue.isDefinitelyNull()) {
        return;
    }
    // Get the value number
    ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getStartFact(basicBlock);
    if (!vnaFrame.isValid()) {
        return;
    }
    ValueNumber valueNumber = vnaFrame.getInstance(exceptionThrower, classContext.getConstantPoolGen());
    Location location = new Location(exceptionThrowerHandle, basicBlock);
    if (DEBUG) {
        System.out.println("Warning: VN " + valueNumber + " invf: " + frame + " @ " + location);
    }

    boolean isConsistent = true;
    Iterator<BasicBlock> bbIter = invDataflow.getCFG().blockIterator();
    LineNumberTable table = method.getLineNumberTable();
    int position = exceptionThrowerHandle.getPosition();
    int line = table == null ? 0 : table.getSourceLine(position);
    while (bbIter.hasNext()) {
        BasicBlock bb = bbIter.next();

        if (!bb.isNullCheck()) {
            continue;
        }

        InstructionHandle eth = bb.getExceptionThrower();
        if (eth == exceptionThrowerHandle) {
            continue;
        }
        if (eth.getInstruction().getOpcode() != exceptionThrower.getOpcode()) {
            continue;
        }

        int ePosition = eth.getPosition();
        if (ePosition == position || table != null && line == table.getSourceLine(ePosition)) {

            IsNullValueFrame frame2 = invDataflow.getStartFact(bb);
            if (!frame2.isValid()) {
                continue;
            }
            // apparent clone
            IsNullValue rv = frame2.getInstance(eth.getInstruction(), classContext.getConstantPoolGen());
            if (!rv.equals(refValue)) {
                isConsistent = false;
            }
        }

    }
    // Issue a warning
    collector.foundNullDeref(location, valueNumber, refValue, vnaFrame, isConsistent);
}
 
Example 12
Source File: FindSqlInjection.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public boolean getSawOpenQuote(InstructionHandle handle) {
    return sawOpenQuote <= handle.getPosition();
}
 
Example 13
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void inspectLocation(JavaClass jclass, ConstantPoolGen cpg, Method method, MethodGen methodGen,
        LinkedList<WarningWithProperties> refComparisonList, LinkedList<WarningWithProperties> stringComparisonList,
        RefComparisonTypeFrameModelingVisitor visitor, TypeDataflow typeDataflow, Location location)
        throws DataflowAnalysisException {
    Instruction ins = location.getHandle().getInstruction();
    short opcode = ins.getOpcode();
    if (opcode == Const.IF_ACMPEQ || opcode == Const.IF_ACMPNE) {
        checkRefComparison(location, jclass, method, methodGen, visitor, typeDataflow, stringComparisonList,
                refComparisonList);
    } else if (ins instanceof InvokeInstruction) {
        InvokeInstruction inv = (InvokeInstruction) ins;
        boolean isStatic = inv instanceof INVOKESTATIC;
        @DottedClassName
        String className = inv.getClassName(cpg);
        String methodName = inv.getMethodName(cpg);
        String methodSig = inv.getSignature(cpg);
        if ("assertSame".equals(methodName) && "(Ljava/lang/Object;Ljava/lang/Object;)V".equals(methodSig)) {
            checkRefComparison(location, jclass, method, methodGen, visitor, typeDataflow, stringComparisonList,
                    refComparisonList);
        } else if ("assertFalse".equals(methodName) && "(Z)V".equals(methodSig)) {
            SourceLineAnnotation lastLocation = bugAccumulator.getLastBugLocation();
            InstructionHandle prevHandle = location.getHandle().getPrev();
            if (lastLocation != null && prevHandle != null && lastLocation.getEndBytecode() == prevHandle.getPosition()) {
                bugAccumulator.forgetLastBug();
                if (DEBUG) {
                    System.out.println("Forgetting last bug due to call to " + className + "." + methodName);
                }
            }

        } else {
            boolean equalsMethod = !isStatic && "equals".equals(methodName) && "(Ljava/lang/Object;)Z".equals(methodSig)
                    || isStatic && "assertEquals".equals(methodName)
                            && "(Ljava/lang/Object;Ljava/lang/Object;)V".equals(methodSig)
                    || isStatic && "equal".equals(methodName) && "(Ljava/lang/Object;Ljava/lang/Object;)Z".equals(methodSig)
                            && "com.google.common.base.Objects".equals(className)
                    || isStatic && "equals".equals(methodName) && "(Ljava/lang/Object;Ljava/lang/Object;)Z".equals(methodSig)
                            && "java.util.Objects".equals(className);

            if (equalsMethod) {
                checkEqualsComparison(location, jclass, method, methodGen, cpg, typeDataflow);
            }
        }
    }

}
 
Example 14
Source File: FindSqlInjection.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public boolean getSawUnsafeAppend(InstructionHandle handle) {
    return sawUnsafeAppend <= handle.getPosition();
}
 
Example 15
Source File: FindSqlInjection.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public boolean getSawTaint(InstructionHandle handle) {
    return sawTaint <= handle.getPosition();
}
 
Example 16
Source File: FindSqlInjection.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public boolean getSawSeriousTaint(InstructionHandle handle) {
    return sawSeriousTaint <= handle.getPosition();
}
 
Example 17
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 18
Source File: RepeatedConditionals.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private boolean compareCode(int first, int endOfFirstSegment, int second,
        int endOfSecondSegment, boolean oppositeChecks) {
    if (endOfFirstSegment - first != endOfSecondSegment - second) {
        return false;
    }
    MethodGen methodGen = null;
    try {
        methodGen = Global.getAnalysisCache().getMethodAnalysis(MethodGen.class, getMethodDescriptor());
    } catch (CheckedAnalysisException e) {
        // Ignore
    }
    if (methodGen == null) {
        // MethodGen is absent for some reason: fallback to byte-to-byte comparison
        byte[] code = getCode().getCode();
        for (int i = first; i < endOfFirstSegment; i++) {
            if (code[i] != code[i - first + second]) {
                return false;
            }
        }
        return true;
    }
    InstructionHandle firstHandle = methodGen.getInstructionList().findHandle(first);
    InstructionHandle secondHandle = methodGen.getInstructionList().findHandle(second);
    while (true) {
        if (firstHandle == null || secondHandle == null) {
            return false;
        }
        if (firstHandle.getPosition() >= endOfFirstSegment) {
            return secondHandle.getPosition() >= endOfSecondSegment;
        }
        if (secondHandle.getPosition() >= endOfSecondSegment) {
            return firstHandle.getPosition() >= endOfFirstSegment;
        }
        Instruction firstInstruction = firstHandle.getInstruction();
        Instruction secondInstruction = secondHandle.getInstruction();
        if (firstInstruction instanceof BranchInstruction && secondInstruction instanceof BranchInstruction) {
            int firstOpcode = firstInstruction.getOpcode();
            int secondOpcode = secondInstruction.getOpcode();
            if (firstOpcode != secondOpcode) {
                return false;
            }
            int firstTarget = ((BranchInstruction) firstInstruction).getTarget().getPosition();
            int secondTarget = ((BranchInstruction) secondInstruction).getTarget().getPosition();
            if (firstTarget == second) {
                if (oppositeChecks || secondTarget <= endOfSecondSegment) {
                    return false;
                }
            } else {
                if (!((firstTarget >= first && firstTarget <= endOfFirstSegment && firstTarget - first == secondTarget - second)
                        || firstTarget == secondTarget)) {
                    return false;
                }
            }
        } else {
            if (!firstInstruction.equals(secondInstruction)) {
                return false;
            }
        }
        firstHandle = firstHandle.getNext();
        secondHandle = secondHandle.getNext();
    }
}
 
Example 19
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 20
Source File: InstructionHandleMap.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@SuppressWarnings("unchecked")
public ValueType get(InstructionHandle handle) {
    return (ValueType) map[handle.getPosition()];
}