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
535 if (V.isUndef() || V.getAs<loc::ConcreteInt>()) {
537 InitE = InitE->IgnoreParenCasts();
538 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
539 EnableNullFPSuppression);
541 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
542 BR, EnableNullFPSuppression);
546 // Okay, we've found the binding. Emit an appropriate message.
547 SmallString<256> sbuf;
548 llvm::raw_svector_ostream os(sbuf);
550 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
551 const Stmt *S = PS->getStmt();
552 const char *action = 0;
553 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
554 const VarRegion *VR = dyn_cast<VarRegion>(R);
557 action = R->canPrintPretty() ? "initialized to " :
559 } else if (isa<BlockExpr>(S)) {
560 action = R->canPrintPretty() ? "captured by block as " :
561 "Captured by block as ";
563 // See if we can get the BlockVarRegion.
564 ProgramStateRef State = StoreSite->getState();
565 SVal V = State->getSVal(S, PS->getLocationContext());
566 if (const BlockDataRegion *BDR =
567 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
568 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
569 if (Optional<KnownSVal> KV =
570 State->getSVal(OriginalR).getAs<KnownSVal>())
571 BR.addVisitor(new FindLastStoreBRVisitor(*KV, OriginalR,
572 EnableNullFPSuppression));
579 if (R->canPrintPretty()) {
584 if (V.getAs<loc::ConcreteInt>()) {
586 if (R->isBoundable()) {
587 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
588 if (TR->getValueType()->isObjCObjectPointerType()) {
589 os << action << "nil";
596 os << action << "a null pointer value";
597 } else if (Optional<nonloc::ConcreteInt> CVal =
598 V.getAs<nonloc::ConcreteInt>()) {
599 os << action << CVal->getValue();
603 if (isa<VarRegion>(R)) {
604 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
606 os << (R->canPrintPretty() ? "initialized" : "Initializing")
607 << " to a garbage value";
609 os << (R->canPrintPretty() ? "declared" : "Declaring")
610 << " without an initial value";
615 os << (R->canPrintPretty() ? "initialized" : "Initialized")
620 } else if (StoreSite->getLocation().getAs<CallEnter>()) {
621 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
622 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
626 if (V.getAs<loc::ConcreteInt>()) {
627 if (Param->getType()->isObjCObjectPointerType())
628 os << "nil object reference";
630 os << "null pointer value";
631 } else if (V.isUndef()) {
632 os << "uninitialized value";
633 } else if (Optional<nonloc::ConcreteInt> CI =
634 V.getAs<nonloc::ConcreteInt>()) {
635 os << "the value " << CI->getValue();
640 // Printed parameter indexes are 1-based, not 0-based.
641 unsigned Idx = Param->getFunctionScopeIndex() + 1;
642 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
643 if (R->canPrintPretty()) {
650 if (os.str().empty()) {
651 if (V.getAs<loc::ConcreteInt>()) {
653 if (R->isBoundable()) {
654 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
655 if (TR->getValueType()->isObjCObjectPointerType()) {
656 os << "nil object reference stored";
662 if (R->canPrintPretty())
663 os << "Null pointer value stored";
665 os << "Storing null pointer value";
668 } else if (V.isUndef()) {
669 if (R->canPrintPretty())
670 os << "Uninitialized value stored";
672 os << "Storing uninitialized value";
674 } else if (Optional<nonloc::ConcreteInt> CV =
675 V.getAs<nonloc::ConcreteInt>()) {
676 if (R->canPrintPretty())
677 os << "The value " << CV->getValue() << " is assigned";
679 os << "Assigning " << CV->getValue();
682 if (R->canPrintPretty())
683 os << "Value assigned";
685 os << "Assigning value";
688 if (R->canPrintPretty()) {
694 // Construct a new PathDiagnosticPiece.
695 ProgramPoint P = StoreSite->getLocation();
696 PathDiagnosticLocation L;
697 if (P.getAs<CallEnter>() && InitE)
698 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
699 P.getLocationContext());
701 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
704 return new PathDiagnosticEventPiece(L, os.str());
707 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
710 ID.AddBoolean(Assumption);
714 /// Return the tag associated with this visitor. This tag will be used
715 /// to make all PathDiagnosticPieces created by this visitor.
716 const char *TrackConstraintBRVisitor::getTag() {
717 return "TrackConstraintBRVisitor";
720 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
722 return N->getState()->isNull(Constraint).isUnderconstrained();
723 return N->getState()->assume(Constraint, !Assumption);
726 PathDiagnosticPiece *
727 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
728 const ExplodedNode *PrevN,
729 BugReporterContext &BRC,
734 // Start tracking after we see the first state in which the value is
736 if (!IsTrackingTurnedOn)
737 if (!isUnderconstrained(N))
738 IsTrackingTurnedOn = true;
739 if (!IsTrackingTurnedOn)
742 // Check if in the previous state it was feasible for this constraint
744 if (isUnderconstrained(PrevN)) {
748 // As a sanity check, make sure that the negation of the constraint
749 // was infeasible in the current state. If it is feasible, we somehow
750 // missed the transition point.
751 assert(!isUnderconstrained(N));
753 // We found the transition point for the constraint. We now need to
754 // pretty-print the constraint. (work-in-progress)
755 SmallString<64> sbuf;
756 llvm::raw_svector_ostream os(sbuf);
758 if (Constraint.getAs<Loc>()) {
759 os << "Assuming pointer value is ";
760 os << (Assumption ? "non-null" : "null");
763 if (os.str().empty())
766 // Construct a new PathDiagnosticPiece.
767 ProgramPoint P = N->getLocation();
768 PathDiagnosticLocation L =
769 PathDiagnosticLocation::create(P, BRC.getSourceManager());
773 PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
781 SuppressInlineDefensiveChecksVisitor::
782 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
783 : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
785 // Check if the visitor is disabled.
786 SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
787 assert(Eng && "Cannot file a bug report without an owning engine");
788 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
789 if (!Options.shouldSuppressInlinedDefensiveChecks())
792 assert(N->getState()->isNull(V).isConstrainedTrue() &&
793 "The visitor only tracks the cases where V is constrained to 0");
796 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
802 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
806 PathDiagnosticPiece *
807 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
808 const ExplodedNode *Pred,
809 BugReporterContext &BRC,
814 // Start tracking after we see the first state in which the value is null.
815 if (!IsTrackingTurnedOn)
816 if (Succ->getState()->isNull(V).isConstrainedTrue())
817 IsTrackingTurnedOn = true;
818 if (!IsTrackingTurnedOn)
821 // Check if in the previous state it was feasible for this value
823 if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
826 assert(Succ->getState()->isNull(V).isConstrainedTrue());
828 // Check if this is inlined defensive checks.
829 const LocationContext *CurLC =Succ->getLocationContext();
830 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
831 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
832 BR.markInvalid("Suppress IDC", CurLC);
837 static const MemRegion *getLocationRegionIfReference(const Expr *E,
838 const ExplodedNode *N) {
839 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
840 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
841 if (!VD->getType()->isReferenceType())
843 ProgramStateManager &StateMgr = N->getState()->getStateManager();
844 MemRegionManager &MRMgr = StateMgr.getRegionManager();
845 return MRMgr.getVarRegion(VD, N->getLocationContext());
849 // FIXME: This does not handle other kinds of null references,
850 // for example, references from FieldRegions:
851 // struct Wrapper { int &ref; };
852 // Wrapper w = { *(int *)0 };
858 static const Expr *peelOffOuterExpr(const Expr *Ex,
859 const ExplodedNode *N) {
860 Ex = Ex->IgnoreParenCasts();
861 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
862 return peelOffOuterExpr(EWC->getSubExpr(), N);
863 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
864 return peelOffOuterExpr(OVE->getSourceExpr(), N);
866 // Peel off the ternary operator.
867 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
868 // Find a node where the branching occured and find out which branch
869 // we took (true/false) by looking at the ExplodedGraph.
870 const ExplodedNode *NI = N;
872 ProgramPoint ProgPoint = NI->getLocation();
873 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
874 const CFGBlock *srcBlk = BE->getSrc();
875 if (const Stmt *term = srcBlk->getTerminator()) {
877 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
879 return peelOffOuterExpr(CO->getTrueExpr(), N);
881 return peelOffOuterExpr(CO->getFalseExpr(), N);
885 NI = NI->getFirstPred();
891 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
893 BugReport &report, bool IsArg,
894 bool EnableNullFPSuppression) {
898 if (const Expr *Ex = dyn_cast<Expr>(S)) {
899 Ex = Ex->IgnoreParenCasts();
900 const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
905 const Expr *Inner = 0;
906 if (const Expr *Ex = dyn_cast<Expr>(S)) {
907 Ex = Ex->IgnoreParenCasts();
908 if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
912 if (IsArg && !Inner) {
913 assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
915 // Walk through nodes until we get one that matches the statement exactly.
916 // Alternately, if we hit a known lvalue for the statement, we know we've
917 // gone too far (though we can likely track the lvalue better anyway).
919 const ProgramPoint &pp = N->getLocation();
920 if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
921 if (ps->getStmt() == S || ps->getStmt() == Inner)
923 } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
924 if (CEE->getCalleeContext()->getCallSite() == S ||
925 CEE->getCalleeContext()->getCallSite() == Inner)
928 N = N->getFirstPred();
935 ProgramStateRef state = N->getState();
937 // The message send could be nil due to the receiver being nil.
938 // At this point in the path, the receiver should be live since we are at the
939 // message send expr. If it is nil, start tracking it.
940 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
941 trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
944 // See if the expression we're interested refers to a variable.
945 // If so, we can track both its contents and constraints on its value.
946 if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
947 const MemRegion *R = 0;
949 // Find the ExplodedNode where the lvalue (the value of 'Ex')
950 // was computed. We need this for getting the location value.
951 const ExplodedNode *LVNode = N;
953 if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
954 if (P->getStmt() == Inner)
957 LVNode = LVNode->getFirstPred();
959 assert(LVNode && "Unable to find the lvalue node.");
960 ProgramStateRef LVState = LVNode->getState();
961 SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
963 if (LVState->isNull(LVal).isConstrainedTrue()) {
964 // In case of C++ references, we want to differentiate between a null
965 // reference and reference to null pointer.
966 // If the LVal is null, check if we are dealing with null reference.
967 // For those, we want to track the location of the reference.
968 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
971 R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
973 // If this is a C++ reference to a null pointer, we are tracking the
974 // pointer. In additon, we should find the store at which the reference
976 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
977 if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
978 report.addVisitor(new FindLastStoreBRVisitor(*KV, RR,
979 EnableNullFPSuppression));
984 // Mark both the variable region and its contents as interesting.
985 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
987 report.markInteresting(R);
988 report.markInteresting(V);
989 report.addVisitor(new UndefOrNullArgVisitor(R));
991 // If the contents are symbolic, find out when they became null.
992 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true)) {
993 BugReporterVisitor *ConstraintTracker =
994 new TrackConstraintBRVisitor(V.castAs<DefinedSVal>(), false);
995 report.addVisitor(ConstraintTracker);
997 // Add visitor, which will suppress inline defensive checks.
998 if (LVState->isNull(V).isConstrainedTrue() &&
999 EnableNullFPSuppression) {
1000 BugReporterVisitor *IDCSuppressor =
1001 new SuppressInlineDefensiveChecksVisitor(V.castAs<DefinedSVal>(),
1003 report.addVisitor(IDCSuppressor);
1007 if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1008 report.addVisitor(new FindLastStoreBRVisitor(*KV, R,
1009 EnableNullFPSuppression));
1014 // If the expression is not an "lvalue expression", we can still
1015 // track the constraints on its contents.
1016 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1018 // If the value came from an inlined function call, we should at least make
1019 // sure that function isn't pruned in our output.
1020 if (const Expr *E = dyn_cast<Expr>(S))
1021 S = E->IgnoreParenCasts();
1023 ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1025 // Uncomment this to find cases where we aren't properly getting the
1026 // base value that was dereferenced.
1027 // assert(!V.isUnknownOrUndef());
1028 // Is it a symbolic value?
1029 if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
1030 // At this point we are dealing with the region's LValue.
1031 // However, if the rvalue is a symbolic region, we should track it as well.
1032 // Try to use the correct type when looking up the value.
1034 if (const Expr *E = dyn_cast<Expr>(S))
1035 RVal = state->getRawSVal(L.getValue(), E->getType());
1037 RVal = state->getSVal(L->getRegion());
1039 const MemRegion *RegionRVal = RVal.getAsRegion();
1040 report.addVisitor(new UndefOrNullArgVisitor(L->getRegion()));
1042 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1043 report.markInteresting(RegionRVal);
1044 report.addVisitor(new TrackConstraintBRVisitor(
1045 loc::MemRegionVal(RegionRVal), false));
1052 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1053 const ExplodedNode *N) {
1054 const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1057 if (const Expr *Receiver = ME->getInstanceReceiver()) {
1058 ProgramStateRef state = N->getState();
1059 SVal V = state->getSVal(Receiver, N->getLocationContext());
1060 if (state->isNull(V).isConstrainedTrue())
1066 PathDiagnosticPiece *NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1067 const ExplodedNode *PrevN,
1068 BugReporterContext &BRC,
1070 Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1074 const Stmt *S = P->getStmt();
1075 const Expr *Receiver = getNilReceiver(S, N);
1079 llvm::SmallString<256> Buf;
1080 llvm::raw_svector_ostream OS(Buf);
1082 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1083 OS << "'" << ME->getSelector().getAsString() << "' not called";
1086 OS << "No method is called";
1088 OS << " because the receiver is nil";
1090 // The receiver was nil, and hence the method was skipped.
1091 // Register a BugReporterVisitor to issue a message telling us how
1092 // the receiver was null.
1093 bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1094 /*EnableNullFPSuppression*/ false);
1095 // Issue a message saying that the method was skipped.
1096 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1097 N->getLocationContext());
1098 return new PathDiagnosticEventPiece(L, OS.str());
1101 // Registers every VarDecl inside a Stmt with a last store visitor.
1102 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1104 bool EnableNullFPSuppression) {
1105 const ExplodedNode *N = BR.getErrorNode();
1106 std::deque<const Stmt *> WorkList;
1107 WorkList.push_back(S);
1109 while (!WorkList.empty()) {
1110 const Stmt *Head = WorkList.front();
1111 WorkList.pop_front();
1113 ProgramStateRef state = N->getState();
1114 ProgramStateManager &StateMgr = state->getStateManager();
1116 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1117 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1118 const VarRegion *R =
1119 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1121 // What did we load?
1122 SVal V = state->getSVal(S, N->getLocationContext());
1124 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1125 // Register a new visitor with the BugReport.
1126 BR.addVisitor(new FindLastStoreBRVisitor(V.castAs<KnownSVal>(), R,
1127 EnableNullFPSuppression));
1132 for (Stmt::const_child_iterator I = Head->child_begin();
1133 I != Head->child_end(); ++I)
1134 WorkList.push_back(*I);
1138 //===----------------------------------------------------------------------===//
1139 // Visitor that tries to report interesting diagnostics from conditions.
1140 //===----------------------------------------------------------------------===//
1142 /// Return the tag associated with this visitor. This tag will be used
1143 /// to make all PathDiagnosticPieces created by this visitor.
1144 const char *ConditionBRVisitor::getTag() {
1145 return "ConditionBRVisitor";
1148 PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1149 const ExplodedNode *Prev,
1150 BugReporterContext &BRC,
1152 PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
1154 piece->setTag(getTag());
1155 if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
1156 ev->setPrunable(true, /* override */ false);
1161 PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1162 const ExplodedNode *Prev,
1163 BugReporterContext &BRC,
1166 ProgramPoint progPoint = N->getLocation();
1167 ProgramStateRef CurrentState = N->getState();
1168 ProgramStateRef PrevState = Prev->getState();
1170 // Compare the GDMs of the state, because that is where constraints
1171 // are managed. Note that ensure that we only look at nodes that
1172 // were generated by the analyzer engine proper, not checkers.
1173 if (CurrentState->getGDM().getRoot() ==
1174 PrevState->getGDM().getRoot())
1177 // If an assumption was made on a branch, it should be caught
1178 // here by looking at the state transition.
1179 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1180 const CFGBlock *srcBlk = BE->getSrc();
1181 if (const Stmt *term = srcBlk->getTerminator())
1182 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1186 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1187 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1189 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1190 cast<GRBugReporter>(BRC.getBugReporter()).
1191 getEngine().geteagerlyAssumeBinOpBifurcationTags();
1193 const ProgramPointTag *tag = PS->getTag();
1194 if (tag == tags.first)
1195 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1197 if (tag == tags.second)
1198 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1207 PathDiagnosticPiece *
1208 ConditionBRVisitor::VisitTerminator(const Stmt *Term,
1209 const ExplodedNode *N,
1210 const CFGBlock *srcBlk,
1211 const CFGBlock *dstBlk,
1213 BugReporterContext &BRC) {
1214 const Expr *Cond = 0;
1216 switch (Term->getStmtClass()) {
1219 case Stmt::IfStmtClass:
1220 Cond = cast<IfStmt>(Term)->getCond();
1222 case Stmt::ConditionalOperatorClass:
1223 Cond = cast<ConditionalOperator>(Term)->getCond();
1228 assert(srcBlk->succ_size() == 2);
1229 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1230 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1233 PathDiagnosticPiece *
1234 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1236 BugReporterContext &BRC,
1238 const ExplodedNode *N) {
1240 const Expr *Ex = Cond;
1243 Ex = Ex->IgnoreParenCasts();
1244 switch (Ex->getStmtClass()) {
1247 case Stmt::BinaryOperatorClass:
1248 return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
1250 case Stmt::DeclRefExprClass:
1251 return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
1253 case Stmt::UnaryOperatorClass: {
1254 const UnaryOperator *UO = cast<UnaryOperator>(Ex);
1255 if (UO->getOpcode() == UO_LNot) {
1256 tookTrue = !tookTrue;
1257 Ex = UO->getSubExpr();
1266 bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
1267 BugReporterContext &BRC,
1269 const ExplodedNode *N,
1270 Optional<bool> &prunable) {
1271 const Expr *OriginalExpr = Ex;
1272 Ex = Ex->IgnoreParenCasts();
1274 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1275 const bool quotes = isa<VarDecl>(DR->getDecl());
1278 const LocationContext *LCtx = N->getLocationContext();
1279 const ProgramState *state = N->getState().getPtr();
1280 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1281 LCtx).getAsRegion()) {
1282 if (report.isInteresting(R))
1285 const ProgramState *state = N->getState().getPtr();
1286 SVal V = state->getSVal(R);
1287 if (report.isInteresting(V))
1292 Out << DR->getDecl()->getDeclName().getAsString();
1298 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1299 QualType OriginalTy = OriginalExpr->getType();
1300 if (OriginalTy->isPointerType()) {
1301 if (IL->getValue() == 0) {
1306 else if (OriginalTy->isObjCObjectPointerType()) {
1307 if (IL->getValue() == 0) {
1313 Out << IL->getValue();
1320 PathDiagnosticPiece *
1321 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1322 const BinaryOperator *BExpr,
1323 const bool tookTrue,
1324 BugReporterContext &BRC,
1326 const ExplodedNode *N) {
1328 bool shouldInvert = false;
1329 Optional<bool> shouldPrune;
1331 SmallString<128> LhsString, RhsString;
1333 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1334 const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1336 const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1339 shouldInvert = !isVarLHS && isVarRHS;
1342 BinaryOperator::Opcode Op = BExpr->getOpcode();
1344 if (BinaryOperator::isAssignmentOp(Op)) {
1345 // For assignment operators, all that we care about is that the LHS
1346 // evaluates to "true" or "false".
1347 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1351 // For non-assignment operations, we require that we can understand
1352 // both the LHS and RHS.
1353 if (LhsString.empty() || RhsString.empty())
1356 // Should we invert the strings if the LHS is not a variable name?
1357 SmallString<256> buf;
1358 llvm::raw_svector_ostream Out(buf);
1359 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1361 // Do we need to invert the opcode?
1365 case BO_LT: Op = BO_GT; break;
1366 case BO_GT: Op = BO_LT; break;
1367 case BO_LE: Op = BO_GE; break;
1368 case BO_GE: Op = BO_LE; break;
1373 case BO_EQ: Op = BO_NE; break;
1374 case BO_NE: Op = BO_EQ; break;
1375 case BO_LT: Op = BO_GE; break;
1376 case BO_GT: Op = BO_LE; break;
1377 case BO_LE: Op = BO_GT; break;
1378 case BO_GE: Op = BO_LT; break;
1388 Out << "not equal to ";
1391 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1395 Out << (shouldInvert ? LhsString : RhsString);
1396 const LocationContext *LCtx = N->getLocationContext();
1397 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1398 PathDiagnosticEventPiece *event =
1399 new PathDiagnosticEventPiece(Loc, Out.str());
1400 if (shouldPrune.hasValue())
1401 event->setPrunable(shouldPrune.getValue());
1405 PathDiagnosticPiece *
1406 ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1407 const Expr *CondVarExpr,
1408 const bool tookTrue,
1409 BugReporterContext &BRC,
1411 const ExplodedNode *N) {
1412 // FIXME: If there's already a constraint tracker for this variable,
1413 // we shouldn't emit anything here (c.f. the double note in
1414 // test/Analysis/inlining/path-notes.c)
1415 SmallString<256> buf;
1416 llvm::raw_svector_ostream Out(buf);
1417 Out << "Assuming " << LhsString << " is ";
1419 QualType Ty = CondVarExpr->getType();
1421 if (Ty->isPointerType())
1422 Out << (tookTrue ? "not null" : "null");
1423 else if (Ty->isObjCObjectPointerType())
1424 Out << (tookTrue ? "not nil" : "nil");
1425 else if (Ty->isBooleanType())
1426 Out << (tookTrue ? "true" : "false");
1427 else if (Ty->isIntegralOrEnumerationType())
1428 Out << (tookTrue ? "non-zero" : "zero");
1432 const LocationContext *LCtx = N->getLocationContext();
1433 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1434 PathDiagnosticEventPiece *event =
1435 new PathDiagnosticEventPiece(Loc, Out.str());
1437 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1438 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1439 const ProgramState *state = N->getState().getPtr();
1440 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1441 if (report.isInteresting(R))
1442 event->setPrunable(false);
1450 PathDiagnosticPiece *
1451 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1452 const DeclRefExpr *DR,
1453 const bool tookTrue,
1454 BugReporterContext &BRC,
1456 const ExplodedNode *N) {
1458 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1462 SmallString<256> Buf;
1463 llvm::raw_svector_ostream Out(Buf);
1465 Out << "Assuming '";
1466 VD->getDeclName().printName(Out);
1469 QualType VDTy = VD->getType();
1471 if (VDTy->isPointerType())
1472 Out << (tookTrue ? "non-null" : "null");
1473 else if (VDTy->isObjCObjectPointerType())
1474 Out << (tookTrue ? "non-nil" : "nil");
1475 else if (VDTy->isScalarType())
1476 Out << (tookTrue ? "not equal to 0" : "0");
1480 const LocationContext *LCtx = N->getLocationContext();
1481 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1482 PathDiagnosticEventPiece *event =
1483 new PathDiagnosticEventPiece(Loc, Out.str());
1485 const ProgramState *state = N->getState().getPtr();
1486 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1487 if (report.isInteresting(R))
1488 event->setPrunable(false);
1490 SVal V = state->getSVal(R);
1491 if (report.isInteresting(V))
1492 event->setPrunable(false);
1499 // FIXME: Copied from ExprEngineCallAndReturn.cpp.
1500 static bool isInStdNamespace(const Decl *D) {
1501 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
1502 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
1506 while (const NamespaceDecl *Parent = dyn_cast<NamespaceDecl>(ND->getParent()))
1509 return ND->getName() == "std";
1513 PathDiagnosticPiece *
1514 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1515 const ExplodedNode *N,
1517 // Here we suppress false positives coming from system headers. This list is
1518 // based on known issues.
1520 // Skip reports within the 'std' namespace. Although these can sometimes be
1521 // the user's fault, we currently don't report them very well, and
1522 // Note that this will not help for any other data structure libraries, like
1523 // TR1, Boost, or llvm/ADT.
1524 ExprEngine &Eng = BRC.getBugReporter().getEngine();
1525 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1526 if (Options.shouldSuppressFromCXXStandardLibrary()) {
1527 const LocationContext *LCtx = N->getLocationContext();
1528 if (isInStdNamespace(LCtx->getDecl())) {
1529 BR.markInvalid(getTag(), 0);
1534 // Skip reports within the sys/queue.h macros as we do not have the ability to
1535 // reason about data structure shapes.
1536 SourceManager &SM = BRC.getSourceManager();
1537 FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1538 while (Loc.isMacroID()) {
1539 if (SM.isInSystemMacro(Loc) &&
1540 (SM.getFilename(SM.getSpellingLoc(Loc)).endswith("sys/queue.h"))) {
1541 BR.markInvalid(getTag(), 0);
1544 Loc = Loc.getSpellingLoc();
1550 PathDiagnosticPiece *
1551 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1552 const ExplodedNode *PrevN,
1553 BugReporterContext &BRC,
1556 ProgramStateRef State = N->getState();
1557 ProgramPoint ProgLoc = N->getLocation();
1559 // We are only interested in visiting CallEnter nodes.
1560 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1564 // Check if one of the arguments is the region the visitor is tracking.
1565 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1566 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1568 for (CallEvent::param_iterator I = Call->param_begin(),
1569 E = Call->param_end(); I != E; ++I, ++Idx) {
1570 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1572 // Are we tracking the argument or its subregion?
1573 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1576 // Check the function parameter type.
1577 const ParmVarDecl *ParamDecl = *I;
1578 assert(ParamDecl && "Formal parameter has no decl?");
1579 QualType T = ParamDecl->getType();
1581 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1582 // Function can only change the value passed in by address.
1586 // If it is a const pointer value, the function does not intend to
1587 // change the value.
1588 if (T->getPointeeType().isConstQualified())
1591 // Mark the call site (LocationContext) as interesting if the value of the
1592 // argument is undefined or '0'/'NULL'.
1593 SVal BoundVal = State->getSVal(R);
1594 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1595 BR.markInteresting(CEnter->getCalleeContext());