Java Code Examples for org.apache.bcel.generic.Instruction#getOpcode()

The following examples show how to use org.apache.bcel.generic.Instruction#getOpcode() . 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: BackwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void registerInstructionSinks() throws DataflowAnalysisException {
    TypeQualifierAnnotation returnValueAnnotation = null;
    if (!xmethod.getSignature().endsWith(")V")) {
        returnValueAnnotation = TypeQualifierApplications.getEffectiveTypeQualifierAnnotation(xmethod, typeQualifierValue);
    }

    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        Location location = i.next();

        Instruction ins = location.getHandle().getInstruction();

        if (ins instanceof ReturnInstruction && !(ins instanceof RETURN)) {
            // Return instruction which returns a value
            modelReturn(returnValueAnnotation, location);
        } else {
            short opcode = ins.getOpcode();

            if (opcode == Const.PUTFIELD || opcode == Const.PUTSTATIC) {
                modelFieldStore(location);
            } else if (location.getHandle().getInstruction() instanceof InvokeInstruction) {
                modelArguments(location);
            }
        }
    }
}
 
Example 2
Source File: StaticFieldLoadStreamFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

    Instruction ins = location.getHandle().getInstruction();
    if (ins.getOpcode() != Const.GETSTATIC) {
        return null;
    }

    GETSTATIC getstatic = (GETSTATIC) ins;
    if (!className.equals(getstatic.getClassName(cpg)) || !fieldName.equals(getstatic.getName(cpg))
            || !fieldSig.equals(getstatic.getSignature(cpg))) {
        return null;
    }

    return new Stream(location, type.getClassName(), streamBaseClass).setIgnoreImplicitExceptions(true).setIsOpenOnCreation(
            true);
}
 
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: ValueRangeAnalysisFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Condition extractCondition(BackIterator iterator) throws DataflowAnalysisException {
    Instruction comparisonInstruction = iterator.next().getInstruction();
    if (!(comparisonInstruction instanceof IfInstruction)) {
        return null;
    }
    short cmpOpcode = comparisonInstruction.getOpcode();
    int nargs = ((IfInstruction) comparisonInstruction).consumeStack(null);
    if (nargs == 2) {
        return extractTwoArgCondition(iterator, cmpOpcode, "I");
    } else if (nargs == 1) {
        Object val = extractValue(iterator, "I");
        if (val instanceof Value) {
            return new Condition(cmpOpcode, (Value) val, 0);
        } else if (val instanceof LCMP) {
            return extractTwoArgCondition(iterator, cmpOpcode, "J");
        }
    }
    return null;
}
 
Example 5
Source File: NullDerefAndRedundantComparisonFinder.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Examine basic blocks for null checks and potentially-redundant null
 * comparisons.
 *
 * @throws DataflowAnalysisException
 * @throws CFGBuilderException
 */
private void examineBasicBlocks() throws DataflowAnalysisException, CFGBuilderException {
    // Look for null check blocks where the reference being checked
    // is definitely null, or null on some path
    Iterator<BasicBlock> bbIter = invDataflow.getCFG().blockIterator();
    while (bbIter.hasNext()) {
        BasicBlock basicBlock = bbIter.next();

        if (basicBlock.isNullCheck()) {
            analyzeNullCheck(invDataflow, basicBlock);
        } else if (!basicBlock.isEmpty()) {
            // Look for all reference comparisons where
            // - both values compared are definitely null, or
            // - one value is definitely null and one is definitely not null
            // These cases are not null dereferences,
            // but they are quite likely to indicate an error, so while
            // we've got
            // information about null values, we may as well report them.
            InstructionHandle lastHandle = basicBlock.getLastInstruction();
            Instruction last = lastHandle.getInstruction();
            switch (last.getOpcode()) {
            case Const.IF_ACMPEQ:
            case Const.IF_ACMPNE:
                analyzeRefComparisonBranch(basicBlock, lastHandle);
                break;
            case Const.IFNULL:
            case Const.IFNONNULL:
                analyzeIfNullBranch(basicBlock, lastHandle);
                break;
            default:
                break;
            }
        }
    }
}
 
Example 6
Source File: ForwardTypeQualifierDataflowAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void registerInstructionSources() throws DataflowAnalysisException {
    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        Location location = i.next();
        Instruction instruction = location.getHandle().getInstruction();
        short opcode = instruction.getOpcode();

        int produces = instruction.produceStack(cpg);
        if (instruction instanceof InvokeInstruction) {
            // Model return value
            registerReturnValueSource(location);
        } else if (opcode == Const.GETFIELD || opcode == Const.GETSTATIC) {
            // Model field loads
            registerFieldLoadSource(location);
        } else if (instruction instanceof LDC) {
            // Model constant values
            registerLDCValueSource(location);
        } else if (instruction instanceof LDC2_W) {
            // Model constant values
            registerLDC2ValueSource(location);
        } else if (instruction instanceof ConstantPushInstruction) {
            // Model constant values
            registerConstantPushSource(location);
        } else if (instruction instanceof ACONST_NULL) {
            // Model constant values
            registerPushNullSource(location);
        } else if ((produces == 1 || produces == 2) && !(instruction instanceof LocalVariableInstruction)
                && !(instruction instanceof CHECKCAST)) {
            // Model other sources
            registerOtherSource(location);
        }
    }
}
 
Example 7
Source File: Hierarchy.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determine if given Instruction is a monitor wait.
 *
 * @param ins
 *            the Instruction
 * @param cpg
 *            the ConstantPoolGen for the Instruction
 *
 * @return true if the instruction is a monitor wait, false if not
 */
public static boolean isMonitorNotify(Instruction ins, ConstantPoolGen cpg) {
    if (!(ins instanceof InvokeInstruction)) {
        return false;
    }
    if (ins.getOpcode() == Const.INVOKESTATIC) {
        return false;
    }

    InvokeInstruction inv = (InvokeInstruction) ins;
    String methodName = inv.getMethodName(cpg);
    String methodSig = inv.getSignature(cpg);

    return isMonitorNotify(methodName, methodSig);
}
 
Example 8
Source File: InstanceFieldLoadStreamFactory.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

    Instruction ins = location.getHandle().getInstruction();
    if (ins.getOpcode() != Const.GETFIELD) {
        return null;
    }

    String fieldClass = type.getClassName();
    try {
        if (fieldClass.startsWith("[")) {
            return null;
        }
        if (!Hierarchy.isSubtype(fieldClass, streamBaseClass)) {
            return null;
        }

        Stream stream = new Stream(location, fieldClass, streamBaseClass);
        stream.setIsOpenOnCreation(true);
        stream.setOpenLocation(location);
        if (bugPatternType != null) {
            stream.setInteresting(bugPatternType);
        }

        // System.out.println("Instance field stream at " + location);
        return stream;
    } catch (ClassNotFoundException e) {
        lookupFailureCallback.reportMissingClass(e);
        return null;
    }
}
 
Example 9
Source File: FindUnreleasedLock.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private InvokeInstruction toInvokeInstruction(Instruction ins) {
    short opcode = ins.getOpcode();
    if (opcode != Const.INVOKEVIRTUAL && opcode != Const.INVOKEINTERFACE) {
        return null;
    }
    return (InvokeInstruction) ins;
}
 
Example 10
Source File: BCELFactory.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private boolean visitInstruction( final Instruction i ) {
    final short opcode = i.getOpcode();
    if ((InstructionConst.getInstruction(opcode) != null)
            && !(i instanceof ConstantPushInstruction) && !(i instanceof ReturnInstruction)) { // Handled below
        _out.println("il.append(InstructionConst."
                + i.getName().toUpperCase(Locale.ENGLISH) + ");");
        return true;
    }
    return false;
}
 
Example 11
Source File: IOStreamFactory.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

    try {
        Instruction ins = location.getHandle().getInstruction();

        if (ins.getOpcode() != Const.NEW) {
            return null;
        }

        if (Hierarchy.isSubtype(type, baseClassType)) {
            boolean isUninteresting = false;
            for (ObjectType aUninterestingSubclassTypeList : uninterestingSubclassTypeList) {
                if (Hierarchy.isSubtype(type, aUninterestingSubclassTypeList)) {
                    isUninteresting = true;
                    break;
                }
            }
            Stream result = new Stream(location, type.getClassName(), baseClassType.getClassName())
                    .setIgnoreImplicitExceptions(true);
            if (!isUninteresting) {
                result.setInteresting(bugType);
            }
            return result;
        }
    } catch (ClassNotFoundException e) {
        lookupFailureCallback.reportMissingClass(e);
    }

    return null;
}
 
Example 12
Source File: FieldSetAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void handleInstruction(InstructionHandle handle, BasicBlock basicBlock, FieldSet fact) {
    Instruction ins = handle.getInstruction();
    short opcode = ins.getOpcode();
    XField field;

    switch (opcode) {
    case Const.GETFIELD:
    case Const.GETSTATIC:
        field = lookupField(handle, (FieldInstruction) ins);
        if (field != null) {
            sawLoad(fact, field);
        }
        break;

    case Const.PUTFIELD:
    case Const.PUTSTATIC:
        field = lookupField(handle, (FieldInstruction) ins);
        if (field != null) {
            sawStore(fact, field);
        }
        break;

    case Const.INVOKEINTERFACE:
    case Const.INVOKESPECIAL:
    case Const.INVOKESTATIC:
    case Const.INVOKEVIRTUAL:
        // Assume that the called method assigns loads and stores all
        // possible fields
        fact.setBottom();
        break;
    default:
        break;
    }
}
 
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: 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 15
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 16
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 17
Source File: MethodReturnValueStreamFactory.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public Stream createStream(Location location, ObjectType type, ConstantPoolGen cpg,
        RepositoryLookupFailureCallback lookupFailureCallback) {

    try {
        Instruction ins = location.getHandle().getInstruction();

        // For now, just support instance methods
        short opcode = ins.getOpcode();
        if (!invokeOpcodeSet.get(opcode)) {
            return null;
        }

        // Is invoked class a subtype of the base class we want
        // FIXME: should test be different for INVOKESPECIAL and
        // INVOKESTATIC?
        InvokeInstruction inv = (InvokeInstruction) ins;
        ReferenceType classType = inv.getReferenceType(cpg);
        if (!Hierarchy.isSubtype(classType, baseClassType)) {
            return null;
        }

        // See if method name and signature match
        String methodName = inv.getMethodName(cpg);
        String methodSig = inv.getSignature(cpg);
        if (!this.methodName.equals(methodName) || !this.methodSig.equals(methodSig)) {
            return null;
        }

        String streamClass = type.getClassName();
        if ("java.sql.CallableStatement".equals(streamClass)) {
            streamClass = "java.sql.PreparedStatement";
        }
        Stream result = new Stream(location, streamClass, streamClass).setIgnoreImplicitExceptions(true).setIsOpenOnCreation(
                true);
        if (!isUninteresting) {
            result.setInteresting(bugType);
        }
        return result;
    } catch (ClassNotFoundException e) {
        lookupFailureCallback.reportMissingClass(e);
    }

    return null;
}
 
Example 18
Source File: FindSelfComparison2.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * @param classContext
 * @param location
 * @param method
 * @param methodGen
 * @param sourceFile
 * @throws DataflowAnalysisException
 */
private void checkForSelfOperation(ClassContext classContext, Location location, ValueNumberDataflow valueNumberDataflow,
        String op, Method method, MethodGen methodGen, String sourceFile) throws DataflowAnalysisException {
    ValueNumberFrame frame = valueNumberDataflow.getFactAtLocation(location);
    if (!frame.isValid()) {
        return;
    }
    Instruction ins = location.getHandle().getInstruction();
    int opcode = ins.getOpcode();
    int offset = 1;
    if (opcode == LCMP || opcode == LXOR || opcode == LAND || opcode == LOR || opcode == LSUB) {
        offset = 2;
    }
    ValueNumber v0 = frame.getStackValue(0);
    ValueNumber v1 = frame.getStackValue(offset);
    if (!v1.equals(v0)) {
        return;
    }
    if (v0.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT) || v0.hasFlag(ValueNumber.CONSTANT_VALUE)) {
        return;
    }

    int priority = HIGH_PRIORITY;
    if (opcode == ISUB || opcode == LSUB || opcode == INVOKEINTERFACE || opcode == INVOKEVIRTUAL) {
        priority = NORMAL_PRIORITY;
    }
    XField field = ValueNumberSourceInfo.findXFieldFromValueNumber(method, location, v0, frame);
    BugAnnotation annotation;
    String prefix;
    if (field != null) {
        return; // don't report non-volatiles; too many false positives
    } else {
        annotation = ValueNumberSourceInfo.findLocalAnnotationFromValueNumber(method, location, v0, frame);
        prefix = "SA_LOCAL_SELF_";
        if (opcode == ISUB) {
            return; // only report this if simple detector reports it
        }
    }
    if (annotation == null) {
        return;
    }
    SourceLineAnnotation sourceLine = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile,
            location.getHandle());
    int line = sourceLine.getStartLine();
    BitSet occursMultipleTimes = classContext.linesMentionedMultipleTimes(method);
    if (line > 0 && occursMultipleTimes.get(line)) {
        return;
    }
    BugInstance bug = new BugInstance(this, prefix + op, priority).addClassAndMethod(methodGen, sourceFile);
    if (ins instanceof InvokeInstruction) {
        bug.addCalledMethod(classContext.getConstantPoolGen(), (InvokeInstruction) ins);
    }

    bug.add(annotation)
            .addSourceLine(classContext, methodGen, sourceFile, location.getHandle());
    bugReporter.reportBug(bug);
}
 
Example 19
Source File: FindSelfComparison2.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void analyzeMethod(ClassContext classContext, Method method) throws CFGBuilderException, DataflowAnalysisException {
    CFG cfg = classContext.getCFG(method);
    ValueNumberDataflow valueNumberDataflow = classContext.getValueNumberDataflow(method);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    MethodGen methodGen = classContext.getMethodGen(method);
    String sourceFile = classContext.getJavaClass().getSourceFileName();

    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        Location location = i.next();

        Instruction ins = location.getHandle().getInstruction();
        switch (ins.getOpcode()) {
        case INVOKEVIRTUAL:
        case INVOKEINTERFACE:
            InvokeInstruction iins = (InvokeInstruction) ins;
            String invoking = iins.getName(cpg);
            if (comparatorMethod(invoking) || booleanComparisonMethod(invoking)) {
                if (methodGen.getName().toLowerCase().indexOf("test") >= 0) {
                    break;
                }
                if (methodGen.getClassName().toLowerCase().indexOf("test") >= 0) {
                    break;
                }
                if (classContext.getJavaClass().getSuperclassName().toLowerCase().indexOf("test") >= 0) {
                    break;
                }
                if (location.getHandle().getNext().getInstruction().getOpcode() == POP) {
                    break;
                }
                String sig = iins.getSignature(cpg);

                SignatureParser parser = new SignatureParser(sig);
                if (parser.getNumParameters() == 1
                        && (booleanComparisonMethod(invoking) && sig.endsWith(";)Z") || comparatorMethod(invoking) && sig.endsWith(";)I"))) {
                    checkForSelfOperation(classContext, location, valueNumberDataflow, "COMPARISON", method, methodGen,
                            sourceFile);
                }

            }
            break;

        case LOR:
        case LAND:
        case LXOR:
        case LSUB:
        case IOR:
        case IAND:
        case IXOR:
        case ISUB:
            checkForSelfOperation(classContext, location, valueNumberDataflow, "COMPUTATION", method, methodGen, sourceFile);
            break;
        case FCMPG:
        case DCMPG:
        case DCMPL:
        case FCMPL:
            break;
        case LCMP:
        case IF_ACMPEQ:
        case IF_ACMPNE:
        case IF_ICMPNE:
        case IF_ICMPEQ:
        case IF_ICMPGT:
        case IF_ICMPLE:
        case IF_ICMPLT:
        case IF_ICMPGE:
            checkForSelfOperation(classContext, location, valueNumberDataflow, "COMPARISON", method, methodGen, sourceFile);
            break;
        default:
            break;
        }

    }
}
 
Example 20
Source File: FindNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Determine whether or not given instruction is a goto.
 *
 * @param instruction
 *            the instruction
 * @return true if the instruction is a goto, false otherwise
 */
private boolean isGoto(Instruction instruction) {
    return instruction.getOpcode() == Const.GOTO || instruction.getOpcode() == Const.GOTO_W;
}