Java Code Examples for edu.umd.cs.findbugs.SourceLineAnnotation#fromVisitedInstruction()

The following examples show how to use edu.umd.cs.findbugs.SourceLineAnnotation#fromVisitedInstruction() . 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: PreferZeroLengthArrays.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void sawOpcode(int seen) {

    switch (seen) {
    case Const.ACONST_NULL:
        nullOnTOS = true;
        return;
    case Const.ARETURN:
        if (nullOnTOS) {
            SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(getClassContext(), this,
                    getPC());
            if (sourceLineAnnotation != null) {
                found.add(sourceLineAnnotation);
            }
        }
        break;
    default:
        break;
    }
    nullOnTOS = false;
}
 
Example 2
Source File: DontUseEnum.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(LocalVariable obj) {
    if (isReservedName(obj.getName())) {
        LocalVariableAnnotation var = new LocalVariableAnnotation(obj.getName(), obj.getIndex(), obj.getStartPC());
        SourceLineAnnotation source = SourceLineAnnotation.fromVisitedInstruction(getClassContext(), this, obj.getStartPC());
        BugInstance bug = new BugInstance(this, "NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER", NORMAL_PRIORITY)
                .addClassAndMethod(this).add(var).add(source);
        bugReporter.reportBug(bug);
    }
}
 
Example 3
Source File: RedundantConditions.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    for (Method method : classContext.getJavaClass().getMethods()) {
        MethodDescriptor methodDescriptor = BCELUtil.getMethodDescriptor(classContext.getJavaClass(), method);
        ValueRangeAnalysis analysis;
        try {
            analysis = Global.getAnalysisCache().getMethodAnalysis(ValueRangeAnalysis.class, methodDescriptor);
        } catch (CheckedAnalysisException e) {
            bugReporter.logError("ValueRangeAnalysis failed for " + methodDescriptor, e);
            continue;
        }
        if (analysis == null) {
            continue;
        }
        for (RedundantCondition condition : analysis.getRedundantConditions()) {
            int priority = getPriority(methodDescriptor, condition);
            SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, method,
                    condition.getLocation().getHandle().getPosition());
            BugInstance bug = new BugInstance(condition.isByType() ? "UC_USELESS_CONDITION_TYPE" : "UC_USELESS_CONDITION", priority)
                    .addClassAndMethod(methodDescriptor).add(new StringAnnotation(normalize(condition.getTrueCondition())));
            if (condition.isByType()) {
                bug.addType(condition.getSignature());
            }
            if (condition.isDeadCodeUnreachable() && condition.getDeadCodeLocation() != null && priority == HIGH_PRIORITY) {
                bug.addSourceLine(methodDescriptor, condition.getDeadCodeLocation()).describe(SourceLineAnnotation.ROLE_UNREACHABLE_CODE);
            }
            bugAccumulator.accumulateBug(bug, sourceLineAnnotation);
        }
        bugAccumulator.reportAccumulatedBugs();
    }

}
 
Example 4
Source File: IDivResultCastToDouble.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void sawOpcode(int seen) {

    if (DEBUG) {
        System.out.println("Saw opcode " + Const.getOpcodeName(seen) + " " + pendingIdivCastToDivBugLocation);
    }

    if ((prevOpCode == Const.I2D || prevOpCode == Const.L2D) && seen == Const.INVOKESTATIC && ClassName.isMathClass(getClassConstantOperand())
            && "ceil".equals(getNameConstantOperand())) {
        bugAccumulator
                .accumulateBug(new BugInstance(this, "ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL", HIGH_PRIORITY)
                        .addClassAndMethod(this), this);
        pendingIdivCastToDivBugLocation = null;
    } else if ((prevOpCode == Const.I2F || prevOpCode == Const.L2F) && seen == Const.INVOKESTATIC
            && ClassName.isMathClass(getClassConstantOperand()) && "round".equals(getNameConstantOperand())) {
        bugAccumulator.accumulateBug(
                new BugInstance(this, "ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND", NORMAL_PRIORITY).addClassAndMethod(this),
                this);
        pendingIdivCastToDivBugLocation = null;
    } else if (pendingIdivCastToDivBugLocation != null) {
        bugAccumulator.accumulateBug(
                new BugInstance(this, "ICAST_IDIV_CAST_TO_DOUBLE", NORMAL_PRIORITY).addClassAndMethod(this),
                pendingIdivCastToDivBugLocation);
        pendingIdivCastToDivBugLocation = null;
    }

    if (prevOpCode == Const.IDIV && (seen == Const.I2D || seen == Const.I2F) || prevOpCode == Const.LDIV && (seen == Const.L2D
            || seen == Const.L2F)) {
        pendingIdivCastToDivBugLocation = SourceLineAnnotation.fromVisitedInstruction(this);
    }
    prevOpCode = seen;
}
 
Example 5
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void handleSuspiciousRefComparison(JavaClass jclass, Method method, MethodGen methodGen,
        List<WarningWithProperties> refComparisonList, Location location, String lhs, ReferenceType lhsType,
        ReferenceType rhsType) {
    XField xf = null;
    if (lhsType instanceof FinalConstant) {
        xf = ((FinalConstant) lhsType).getXField();
    } else if (rhsType instanceof FinalConstant) {
        xf = ((FinalConstant) rhsType).getXField();
    }
    String sourceFile = jclass.getSourceFileName();
    String bugPattern = "RC_REF_COMPARISON";
    int priority = Priorities.HIGH_PRIORITY;
    if ("java.lang.Boolean".equals(lhs)) {
        bugPattern = "RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN";
        priority = Priorities.NORMAL_PRIORITY;
    } else if (xf != null && xf.isStatic() && xf.isFinal()) {
        bugPattern = "RC_REF_COMPARISON_BAD_PRACTICE";
        if (xf.isPublic() || !methodGen.isPublic()) {
            priority = Priorities.NORMAL_PRIORITY;
        }
    }
    BugInstance instance = new BugInstance(this, bugPattern, priority).addClassAndMethod(methodGen, sourceFile)
            .addType("L" + lhs.replace('.', '/') + ";").describe(TypeAnnotation.FOUND_ROLE);
    if (xf != null) {
        instance.addField(xf).describe(FieldAnnotation.LOADED_FROM_ROLE);
    } else {
        instance.addSomeSourceForTopTwoStackValues(classContext, method, location);
    }
    SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen,
            sourceFile, location.getHandle());

    refComparisonList.add(new WarningWithProperties(instance, new WarningPropertySet<>(),
            sourceLineAnnotation, location));
}
 
Example 6
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 7
Source File: FindUnsatisfiedObligation.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void reportPath(final BugInstance bugInstance, final Obligation obligation, final State state) {

            Path path = state.getPath();

            // This PathVisitor will traverse the Path and add appropriate
            // SourceLineAnnotations to the BugInstance.
            PathVisitor visitor = new PathVisitor() {
                boolean sawFirstCreation;

                SourceLineAnnotation lastSourceLine;// = creationSourceLine;

                BasicBlock curBlock;

                @Override
                public void visitBasicBlock(BasicBlock basicBlock) {
                    curBlock = basicBlock;

                    // See if the initial instance of the leaked resource
                    // is in the entry fact due to a @WillClose annotation.
                    if (curBlock == cfg.getEntry()) {
                        // Get the entry fact - it should have precisely one
                        // state
                        StateSet entryFact = dataflow.getResultFact(curBlock);
                        Iterator<State> i = entryFact.stateIterator();
                        if (i.hasNext()) {
                            State entryState = i.next();
                            if (entryState.getObligationSet().getCount(obligation.getId()) > 0) {
                                lastSourceLine = SourceLineAnnotation.forFirstLineOfMethod(methodDescriptor);
                                lastSourceLine
                                        .setDescription(SourceLineAnnotation.ROLE_OBLIGATION_CREATED_BY_WILLCLOSE_PARAMETER);
                                bugInstance.add(lastSourceLine);
                                sawFirstCreation = true;

                                if (REPORT_PATH_DEBUG) {
                                    System.out.println("  " + obligation + " created by @WillClose parameter at "
                                            + lastSourceLine);
                                }
                            }
                        }
                    }
                }

                @Override
                public void visitInstructionHandle(InstructionHandle handle) {
                    boolean isCreation = (dataflow.getAnalysis().getActionCache().addsObligation(curBlock, handle, obligation));

                    if (!sawFirstCreation && !isCreation) {
                        return;
                    }

                    SourceLineAnnotation sourceLine = SourceLineAnnotation.fromVisitedInstruction(methodDescriptor, new Location(
                            handle, curBlock));
                    sourceLine.setDescription(isCreation ? SourceLineAnnotation.ROLE_OBLIGATION_CREATED
                            : SourceLineAnnotation.ROLE_PATH_CONTINUES);

                    boolean isInteresting = (sourceLine.getStartLine() > 0)
                            && (lastSourceLine == null || isCreation || sourceLine.getStartLine() != lastSourceLine.getStartLine());

                    if (REPORT_PATH_DEBUG) {
                        System.out.println("  " + handle.getPosition() + " --> " + sourceLine + (isInteresting ? " **" : ""));
                    }
                    if (isInteresting) {
                        bugInstance.add(sourceLine);
                        lastSourceLine = sourceLine;
                        if (isCreation) {
                            sawFirstCreation = true;
                        }
                    }
                }

                @Override
                public void visitEdge(Edge edge) {
                    if (REPORT_PATH_DEBUG) {
                        System.out.println("Edge of type " + Edge.edgeTypeToString(edge.getType()) + " to "
                                + edge.getTarget().getLabel());
                        if (edge.getTarget().getFirstInstruction() != null) {
                            System.out.println("  First instruction in target: " + edge.getTarget().getFirstInstruction());
                        }
                        if (edge.getTarget().isExceptionThrower()) {
                            System.out.println("  exception thrower for " + edge.getTarget().getExceptionThrower());
                        }
                        if (edge.isExceptionEdge()) {
                            System.out.println("  exceptions thrown: " + typeDataflow.getEdgeExceptionSet(edge));
                        }
                    }
                }
            };

            // Visit the Path
            path.acceptVisitor(cfg, visitor);
        }
 
Example 8
Source File: FindUseOfNonSerializableValue.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 {
    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }
    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return;
    }
    // We don't adequately model instanceof interfaces yet
    if (bytecodeSet.get(Const.INSTANCEOF) || bytecodeSet.get(Const.CHECKCAST)) {
        return;
    }
    CFG cfg = classContext.getCFG(method);
    TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();

    String sourceFile = classContext.getJavaClass().getSourceFileName();
    if (DEBUG) {
        String methodName = methodGen.getClassName() + "." + methodGen.getName();
        System.out.println("Checking " + methodName);
    }

    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        Location location = i.next();
        InstructionHandle handle = location.getHandle();
        Instruction ins = handle.getInstruction();

        Use use = getUse(cpg, ins);
        if (use == null) {
            continue;
        }

        TypeFrame frame = typeDataflow.getFactAtLocation(location);
        if (!frame.isValid()) {
            // This basic block is probably dead
            continue;
        }
        Type operandType = frame.getTopValue();

        if (operandType.equals(TopType.instance())) {
            // unreachable
            continue;
        }
        if (!(operandType instanceof ReferenceType)) {
            // Shouldn't happen - illegal bytecode
            continue;
        }
        ReferenceType refType = (ReferenceType) operandType;

        if (refType.equals(NullType.instance())) {
            continue;
        }

        try {

            double isSerializable = DeepSubtypeAnalysis.isDeepSerializable(refType);

            if (isSerializable < 0.9) {
                SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext,
                        methodGen, sourceFile, handle);
                ReferenceType problem = DeepSubtypeAnalysis.getLeastSerializableTypeComponent(refType);

                String pattern;
                switch (use) {
                case PASSED_TO_WRITE_OBJECT:
                    pattern = "DMI_NONSERIALIZABLE_OBJECT_WRITTEN";
                    double isRemote = DeepSubtypeAnalysis.isDeepRemote(refType);
                    if (isRemote >= 0.9) {
                        continue;
                    }
                    if (isSerializable < isRemote) {
                        isSerializable = isRemote;
                    }
                    break;
                case STORE_INTO_HTTP_SESSION:
                    pattern = "J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION";
                    break;
                default:
                    throw new IllegalStateException();
                }

                bugAccumulator.accumulateBug(new BugInstance(this, pattern,
                        isSerializable < 0.15 ? HIGH_PRIORITY : isSerializable > 0.5 ? LOW_PRIORITY : NORMAL_PRIORITY)
                                .addClassAndMethod(methodGen, sourceFile).addType(problem).describe(TypeAnnotation.FOUND_ROLE),
                        sourceLineAnnotation);

            }
        } catch (ClassNotFoundException e) {
            // ignore
        }
    }
}
 
Example 9
Source File: FindNonSerializableStoreIntoSession.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 {
    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }
    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return;
    }
    // We don't adequately model instanceof interfaces yet
    if (bytecodeSet.get(Const.INSTANCEOF) || bytecodeSet.get(Const.CHECKCAST)) {
        return;
    }
    CFG cfg = classContext.getCFG(method);
    TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();

    String sourceFile = classContext.getJavaClass().getSourceFileName();
    if (DEBUG) {
        String methodName = methodGen.getClassName() + "." + methodGen.getName();
        System.out.println("Checking " + methodName);
    }

    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        Location location = i.next();
        InstructionHandle handle = location.getHandle();
        Instruction ins = handle.getInstruction();

        if (!(ins instanceof INVOKEINTERFACE)) {
            continue;
        }

        INVOKEINTERFACE invoke = (INVOKEINTERFACE) ins;
        String mName = invoke.getMethodName(cpg);
        if (!"setAttribute".equals(mName)) {
            continue;
        }
        String cName = invoke.getClassName(cpg);
        if (!"javax.servlet.http.HttpSession".equals(cName)) {
            continue;
        }

        TypeFrame frame = typeDataflow.getFactAtLocation(location);
        if (!frame.isValid()) {
            // This basic block is probably dead
            continue;
        }
        Type operandType = frame.getTopValue();

        if (operandType.equals(TopType.instance())) {
            // unreachable
            continue;
        }
        if (!(operandType instanceof ReferenceType)) {
            // Shouldn't happen - illegal bytecode
            continue;
        }
        ReferenceType refType = (ReferenceType) operandType;

        if (refType.equals(NullType.instance())) {
            continue;
        }

        try {

            double isSerializable = DeepSubtypeAnalysis.isDeepSerializable(refType);

            if (isSerializable < 0.9) {
                SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext,
                        methodGen, sourceFile, handle);
                ReferenceType problem = DeepSubtypeAnalysis.getLeastSerializableTypeComponent(refType);

                bugAccumulator.accumulateBug(new BugInstance(this, "J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION",
                        isSerializable < 0.15 ? HIGH_PRIORITY : isSerializable > 0.5 ? LOW_PRIORITY : NORMAL_PRIORITY)
                                .addClassAndMethod(methodGen, sourceFile).addType(problem).describe(TypeAnnotation.FOUND_ROLE),
                        sourceLineAnnotation);

            }
        } catch (ClassNotFoundException e) {
            // ignore
        }
    }
}
 
Example 10
Source File: FindFloatEquality.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void sawOpcode(int seen) {
    switch (seen) {
    case Const.FCMPG:
    case Const.FCMPL:
    case Const.DCMPG:
    case Const.DCMPL:
        if (stack.getStackDepth() >= 2) {
            OpcodeStack.Item first = stack.getStackItem(0);
            OpcodeStack.Item second = stack.getStackItem(1);

            if (first.getRegisterNumber() == second.getRegisterNumber() && first.getRegisterNumber() != -1) {
                break;
            }
            if (first.isInitialParameter() && second.isInitialParameter()) {
                break;
            }
            if (sameField(first, second)) {
                break;
            }

            Number n1 = (Number) first.getConstant();
            Number n2 = (Number) second.getConstant();
            if (n1 != null && Double.isNaN(n1.doubleValue()) || n2 != null && Double.isNaN(n2.doubleValue())) {
                BugInstance bug = new BugInstance(this, "FE_TEST_IF_EQUAL_TO_NOT_A_NUMBER", HIGH_PRIORITY)
                        .addClassAndMethod(this);
                bugAccumulator.accumulateBug(bug, this);
                state = SAW_NOTHING;
                break;
            }
            if (first.getSpecialKind() == OpcodeStack.Item.NASTY_FLOAT_MATH && !isZero(n2)
                    || second.getSpecialKind() == OpcodeStack.Item.NASTY_FLOAT_MATH && !isZero(n1)
                    || first.getSpecialKind() == OpcodeStack.Item.FLOAT_MATH && !okValueToCompareAgainst(n2)
                    || second.getSpecialKind() == OpcodeStack.Item.FLOAT_MATH && !okValueToCompareAgainst(n1)) {
                if (priority != HIGH_PRIORITY) {
                    found.clear();
                }
                priority = HIGH_PRIORITY;
                state = SAW_COMP;
                break;
            }
            if (priority == HIGH_PRIORITY) {
                break;
            }
            // if (first.isInitialParameter() && n2 != null) break;
            // if (second.isInitialParameter() && n1 != null) break;
            if (n1 != null && n2 != null) {
                break;
            }

            if (okValueToCompareAgainst(n1) || okValueToCompareAgainst(n2)) {
                break;
            }
            if (n1 != null && !second.isInitialParameter() || n2 != null && !first.isInitialParameter()) {
                if (priority == LOW_PRIORITY) {
                    found.clear();
                }
                priority = NORMAL_PRIORITY;

            } else if (priority == NORMAL_PRIORITY) {
                break;
            }
            state = SAW_COMP;
        }
        break;

    case Const.IFEQ:
    case Const.IFNE:
        if (state == SAW_COMP) {
            SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(getClassContext(), this,
                    getPC());
            if (sourceLineAnnotation != null) {
                found.add(sourceLineAnnotation);
            }
        }
        state = SAW_NOTHING;
        break;

    default:
        state = SAW_NOTHING;
        break;
    }
}
 
Example 11
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void handleStringComparison(JavaClass jclass, Method method, MethodGen methodGen,
        RefComparisonTypeFrameModelingVisitor visitor, List<WarningWithProperties> stringComparisonList, Location location,
        Type lhsType, Type rhsType) {
    if (DEBUG) {
        System.out.println("String/String comparison at " + location.getHandle());
    }

    // Compute the priority:
    // - two static strings => do not report
    // - dynamic string and anything => high
    // - static string and unknown => medium
    // - all other cases => low
    // System.out.println("Compare " + lhsType + " == " + rhsType);
    byte type1 = lhsType.getType();
    byte type2 = rhsType.getType();

    String bugPattern = "ES_COMPARING_STRINGS_WITH_EQ";
    // T1 T2 result
    // S S no-op
    // D ? high
    // ? D high
    // S ? normal
    // ? S normal
    WarningPropertySet<WarningProperty> propertySet = new WarningPropertySet<>();
    if (type1 == T_STATIC_STRING && type2 == T_STATIC_STRING) {
        propertySet.addProperty(RefComparisonWarningProperty.COMPARE_STATIC_STRINGS);
    } else if (type1 == T_DYNAMIC_STRING || type2 == T_DYNAMIC_STRING) {
        propertySet.addProperty(RefComparisonWarningProperty.DYNAMIC_AND_UNKNOWN);
    } else if (type2 == T_PARAMETER_STRING || type1 == T_PARAMETER_STRING) {
        bugPattern = "ES_COMPARING_PARAMETER_STRING_WITH_EQ";
        if (methodGen.isPublic() || methodGen.isProtected()) {
            propertySet.addProperty(RefComparisonWarningProperty.STRING_PARAMETER_IN_PUBLIC_METHOD);
        } else {
            propertySet.addProperty(RefComparisonWarningProperty.STRING_PARAMETER);
        }
    } else if (type1 == T_STATIC_STRING || type2 == T_STATIC_STRING) {
        if (lhsType instanceof EmptyStringType || rhsType instanceof EmptyStringType) {
            propertySet.addProperty(RefComparisonWarningProperty.EMPTY_AND_UNKNOWN);
        } else {
            propertySet.addProperty(RefComparisonWarningProperty.STATIC_AND_UNKNOWN);
        }
    } else if (visitor.sawStringIntern()) {
        propertySet.addProperty(RefComparisonWarningProperty.SAW_INTERN);
    }

    String sourceFile = jclass.getSourceFileName();
    BugInstance instance = new BugInstance(this, bugPattern, BASE_ES_PRIORITY).addClassAndMethod(methodGen, sourceFile)
            .addType("Ljava/lang/String;").describe(TypeAnnotation.FOUND_ROLE).addSomeSourceForTopTwoStackValues(classContext, method, location);
    SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen,
            sourceFile, location.getHandle());

    WarningWithProperties warn = new WarningWithProperties(instance, propertySet, sourceLineAnnotation, location);
    stringComparisonList.add(warn);
}
 
Example 12
Source File: FindInconsistentSync2.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
SourceLineAnnotation asSourceLineAnnotation() {
    return SourceLineAnnotation.fromVisitedInstruction(methodDescriptor, position);
}
 
Example 13
Source File: CheckTypeQualifiers.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void emitDataflowWarning(XMethod xMethod, TypeQualifierValue<?> typeQualifierValue,
        TypeQualifierValueSet forwardsFact, TypeQualifierValueSet backwardsFact, ValueNumber vn, FlowValue forward,
        FlowValue backward, Location locationToReport, @CheckForNull Location locationWhereDoomedValueIsObserved, ValueNumberFrame vnaFrame)
        throws CheckedAnalysisException {
    String bugType;
    if (typeQualifierValue.isStrictQualifier() && forward == FlowValue.UNKNOWN) {
        bugType = "TQ_UNKNOWN_VALUE_USED_WHERE_ALWAYS_STRICTLY_REQUIRED";
    } else if (backward == FlowValue.NEVER) {
        bugType = "TQ_ALWAYS_VALUE_USED_WHERE_NEVER_REQUIRED";
    } else {
        bugType = "TQ_NEVER_VALUE_USED_WHERE_ALWAYS_REQUIRED";
    }

    // Issue warning
    BugInstance warning = new BugInstance(this, bugType, Priorities.NORMAL_PRIORITY).addClassAndMethod(xMethod);
    annotateWarningWithTypeQualifier(warning, typeQualifierValue);

    Set<? extends SourceSinkInfo> sourceSet = (forward == FlowValue.ALWAYS) ? forwardsFact.getWhereAlways(vn)
            : forwardsFact
                    .getWhereNever(vn);
    for (SourceSinkInfo source : sourceSet) {
        annotateWarningWithSourceSinkInfo(warning, xMethod, vn, source);
    }
    Set<? extends SourceSinkInfo> sinkSet = (backward == FlowValue.ALWAYS) ? backwardsFact.getWhereAlways(vn)
            : backwardsFact
                    .getWhereNever(vn);

    Location sinkLocation = getSinkLocation(sinkSet);
    if (sinkLocation == null) {
        AnalysisContext.logError("Unable to compute sink location for " + xMethod);
        return;
    }

    // Hopefully we can find the conflicted value in a local variable
    if (locationWhereDoomedValueIsObserved != null) {
        Method method = Global.getAnalysisCache().getMethodAnalysis(Method.class, xMethod.getMethodDescriptor());

        LocalVariableAnnotation localVariable = ValueNumberSourceInfo.findLocalAnnotationFromValueNumber(method,
                locationWhereDoomedValueIsObserved, vn, vnaFrame);
        if (localVariable != null && !localVariable.equals(warning.getPrimaryLocalVariableAnnotation())) {
            localVariable.setDescription(localVariable.isSignificant() ? "LOCAL_VARIABLE_VALUE_DOOMED_NAMED"
                    : "LOCAL_VARIABLE_VALUE_DOOMED");
            warning.add(localVariable);

        }
        if (!sinkLocation.equals(locationToReport)) {
            // Report where we observed the value.
            // Note that for conflicts detected on control edges,
            // we REPORT the edge source location
            // rather than the target location, even though it is the
            // target location where the conflict is detected.
            // The only reason to use a different reporting location
            // is to produce a more informative report for the user,
            // since the edge source is where the branch is found.
            SourceLineAnnotation observedLocation = SourceLineAnnotation.fromVisitedInstruction(xMethod.getMethodDescriptor(),
                    locationToReport);
            observedLocation.setDescription("SOURCE_LINE_VALUE_DOOMED");
            warning.add(observedLocation);
        }
    }

    // Add value sinks
    for (SourceSinkInfo sink : sinkSet) {
        annotateWarningWithSourceSinkInfo(warning, xMethod, vn, sink);
    }

    bugReporter.reportBug(warning);
}
 
Example 14
Source File: FindNonSerializableValuePassedToWriteObject.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 {
    MethodGen methodGen = classContext.getMethodGen(method);
    if (methodGen == null) {
        return;
    }
    BitSet bytecodeSet = classContext.getBytecodeSet(method);
    if (bytecodeSet == null) {
        return;
    }
    // We don't adequately model instanceof interfaces yet
    if (bytecodeSet.get(Const.INSTANCEOF) || bytecodeSet.get(Const.CHECKCAST)) {
        return;
    }
    CFG cfg = classContext.getCFG(method);
    TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
    ConstantPoolGen cpg = classContext.getConstantPoolGen();

    String sourceFile = classContext.getJavaClass().getSourceFileName();
    if (DEBUG) {
        String methodName = methodGen.getClassName() + "." + methodGen.getName();
        System.out.println("Checking " + methodName);
    }

    for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
        Location location = i.next();
        InstructionHandle handle = location.getHandle();
        Instruction ins = handle.getInstruction();

        if (!(ins instanceof InvokeInstruction)) {
            continue;
        }

        InvokeInstruction invoke = (InvokeInstruction) ins;
        String mName = invoke.getMethodName(cpg);
        if (!"writeObject".equals(mName)) {
            continue;
        }
        String cName = invoke.getClassName(cpg);
        if (!"java.io.ObjectOutput".equals(cName) && !"java.io.ObjectOutputStream".equals(cName)) {
            continue;
        }

        TypeFrame frame = typeDataflow.getFactAtLocation(location);
        if (!frame.isValid()) {
            // This basic block is probably dead
            continue;
        }
        Type operandType = frame.getTopValue();

        if (operandType.equals(TopType.instance())) {
            // unreachable
            continue;
        }
        if (!(operandType instanceof ReferenceType)) {
            // Shouldn't happen - illegal bytecode
            continue;
        }
        ReferenceType refType = (ReferenceType) operandType;

        if (refType.equals(NullType.instance())) {
            continue;
        }

        try {

            double isSerializable = DeepSubtypeAnalysis.isDeepSerializable(refType);

            if (isSerializable >= 0.9) {
                continue;
            }

            ReferenceType problem = DeepSubtypeAnalysis.getLeastSerializableTypeComponent(refType);

            double isRemote = DeepSubtypeAnalysis.isDeepRemote(refType);
            if (isRemote >= 0.9) {
                continue;
            }
            if (isSerializable < isRemote) {
                isSerializable = isRemote;
            }


            SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext,
                    methodGen, sourceFile, handle);

            bugReporter.reportBug(new BugInstance(this, "DMI_NONSERIALIZABLE_OBJECT_WRITTEN",
                    isSerializable < 0.15 ? HIGH_PRIORITY : isSerializable > 0.5 ? LOW_PRIORITY : NORMAL_PRIORITY)
                            .addClassAndMethod(methodGen, sourceFile).addType(problem).describe(TypeAnnotation.FOUND_ROLE)
                            .addSourceLine(sourceLineAnnotation));

        } catch (ClassNotFoundException e) {
            // ignore
        }
    }
}