1 // BugReporterVisitors.cpp - Helpers for reporting bugs -----------*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a set of BugReporter "visitors" which can be used to
11 // enhance the diagnostics reported for a bug.
13 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitor.h"
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Support/raw_ostream.h"
27 using namespace clang;
30 using llvm::FoldingSetNodeID;
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 bool bugreporter::isDeclRefExprToReference(const Expr *E) {
37 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
38 return DRE->getDecl()->getType()->isReferenceType();
43 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
44 // Pattern match for a few useful cases:
46 const Expr *E = dyn_cast<Expr>(S);
49 E = E->IgnoreParenCasts();
52 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
53 assert(B->isAssignmentOp());
54 E = B->getLHS()->IgnoreParenCasts();
57 else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
58 if (U->getOpcode() == UO_Deref)
59 return U->getSubExpr()->IgnoreParenCasts();
61 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
62 if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
63 return ME->getBase()->IgnoreParenCasts();
65 // If we have a member expr with a dot, the base must have been
67 return getDerefExpr(ME->getBase());
70 else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
71 return IvarRef->getBase()->IgnoreParenCasts();
73 else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
76 else if (isDeclRefExprToReference(E)) {
85 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
86 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
87 if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
92 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
93 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
94 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
95 return RS->getRetValue();
99 //===----------------------------------------------------------------------===//
100 // Definitions for bug reporter visitors.
101 //===----------------------------------------------------------------------===//
104 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
105 const ExplodedNode *EndPathNode,
111 BugReporterVisitor::getDefaultEndPath(BugReporterContext &BRC,
112 const ExplodedNode *EndPathNode,
114 PathDiagnosticLocation L =
115 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
117 BugReport::ranges_iterator Beg, End;
118 llvm::tie(Beg, End) = BR.getRanges();
120 // Only add the statement itself as a range if we didn't specify any
121 // special ranges for this report.
122 PathDiagnosticPiece *P = new PathDiagnosticEventPiece(L,
125 for (; Beg != End; ++Beg)
133 /// Emits an extra note at the return statement of an interesting stack frame.
135 /// The returned value is marked as an interesting value, and if it's null,
136 /// adds a visitor to track where it became null.
138 /// This visitor is intended to be used when another visitor discovers that an
139 /// interesting value comes from an inlined function call.
140 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
141 const StackFrameContext *StackFrame;
148 bool EnableNullFPSuppression;
151 ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
152 : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
154 static void *getTag() {
156 return static_cast<void *>(&Tag);
159 virtual void Profile(llvm::FoldingSetNodeID &ID) const {
160 ID.AddPointer(ReturnVisitor::getTag());
161 ID.AddPointer(StackFrame);
162 ID.AddBoolean(EnableNullFPSuppression);
165 /// Adds a ReturnVisitor if the given statement represents a call that was
168 /// This will search back through the ExplodedGraph, starting from the given
169 /// node, looking for when the given statement was processed. If it turns out
170 /// the statement is a call that was inlined, we add the visitor to the
171 /// bug report, so it can print a note later.
172 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
174 bool InEnableNullFPSuppression) {
175 if (!CallEvent::isCallStmt(S))
178 // First, find when we processed the statement.
180 if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
181 if (CEE->getCalleeContext()->getCallSite() == S)
183 if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
184 if (SP->getStmt() == S)
187 Node = Node->getFirstPred();
190 // Next, step over any post-statement checks.
191 while (Node && Node->getLocation().getAs<PostStmt>())
192 Node = Node->getFirstPred();
196 // Finally, see if we inlined the call.
197 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
201 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
202 if (CalleeContext->getCallSite() != S)
205 // Check the return value.
206 ProgramStateRef State = Node->getState();
207 SVal RetVal = State->getSVal(S, Node->getLocationContext());
209 // Handle cases where a reference is returned and then immediately used.
210 if (cast<Expr>(S)->isGLValue())
211 if (Optional<Loc> LValue = RetVal.getAs<Loc>())
212 RetVal = State->getSVal(*LValue);
214 // See if the return value is NULL. If so, suppress the report.
215 SubEngine *Eng = State->getStateManager().getOwningEngine();
216 assert(Eng && "Cannot file a bug report without an owning engine");
217 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
219 bool EnableNullFPSuppression = false;
220 if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
221 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
222 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
224 BR.markInteresting(CalleeContext);
225 BR.addVisitor(new ReturnVisitor(CalleeContext, EnableNullFPSuppression));
228 /// Returns true if any counter-suppression heuristics are enabled for
230 static bool hasCounterSuppression(AnalyzerOptions &Options) {
231 return Options.shouldAvoidSuppressingNullArgumentPaths();
234 PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
235 const ExplodedNode *PrevN,
236 BugReporterContext &BRC,
238 // Only print a message at the interesting return statement.
239 if (N->getLocationContext() != StackFrame)
242 Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
246 const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
250 // Okay, we're at the right return statement, but do we have the return
252 ProgramStateRef State = N->getState();
253 SVal V = State->getSVal(Ret, StackFrame);
254 if (V.isUnknownOrUndef())
257 // Don't print any more notes after this one.
260 const Expr *RetE = Ret->getRetValue();
261 assert(RetE && "Tracking a return value for a void function");
263 // Handle cases where a reference is returned and then immediately used.
264 Optional<Loc> LValue;
265 if (RetE->isGLValue()) {
266 if ((LValue = V.getAs<Loc>())) {
267 SVal RValue = State->getRawSVal(*LValue, RetE->getType());
268 if (RValue.getAs<DefinedSVal>())
273 // Ignore aggregate rvalues.
274 if (V.getAs<nonloc::LazyCompoundVal>() ||
275 V.getAs<nonloc::CompoundVal>())
278 RetE = RetE->IgnoreParenCasts();
280 // If we can't prove the return value is 0, just mark it interesting, and
281 // make sure to track it into any further inner functions.
282 if (!State->isNull(V).isConstrainedTrue()) {
283 BR.markInteresting(V);
284 ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
285 EnableNullFPSuppression);
289 // If we're returning 0, we should track where that 0 came from.
290 bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
291 EnableNullFPSuppression);
293 // Build an appropriate message based on the return value.
295 llvm::raw_svector_ostream Out(Msg);
297 if (V.getAs<Loc>()) {
298 // If we have counter-suppression enabled, make sure we keep visiting
299 // future nodes. We want to emit a path note as well, in case
300 // the report is resurrected as valid later on.
301 ExprEngine &Eng = BRC.getBugReporter().getEngine();
302 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
303 if (EnableNullFPSuppression && hasCounterSuppression(Options))
304 Mode = MaybeUnsuppress;
306 if (RetE->getType()->isObjCObjectPointerType())
307 Out << "Returning nil";
309 Out << "Returning null pointer";
311 Out << "Returning zero";
315 if (const MemRegion *MR = LValue->getAsRegion()) {
316 if (MR->canPrintPretty()) {
317 Out << " (reference to ";
318 MR->printPretty(Out);
323 // FIXME: We should have a more generalized location printing mechanism.
324 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
325 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
326 Out << " (loaded from '" << *DD << "')";
329 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
330 return new PathDiagnosticEventPiece(L, Out.str());
333 PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
334 const ExplodedNode *PrevN,
335 BugReporterContext &BRC,
338 ExprEngine &Eng = BRC.getBugReporter().getEngine();
339 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
340 assert(hasCounterSuppression(Options));
343 // Are we at the entry node for this call?
344 Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
348 if (CE->getCalleeContext() != StackFrame)
353 // Don't automatically suppress a report if one of the arguments is
354 // known to be a null pointer. Instead, start tracking /that/ null
355 // value back to its origin.
356 ProgramStateManager &StateMgr = BRC.getStateManager();
357 CallEventManager &CallMgr = StateMgr.getCallEventManager();
359 ProgramStateRef State = N->getState();
360 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
361 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
362 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
366 const Expr *ArgE = Call->getArgExpr(I);
370 // Is it possible for this argument to be non-null?
371 if (!State->isNull(*ArgV).isConstrainedTrue())
374 if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
375 EnableNullFPSuppression))
376 BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
378 // If we /can't/ track the null pointer, we should err on the side of
379 // false negatives, and continue towards marking this report invalid.
380 // (We will still look at the other arguments, though.)
386 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
387 const ExplodedNode *PrevN,
388 BugReporterContext &BRC,
392 return visitNodeInitial(N, PrevN, BRC, BR);
393 case MaybeUnsuppress:
394 return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
399 llvm_unreachable("Invalid visit mode!");
402 PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
403 const ExplodedNode *N,
405 if (EnableNullFPSuppression)
406 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
410 } // end anonymous namespace
413 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
418 ID.AddBoolean(EnableNullFPSuppression);
421 /// Returns true if \p N represents the DeclStmt declaring and initializing
423 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
424 Optional<PostStmt> P = N->getLocationAs<PostStmt>();
428 const DeclStmt *DS = P->getStmtAs<DeclStmt>();
432 if (DS->getSingleDecl() != VR->getDecl())
435 const MemSpaceRegion *VarSpace = VR->getMemorySpace();
436 const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
438 // If we ever directly evaluate global DeclStmts, this assertion will be
439 // invalid, but this still seems preferable to silently accepting an
440 // initialization that may be for a path-sensitive variable.
441 assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
445 assert(VR->getDecl()->hasLocalStorage());
446 const LocationContext *LCtx = N->getLocationContext();
447 return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
450 PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
451 const ExplodedNode *Pred,
452 BugReporterContext &BRC,
458 const ExplodedNode *StoreSite = 0;
459 const Expr *InitE = 0;
460 bool IsParam = false;
462 // First see if we reached the declaration of the region.
463 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
464 if (isInitializationOfVar(Pred, VR)) {
466 InitE = VR->getDecl()->getInit();
470 // If this is a post initializer expression, initializing the region, we
471 // should track the initializer expression.
472 if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
473 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
474 if (FieldReg && FieldReg == R) {
476 InitE = PIP->getInitializer()->getInit();
480 // Otherwise, see if this is the store site:
481 // (1) Succ has this binding and Pred does not, i.e. this is
482 // where the binding first occurred.
483 // (2) Succ has this binding and is a PostStore node for this region, i.e.
484 // the same binding was re-assigned here.
486 if (Succ->getState()->getSVal(R) != V)
489 if (Pred->getState()->getSVal(R) == V) {
490 Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
491 if (!PS || PS->getLocationValue() != R)
497 // If this is an assignment expression, we can track the value
499 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
500 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
501 if (BO->isAssignmentOp())
502 InitE = BO->getRHS();
504 // If this is a call entry, the variable should be a parameter.
505 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
506 // 'this' should never be NULL, but this visitor isn't just for NULL and
508 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
509 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
510 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
512 ProgramStateManager &StateMgr = BRC.getStateManager();
513 CallEventManager &CallMgr = StateMgr.getCallEventManager();
515 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
517 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
522 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
523 // is wrapped inside of it.
524 if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
525 InitE = TmpR->getExpr();
532 // If we have an expression that provided the value, try to track where it
536 V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
538 InitE = InitE->IgnoreParenCasts();
539 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
540 EnableNullFPSuppression);
542 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
543 BR, EnableNullFPSuppression);
547 // Okay, we've found the binding. Emit an appropriate message.
548 SmallString<256> sbuf;
549 llvm::raw_svector_ostream os(sbuf);
551 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
552 const Stmt *S = PS->getStmt();
553 const char *action = 0;
554 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
555 const VarRegion *VR = dyn_cast<VarRegion>(R);
558 action = R->canPrintPretty() ? "initialized to " :
560 } else if (isa<BlockExpr>(S)) {
561 action = R->canPrintPretty() ? "captured by block as " :
562 "Captured by block as ";
564 // See if we can get the BlockVarRegion.
565 ProgramStateRef State = StoreSite->getState();
566 SVal V = State->getSVal(S, PS->getLocationContext());
567 if (const BlockDataRegion *BDR =
568 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
569 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
570 if (Optional<KnownSVal> KV =
571 State->getSVal(OriginalR).getAs<KnownSVal>())
572 BR.addVisitor(new FindLastStoreBRVisitor(*KV, OriginalR,
573 EnableNullFPSuppression));
580 if (R->canPrintPretty()) {
585 if (V.getAs<loc::ConcreteInt>()) {
587 if (R->isBoundable()) {
588 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
589 if (TR->getValueType()->isObjCObjectPointerType()) {
590 os << action << "nil";
597 os << action << "a null pointer value";
598 } else if (Optional<nonloc::ConcreteInt> CVal =
599 V.getAs<nonloc::ConcreteInt>()) {
600 os << action << CVal->getValue();
604 if (isa<VarRegion>(R)) {
605 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
607 os << (R->canPrintPretty() ? "initialized" : "Initializing")
608 << " to a garbage value";
610 os << (R->canPrintPretty() ? "declared" : "Declaring")
611 << " without an initial value";
616 os << (R->canPrintPretty() ? "initialized" : "Initialized")
621 } else if (StoreSite->getLocation().getAs<CallEnter>()) {
622 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
623 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
627 if (V.getAs<loc::ConcreteInt>()) {
628 if (Param->getType()->isObjCObjectPointerType())
629 os << "nil object reference";
631 os << "null pointer value";
632 } else if (V.isUndef()) {
633 os << "uninitialized value";
634 } else if (Optional<nonloc::ConcreteInt> CI =
635 V.getAs<nonloc::ConcreteInt>()) {
636 os << "the value " << CI->getValue();
641 // Printed parameter indexes are 1-based, not 0-based.
642 unsigned Idx = Param->getFunctionScopeIndex() + 1;
643 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
644 if (R->canPrintPretty()) {
651 if (os.str().empty()) {
652 if (V.getAs<loc::ConcreteInt>()) {
654 if (R->isBoundable()) {
655 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
656 if (TR->getValueType()->isObjCObjectPointerType()) {
657 os << "nil object reference stored";
663 if (R->canPrintPretty())
664 os << "Null pointer value stored";
666 os << "Storing null pointer value";
669 } else if (V.isUndef()) {
670 if (R->canPrintPretty())
671 os << "Uninitialized value stored";
673 os << "Storing uninitialized value";
675 } else if (Optional<nonloc::ConcreteInt> CV =
676 V.getAs<nonloc::ConcreteInt>()) {
677 if (R->canPrintPretty())
678 os << "The value " << CV->getValue() << " is assigned";
680 os << "Assigning " << CV->getValue();
683 if (R->canPrintPretty())
684 os << "Value assigned";
686 os << "Assigning value";
689 if (R->canPrintPretty()) {
695 // Construct a new PathDiagnosticPiece.
696 ProgramPoint P = StoreSite->getLocation();
697 PathDiagnosticLocation L;
698 if (P.getAs<CallEnter>() && InitE)
699 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
700 P.getLocationContext());
702 if (!L.isValid() || !L.asLocation().isValid())
703 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
705 if (!L.isValid() || !L.asLocation().isValid())
708 return new PathDiagnosticEventPiece(L, os.str());
711 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
714 ID.AddBoolean(Assumption);
718 /// Return the tag associated with this visitor. This tag will be used
719 /// to make all PathDiagnosticPieces created by this visitor.
720 const char *TrackConstraintBRVisitor::getTag() {
721 return "TrackConstraintBRVisitor";
724 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
726 return N->getState()->isNull(Constraint).isUnderconstrained();
727 return N->getState()->assume(Constraint, !Assumption);
730 PathDiagnosticPiece *
731 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
732 const ExplodedNode *PrevN,
733 BugReporterContext &BRC,
738 // Start tracking after we see the first state in which the value is
740 if (!IsTrackingTurnedOn)
741 if (!isUnderconstrained(N))
742 IsTrackingTurnedOn = true;
743 if (!IsTrackingTurnedOn)
746 // Check if in the previous state it was feasible for this constraint
748 if (isUnderconstrained(PrevN)) {
752 // As a sanity check, make sure that the negation of the constraint
753 // was infeasible in the current state. If it is feasible, we somehow
754 // missed the transition point.
755 assert(!isUnderconstrained(N));
757 // We found the transition point for the constraint. We now need to
758 // pretty-print the constraint. (work-in-progress)
759 SmallString<64> sbuf;
760 llvm::raw_svector_ostream os(sbuf);
762 if (Constraint.getAs<Loc>()) {
763 os << "Assuming pointer value is ";
764 os << (Assumption ? "non-null" : "null");
767 if (os.str().empty())
770 // Construct a new PathDiagnosticPiece.
771 ProgramPoint P = N->getLocation();
772 PathDiagnosticLocation L =
773 PathDiagnosticLocation::create(P, BRC.getSourceManager());
777 PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
785 SuppressInlineDefensiveChecksVisitor::
786 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
787 : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
789 // Check if the visitor is disabled.
790 SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
791 assert(Eng && "Cannot file a bug report without an owning engine");
792 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
793 if (!Options.shouldSuppressInlinedDefensiveChecks())
796 assert(N->getState()->isNull(V).isConstrainedTrue() &&
797 "The visitor only tracks the cases where V is constrained to 0");
800 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
806 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
810 PathDiagnosticPiece *
811 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
812 const ExplodedNode *Pred,
813 BugReporterContext &BRC,
818 // Start tracking after we see the first state in which the value is null.
819 if (!IsTrackingTurnedOn)
820 if (Succ->getState()->isNull(V).isConstrainedTrue())
821 IsTrackingTurnedOn = true;
822 if (!IsTrackingTurnedOn)
825 // Check if in the previous state it was feasible for this value
827 if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
830 assert(Succ->getState()->isNull(V).isConstrainedTrue());
832 // Check if this is inlined defensive checks.
833 const LocationContext *CurLC =Succ->getLocationContext();
834 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
835 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
836 BR.markInvalid("Suppress IDC", CurLC);
841 static const MemRegion *getLocationRegionIfReference(const Expr *E,
842 const ExplodedNode *N) {
843 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
844 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
845 if (!VD->getType()->isReferenceType())
847 ProgramStateManager &StateMgr = N->getState()->getStateManager();
848 MemRegionManager &MRMgr = StateMgr.getRegionManager();
849 return MRMgr.getVarRegion(VD, N->getLocationContext());
853 // FIXME: This does not handle other kinds of null references,
854 // for example, references from FieldRegions:
855 // struct Wrapper { int &ref; };
856 // Wrapper w = { *(int *)0 };
862 static const Expr *peelOffOuterExpr(const Expr *Ex,
863 const ExplodedNode *N) {
864 Ex = Ex->IgnoreParenCasts();
865 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
866 return peelOffOuterExpr(EWC->getSubExpr(), N);
867 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
868 return peelOffOuterExpr(OVE->getSourceExpr(), N);
870 // Peel off the ternary operator.
871 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
872 // Find a node where the branching occured and find out which branch
873 // we took (true/false) by looking at the ExplodedGraph.
874 const ExplodedNode *NI = N;
876 ProgramPoint ProgPoint = NI->getLocation();
877 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
878 const CFGBlock *srcBlk = BE->getSrc();
879 if (const Stmt *term = srcBlk->getTerminator()) {
881 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
883 return peelOffOuterExpr(CO->getTrueExpr(), N);
885 return peelOffOuterExpr(CO->getFalseExpr(), N);
889 NI = NI->getFirstPred();
895 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
897 BugReport &report, bool IsArg,
898 bool EnableNullFPSuppression) {
902 if (const Expr *Ex = dyn_cast<Expr>(S)) {
903 Ex = Ex->IgnoreParenCasts();
904 const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
909 const Expr *Inner = 0;
910 if (const Expr *Ex = dyn_cast<Expr>(S)) {
911 Ex = Ex->IgnoreParenCasts();
912 if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
916 if (IsArg && !Inner) {
917 assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
919 // Walk through nodes until we get one that matches the statement exactly.
920 // Alternately, if we hit a known lvalue for the statement, we know we've
921 // gone too far (though we can likely track the lvalue better anyway).
923 const ProgramPoint &pp = N->getLocation();
924 if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
925 if (ps->getStmt() == S || ps->getStmt() == Inner)
927 } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
928 if (CEE->getCalleeContext()->getCallSite() == S ||
929 CEE->getCalleeContext()->getCallSite() == Inner)
932 N = N->getFirstPred();
939 ProgramStateRef state = N->getState();
941 // The message send could be nil due to the receiver being nil.
942 // At this point in the path, the receiver should be live since we are at the
943 // message send expr. If it is nil, start tracking it.
944 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
945 trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
948 // See if the expression we're interested refers to a variable.
949 // If so, we can track both its contents and constraints on its value.
950 if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
951 const MemRegion *R = 0;
953 // Find the ExplodedNode where the lvalue (the value of 'Ex')
954 // was computed. We need this for getting the location value.
955 const ExplodedNode *LVNode = N;
957 if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
958 if (P->getStmt() == Inner)
961 LVNode = LVNode->getFirstPred();
963 assert(LVNode && "Unable to find the lvalue node.");
964 ProgramStateRef LVState = LVNode->getState();
965 SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
967 if (LVState->isNull(LVal).isConstrainedTrue()) {
968 // In case of C++ references, we want to differentiate between a null
969 // reference and reference to null pointer.
970 // If the LVal is null, check if we are dealing with null reference.
971 // For those, we want to track the location of the reference.
972 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
975 R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
977 // If this is a C++ reference to a null pointer, we are tracking the
978 // pointer. In additon, we should find the store at which the reference
980 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
981 if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
982 report.addVisitor(new FindLastStoreBRVisitor(*KV, RR,
983 EnableNullFPSuppression));
988 // Mark both the variable region and its contents as interesting.
989 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
991 report.markInteresting(R);
992 report.markInteresting(V);
993 report.addVisitor(new UndefOrNullArgVisitor(R));
995 // If the contents are symbolic, find out when they became null.
996 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true)) {
997 BugReporterVisitor *ConstraintTracker =
998 new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
999 report.addVisitor(ConstraintTracker);
1002 // Add visitor, which will suppress inline defensive checks.
1003 if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
1004 if (!DV->isZeroConstant() &&
1005 LVState->isNull(*DV).isConstrainedTrue() &&
1006 EnableNullFPSuppression) {
1007 BugReporterVisitor *IDCSuppressor =
1008 new SuppressInlineDefensiveChecksVisitor(*DV,
1010 report.addVisitor(IDCSuppressor);
1014 if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1015 report.addVisitor(new FindLastStoreBRVisitor(*KV, R,
1016 EnableNullFPSuppression));
1021 // If the expression is not an "lvalue expression", we can still
1022 // track the constraints on its contents.
1023 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1025 // If the value came from an inlined function call, we should at least make
1026 // sure that function isn't pruned in our output.
1027 if (const Expr *E = dyn_cast<Expr>(S))
1028 S = E->IgnoreParenCasts();
1030 ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1032 // Uncomment this to find cases where we aren't properly getting the
1033 // base value that was dereferenced.
1034 // assert(!V.isUnknownOrUndef());
1035 // Is it a symbolic value?
1036 if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
1037 // At this point we are dealing with the region's LValue.
1038 // However, if the rvalue is a symbolic region, we should track it as well.
1039 // Try to use the correct type when looking up the value.
1041 if (const Expr *E = dyn_cast<Expr>(S))
1042 RVal = state->getRawSVal(L.getValue(), E->getType());
1044 RVal = state->getSVal(L->getRegion());
1046 const MemRegion *RegionRVal = RVal.getAsRegion();
1047 report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
1049 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1050 report.markInteresting(RegionRVal);
1051 report.addVisitor(new TrackConstraintBRVisitor(
1052 loc::MemRegionVal(RegionRVal), false));
1059 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1060 const ExplodedNode *N) {
1061 const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1064 if (const Expr *Receiver = ME->getInstanceReceiver()) {
1065 ProgramStateRef state = N->getState();
1066 SVal V = state->getSVal(Receiver, N->getLocationContext());
1067 if (state->isNull(V).isConstrainedTrue())
1073 PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1074 const ExplodedNode *PrevN,
1075 BugReporterContext &BRC,
1077 Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1081 const Stmt *S = P->getStmt();
1082 const Expr *Receiver = getNilReceiver(S, N);
1086 llvm::SmallString<256> Buf;
1087 llvm::raw_svector_ostream OS(Buf);
1089 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1090 OS << "'" << ME->getSelector().getAsString() << "' not called";
1093 OS << "No method is called";
1095 OS << " because the receiver is nil";
1097 // The receiver was nil, and hence the method was skipped.
1098 // Register a BugReporterVisitor to issue a message telling us how
1099 // the receiver was null.
1100 bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1101 /*EnableNullFPSuppression*/ false);
1102 // Issue a message saying that the method was skipped.
1103 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1104 N->getLocationContext());
1105 return new PathDiagnosticEventPiece(L, OS.str());
1108 // Registers every VarDecl inside a Stmt with a last store visitor.
1109 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1111 bool EnableNullFPSuppression) {
1112 const ExplodedNode *N = BR.getErrorNode();
1113 std::deque<const Stmt *> WorkList;
1114 WorkList.push_back(S);
1116 while (!WorkList.empty()) {
1117 const Stmt *Head = WorkList.front();
1118 WorkList.pop_front();
1120 ProgramStateRef state = N->getState();
1121 ProgramStateManager &StateMgr = state->getStateManager();
1123 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1124 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1125 const VarRegion *R =
1126 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1128 // What did we load?
1129 SVal V = state->getSVal(S, N->getLocationContext());
1131 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1132 // Register a new visitor with the BugReport.
1133 BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R,
1134 EnableNullFPSuppression));
1139 for (Stmt::const_child_iterator I = Head->child_begin();
1140 I != Head->child_end(); ++I)
1141 WorkList.push_back(*I);
1145 //===----------------------------------------------------------------------===//
1146 // Visitor that tries to report interesting diagnostics from conditions.
1147 //===----------------------------------------------------------------------===//
1149 /// Return the tag associated with this visitor. This tag will be used
1150 /// to make all PathDiagnosticPieces created by this visitor.
1151 const char *ConditionBRVisitor::getTag() {
1152 return "ConditionBRVisitor";
1155 PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1156 const ExplodedNode *Prev,
1157 BugReporterContext &BRC,
1159 PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
1161 piece->setTag(getTag());
1162 if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
1163 ev->setPrunable(true, /* override */ false);
1168 PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1169 const ExplodedNode *Prev,
1170 BugReporterContext &BRC,
1173 ProgramPoint progPoint = N->getLocation();
1174 ProgramStateRef CurrentState = N->getState();
1175 ProgramStateRef PrevState = Prev->getState();
1177 // Compare the GDMs of the state, because that is where constraints
1178 // are managed. Note that ensure that we only look at nodes that
1179 // were generated by the analyzer engine proper, not checkers.
1180 if (CurrentState->getGDM().getRoot() ==
1181 PrevState->getGDM().getRoot())
1184 // If an assumption was made on a branch, it should be caught
1185 // here by looking at the state transition.
1186 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1187 const CFGBlock *srcBlk = BE->getSrc();
1188 if (const Stmt *term = srcBlk->getTerminator())
1189 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1193 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1194 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1196 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1197 cast<GRBugReporter>(BRC.getBugReporter()).
1198 getEngine().geteagerlyAssumeBinOpBifurcationTags();
1200 const ProgramPointTag *tag = PS->getTag();
1201 if (tag == tags.first)
1202 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1204 if (tag == tags.second)
1205 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1214 PathDiagnosticPiece *
1215 ConditionBRVisitor::VisitTerminator(const Stmt *Term,
1216 const ExplodedNode *N,
1217 const CFGBlock *srcBlk,
1218 const CFGBlock *dstBlk,
1220 BugReporterContext &BRC) {
1221 const Expr *Cond = 0;
1223 switch (Term->getStmtClass()) {
1226 case Stmt::IfStmtClass:
1227 Cond = cast<IfStmt>(Term)->getCond();
1229 case Stmt::ConditionalOperatorClass:
1230 Cond = cast<ConditionalOperator>(Term)->getCond();
1235 assert(srcBlk->succ_size() == 2);
1236 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1237 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1240 PathDiagnosticPiece *
1241 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1243 BugReporterContext &BRC,
1245 const ExplodedNode *N) {
1247 const Expr *Ex = Cond;
1250 Ex = Ex->IgnoreParenCasts();
1251 switch (Ex->getStmtClass()) {
1254 case Stmt::BinaryOperatorClass:
1255 return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
1257 case Stmt::DeclRefExprClass:
1258 return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
1260 case Stmt::UnaryOperatorClass: {
1261 const UnaryOperator *UO = cast<UnaryOperator>(Ex);
1262 if (UO->getOpcode() == UO_LNot) {
1263 tookTrue = !tookTrue;
1264 Ex = UO->getSubExpr();
1273 bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
1274 BugReporterContext &BRC,
1276 const ExplodedNode *N,
1277 Optional<bool> &prunable) {
1278 const Expr *OriginalExpr = Ex;
1279 Ex = Ex->IgnoreParenCasts();
1281 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1282 const bool quotes = isa<VarDecl>(DR->getDecl());
1285 const LocationContext *LCtx = N->getLocationContext();
1286 const ProgramState *state = N->getState().getPtr();
1287 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1288 LCtx).getAsRegion()) {
1289 if (report.isInteresting(R))
1292 const ProgramState *state = N->getState().getPtr();
1293 SVal V = state->getSVal(R);
1294 if (report.isInteresting(V))
1299 Out << DR->getDecl()->getDeclName().getAsString();
1305 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1306 QualType OriginalTy = OriginalExpr->getType();
1307 if (OriginalTy->isPointerType()) {
1308 if (IL->getValue() == 0) {
1313 else if (OriginalTy->isObjCObjectPointerType()) {
1314 if (IL->getValue() == 0) {
1320 Out << IL->getValue();
1327 PathDiagnosticPiece *
1328 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1329 const BinaryOperator *BExpr,
1330 const bool tookTrue,
1331 BugReporterContext &BRC,
1333 const ExplodedNode *N) {
1335 bool shouldInvert = false;
1336 Optional<bool> shouldPrune;
1338 SmallString<128> LhsString, RhsString;
1340 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1341 const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1343 const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1346 shouldInvert = !isVarLHS && isVarRHS;
1349 BinaryOperator::Opcode Op = BExpr->getOpcode();
1351 if (BinaryOperator::isAssignmentOp(Op)) {
1352 // For assignment operators, all that we care about is that the LHS
1353 // evaluates to "true" or "false".
1354 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1358 // For non-assignment operations, we require that we can understand
1359 // both the LHS and RHS.
1360 if (LhsString.empty() || RhsString.empty() ||
1361 !BinaryOperator::isComparisonOp(Op))
1364 // Should we invert the strings if the LHS is not a variable name?
1365 SmallString<256> buf;
1366 llvm::raw_svector_ostream Out(buf);
1367 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1369 // Do we need to invert the opcode?
1373 case BO_LT: Op = BO_GT; break;
1374 case BO_GT: Op = BO_LT; break;
1375 case BO_LE: Op = BO_GE; break;
1376 case BO_GE: Op = BO_LE; break;
1381 case BO_EQ: Op = BO_NE; break;
1382 case BO_NE: Op = BO_EQ; break;
1383 case BO_LT: Op = BO_GE; break;
1384 case BO_GT: Op = BO_LE; break;
1385 case BO_LE: Op = BO_GT; break;
1386 case BO_GE: Op = BO_LT; break;
1396 Out << "not equal to ";
1399 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1403 Out << (shouldInvert ? LhsString : RhsString);
1404 const LocationContext *LCtx = N->getLocationContext();
1405 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1406 PathDiagnosticEventPiece *event =
1407 new PathDiagnosticEventPiece(Loc, Out.str());
1408 if (shouldPrune.hasValue())
1409 event->setPrunable(shouldPrune.getValue());
1413 PathDiagnosticPiece *
1414 ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1415 const Expr *CondVarExpr,
1416 const bool tookTrue,
1417 BugReporterContext &BRC,
1419 const ExplodedNode *N) {
1420 // FIXME: If there's already a constraint tracker for this variable,
1421 // we shouldn't emit anything here (c.f. the double note in
1422 // test/Analysis/inlining/path-notes.c)
1423 SmallString<256> buf;
1424 llvm::raw_svector_ostream Out(buf);
1425 Out << "Assuming " << LhsString << " is ";
1427 QualType Ty = CondVarExpr->getType();
1429 if (Ty->isPointerType())
1430 Out << (tookTrue ? "not null" : "null");
1431 else if (Ty->isObjCObjectPointerType())
1432 Out << (tookTrue ? "not nil" : "nil");
1433 else if (Ty->isBooleanType())
1434 Out << (tookTrue ? "true" : "false");
1435 else if (Ty->isIntegralOrEnumerationType())
1436 Out << (tookTrue ? "non-zero" : "zero");
1440 const LocationContext *LCtx = N->getLocationContext();
1441 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1442 PathDiagnosticEventPiece *event =
1443 new PathDiagnosticEventPiece(Loc, Out.str());
1445 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1446 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1447 const ProgramState *state = N->getState().getPtr();
1448 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1449 if (report.isInteresting(R))
1450 event->setPrunable(false);
1458 PathDiagnosticPiece *
1459 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1460 const DeclRefExpr *DR,
1461 const bool tookTrue,
1462 BugReporterContext &BRC,
1464 const ExplodedNode *N) {
1466 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1470 SmallString<256> Buf;
1471 llvm::raw_svector_ostream Out(Buf);
1473 Out << "Assuming '" << VD->getDeclName() << "' is ";
1475 QualType VDTy = VD->getType();
1477 if (VDTy->isPointerType())
1478 Out << (tookTrue ? "non-null" : "null");
1479 else if (VDTy->isObjCObjectPointerType())
1480 Out << (tookTrue ? "non-nil" : "nil");
1481 else if (VDTy->isScalarType())
1482 Out << (tookTrue ? "not equal to 0" : "0");
1486 const LocationContext *LCtx = N->getLocationContext();
1487 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1488 PathDiagnosticEventPiece *event =
1489 new PathDiagnosticEventPiece(Loc, Out.str());
1491 const ProgramState *state = N->getState().getPtr();
1492 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1493 if (report.isInteresting(R))
1494 event->setPrunable(false);
1496 SVal V = state->getSVal(R);
1497 if (report.isInteresting(V))
1498 event->setPrunable(false);
1505 // FIXME: Copied from ExprEngineCallAndReturn.cpp.
1506 static bool isInStdNamespace(const Decl *D) {
1507 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
1508 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
1512 while (const NamespaceDecl *Parent = dyn_cast<NamespaceDecl>(ND->getParent()))
1515 return ND->getName() == "std";
1519 PathDiagnosticPiece *
1520 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1521 const ExplodedNode *N,
1523 // Here we suppress false positives coming from system headers. This list is
1524 // based on known issues.
1525 ExprEngine &Eng = BRC.getBugReporter().getEngine();
1526 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1527 const Decl *D = N->getLocationContext()->getDecl();
1529 if (isInStdNamespace(D)) {
1530 // Skip reports within the 'std' namespace. Although these can sometimes be
1531 // the user's fault, we currently don't report them very well, and
1532 // Note that this will not help for any other data structure libraries, like
1533 // TR1, Boost, or llvm/ADT.
1534 if (Options.shouldSuppressFromCXXStandardLibrary()) {
1535 BR.markInvalid(getTag(), 0);
1539 // If the the complete 'std' suppression is not enabled, suppress reports
1540 // from the 'std' namespace that are known to produce false positives.
1542 // The analyzer issues a false use-after-free when std::list::pop_front
1543 // or std::list::pop_back are called multiple times because we cannot
1544 // reason about the internal invariants of the datastructure.
1545 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1546 const CXXRecordDecl *CD = MD->getParent();
1547 if (CD->getName() == "list") {
1548 BR.markInvalid(getTag(), 0);
1553 // The analyzer issues a false positive on
1554 // std::basic_string<uint8_t> v; v.push_back(1);
1556 // std::u16string s; s += u'a';
1557 // because we cannot reason about the internal invariants of the
1559 const LocationContext *LCtx = N->getLocationContext();
1561 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
1565 const CXXRecordDecl *CD = MD->getParent();
1566 if (CD->getName() == "basic_string") {
1567 BR.markInvalid(getTag(), 0);
1569 } else if (CD->getName().find("allocator") == StringRef::npos) {
1570 // Only keep searching if the current method is in a class with the
1571 // word "allocator" in its name, e.g. std::allocator or
1572 // allocator_traits.
1576 LCtx = LCtx->getParent();
1581 // Skip reports within the sys/queue.h macros as we do not have the ability to
1582 // reason about data structure shapes.
1583 SourceManager &SM = BRC.getSourceManager();
1584 FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1585 while (Loc.isMacroID()) {
1586 Loc = Loc.getSpellingLoc();
1587 if (SM.getFilename(Loc).endswith("sys/queue.h")) {
1588 BR.markInvalid(getTag(), 0);
1596 PathDiagnosticPiece *
1597 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1598 const ExplodedNode *PrevN,
1599 BugReporterContext &BRC,
1602 ProgramStateRef State = N->getState();
1603 ProgramPoint ProgLoc = N->getLocation();
1605 // We are only interested in visiting CallEnter nodes.
1606 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1610 // Check if one of the arguments is the region the visitor is tracking.
1611 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1612 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1614 for (CallEvent::param_iterator I = Call->param_begin(),
1615 E = Call->param_end(); I != E; ++I, ++Idx) {
1616 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1618 // Are we tracking the argument or its subregion?
1619 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1622 // Check the function parameter type.
1623 const ParmVarDecl *ParamDecl = *I;
1624 assert(ParamDecl && "Formal parameter has no decl?");
1625 QualType T = ParamDecl->getType();
1627 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1628 // Function can only change the value passed in by address.
1632 // If it is a const pointer value, the function does not intend to
1633 // change the value.
1634 if (T->getPointeeType().isConstQualified())
1637 // Mark the call site (LocationContext) as interesting if the value of the
1638 // argument is undefined or '0'/'NULL'.
1639 SVal BoundVal = State->getSVal(R);
1640 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1641 BR.markInteresting(CEnter->getCalleeContext());