Java Code Examples for edu.umd.cs.findbugs.BugInstance#add()

The following examples show how to use edu.umd.cs.findbugs.BugInstance#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NoiseNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void reportNullDeref(WarningPropertySet<WarningProperty> propertySet, Location location, String type, int priority,
        BugAnnotation cause, @CheckForNull BugAnnotation variable) {

    BugInstance bugInstance = new BugInstance(this, type, priority).addClassAndMethod(classContext.getJavaClass(), method);
    bugInstance.add(cause);
    if (variable != null) {
        bugInstance.add(variable);
    } else {
        bugInstance.add(new LocalVariableAnnotation("?", -1, -1));
    }
    bugInstance.addSourceLine(classContext, method, location).describe("SOURCE_LINE_DEREF");

    if (FindBugsAnalysisFeatures.isRelaxedMode()) {
        WarningPropertyUtil.addPropertiesForDataMining(propertySet, classContext, method, location);
    }
    addPropertiesForDereferenceLocations(propertySet, Collections.singleton(location));

    propertySet.decorateBugInstance(bugInstance);

    bugReporter.reportBug(bugInstance);
}
 
Example 2
Source File: PreferZeroLengthArrays.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code obj) {
    found.clear();
    // Solution to sourceforge bug 1765925; returning null is the
    // convention used by java.io.File.listFiles()
    if ("listFiles".equals(getMethodName())) {
        return;
    }
    String returnType = getMethodSig().substring(getMethodSig().indexOf(')') + 1);
    if (returnType.startsWith("[")) {
        nullOnTOS = false;
        super.visit(obj);
        if (!found.isEmpty()) {
            BugInstance bug = new BugInstance(this, "PZLA_PREFER_ZERO_LENGTH_ARRAYS", LOW_PRIORITY).addClassAndMethod(this);
            for (SourceLineAnnotation s : found) {
                bug.add(s);
            }
            bugReporter.reportBug(bug);
            found.clear();
        }
    }
}
 
Example 3
Source File: FindUselessObjects.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
void report() {
    for (ValueInfo vi : observedValues.values()) {
        if (!vi.escaped) {
            if (vi.hasObjectOnlyCall && vi.used && vi.var == null) {
                continue;
            }
            if (vi.hasObjectOnlyCall || (vi.used && vi.var != null)) {
                BugInstance bug = new BugInstance(vi.var == null ? "UC_USELESS_OBJECT_STACK" : "UC_USELESS_OBJECT",
                        NORMAL_PRIORITY).addClassAndMethod(classContext.getJavaClass(), method);
                if (vi.var != null) {
                    bug.add(new StringAnnotation(vi.var));
                }
                reporter.reportBug(bug.addType(vi.type).addSourceLine(classContext, method, vi.created));
            }
        }
    }
}
 
Example 4
Source File: FindNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void reportNullDeref(WarningPropertySet<WarningProperty> propertySet, Location location, String type, int priority,
        @CheckForNull BugAnnotation variable) {

    BugInstance bugInstance = new BugInstance(this, type, priority).addClassAndMethod(classContext.getJavaClass(), method);
    if (variable != null) {
        bugInstance.add(variable);
    } else {
        bugInstance.add(new LocalVariableAnnotation("?", -1, -1));
    }
    bugInstance.addSourceLine(classContext, method, location).describe("SOURCE_LINE_DEREF");

    if (FindBugsAnalysisFeatures.isRelaxedMode()) {
        WarningPropertyUtil.addPropertiesForDataMining(propertySet, classContext, method, location);
    }
    addPropertiesForDereferenceLocations(propertySet, Collections.singleton(location), false);

    propertySet.decorateBugInstance(bugInstance);

    bugReporter.reportBug(bugInstance);
}
 
Example 5
Source File: UnreadFields.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private BugInstance addClassFieldAndAccess(BugInstance instance, XField f) {
    if (data.writtenNonNullFields.contains(f) && data.readFields.contains(f)) {
        throw new IllegalArgumentException("No information for fields that are both read and written nonnull");
    }

    instance.addClass(f.getClassName()).addField(f);
    if (data.fieldAccess.containsKey(f)) {
        instance.add(data.fieldAccess.get(f));
    }
    return instance;
}
 
Example 6
Source File: FindFloatEquality.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    found.clear();
    priority = LOW_PRIORITY;

    state = SAW_NOTHING;

    super.visit(obj);
    bugAccumulator.reportAccumulatedBugs();
    if (!found.isEmpty()) {
        BugInstance bug = new BugInstance(this, "FE_FLOATING_POINT_EQUALITY", priority).addClassAndMethod(this);

        boolean first = true;
        for (SourceLineAnnotation s : found) {
            bug.add(s);
            if (first) {
                first = false;
            } else {
                bug.describe(SourceLineAnnotation.ROLE_ANOTHER_INSTANCE);
            }
        }

        bugReporter.reportBug(bug);

        found.clear();
    }
}
 
Example 7
Source File: InjectionSink.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void addMessage(BugInstance bug, String role, String text) {
    StringAnnotation stringAnnotation = new StringAnnotation(text);
    stringAnnotation.setDescription(role);
    bug.add(stringAnnotation);
}
 
Example 8
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 9
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 10
Source File: CheckTypeQualifiers.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void annotateWarningWithSourceSinkInfo(BugInstance warning, XMethod xMethod, ValueNumber vn,
        SourceSinkInfo sourceSinkInfo) {
    MethodDescriptor methodDescriptor = xMethod.getMethodDescriptor();
    switch (sourceSinkInfo.getType()) {
    case PARAMETER:
        try {
            Method method = Global.getAnalysisCache().getMethodAnalysis(Method.class, methodDescriptor);
            LocalVariableAnnotation lva = LocalVariableAnnotation.getParameterLocalVariableAnnotation(method,
                    sourceSinkInfo.getLocal());
            lva.setDescription(lva.isSignificant() ? LocalVariableAnnotation.PARAMETER_VALUE_SOURCE_NAMED_ROLE
                    : LocalVariableAnnotation.PARAMETER_VALUE_SOURCE_ROLE);

            warning.add(lva);
        } catch (CheckedAnalysisException e) {
            warning.addSourceLine(methodDescriptor, sourceSinkInfo.getLocation()).describe("SOURCE_LINE_VALUE_SOURCE");
        }
        break;

    case CONSTANT_VALUE:
        Object constantValue = sourceSinkInfo.getConstantValue();
        if (constantValue instanceof String) {
            warning.addString((String) constantValue).describe(StringAnnotation.STRING_CONSTANT_ROLE);
        } else if (constantValue instanceof Integer) {
            warning.addInt((Integer) constantValue).describe(IntAnnotation.INT_VALUE);
        } else if (constantValue == null) {
            warning.addString("null").describe(StringAnnotation.STRING_NONSTRING_CONSTANT_ROLE);
        } else {
            warning.addString(constantValue.toString()).describe(StringAnnotation.STRING_NONSTRING_CONSTANT_ROLE);
        }
        break;

    case RETURN_VALUE_OF_CALLED_METHOD:
    case FIELD_LOAD:
        warning.addSourceLine(methodDescriptor, sourceSinkInfo.getLocation()).describe("SOURCE_LINE_VALUE_SOURCE");
        break;

    case ARGUMENT_TO_CALLED_METHOD:
    case RETURN_VALUE:
    case FIELD_STORE:
        warning.addSourceLine(methodDescriptor, sourceSinkInfo.getLocation());
        return;

    default:
        throw new IllegalStateException();
    }
}