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 //===----------------------------------------------------------------------===//
103 std::unique_ptr<PathDiagnosticPiece>
104 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
105 const ExplodedNode *EndPathNode, BugReport &BR) {
109 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
110 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
111 PathDiagnosticLocation L =
112 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
114 BugReport::ranges_iterator Beg, End;
115 std::tie(Beg, End) = BR.getRanges();
117 // Only add the statement itself as a range if we didn't specify any
118 // special ranges for this report.
119 auto P = llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
121 for (; Beg != End; ++Beg)
129 /// Emits an extra note at the return statement of an interesting stack frame.
131 /// The returned value is marked as an interesting value, and if it's null,
132 /// adds a visitor to track where it became null.
134 /// This visitor is intended to be used when another visitor discovers that an
135 /// interesting value comes from an inlined function call.
136 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
137 const StackFrameContext *StackFrame;
144 bool EnableNullFPSuppression;
147 ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
148 : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
150 static void *getTag() {
152 return static_cast<void *>(&Tag);
155 void Profile(llvm::FoldingSetNodeID &ID) const override {
156 ID.AddPointer(ReturnVisitor::getTag());
157 ID.AddPointer(StackFrame);
158 ID.AddBoolean(EnableNullFPSuppression);
161 /// Adds a ReturnVisitor if the given statement represents a call that was
164 /// This will search back through the ExplodedGraph, starting from the given
165 /// node, looking for when the given statement was processed. If it turns out
166 /// the statement is a call that was inlined, we add the visitor to the
167 /// bug report, so it can print a note later.
168 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
170 bool InEnableNullFPSuppression) {
171 if (!CallEvent::isCallStmt(S))
174 // First, find when we processed the statement.
176 if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
177 if (CEE->getCalleeContext()->getCallSite() == S)
179 if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
180 if (SP->getStmt() == S)
183 Node = Node->getFirstPred();
186 // Next, step over any post-statement checks.
187 while (Node && Node->getLocation().getAs<PostStmt>())
188 Node = Node->getFirstPred();
192 // Finally, see if we inlined the call.
193 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
197 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
198 if (CalleeContext->getCallSite() != S)
201 // Check the return value.
202 ProgramStateRef State = Node->getState();
203 SVal RetVal = State->getSVal(S, Node->getLocationContext());
205 // Handle cases where a reference is returned and then immediately used.
206 if (cast<Expr>(S)->isGLValue())
207 if (Optional<Loc> LValue = RetVal.getAs<Loc>())
208 RetVal = State->getSVal(*LValue);
210 // See if the return value is NULL. If so, suppress the report.
211 SubEngine *Eng = State->getStateManager().getOwningEngine();
212 assert(Eng && "Cannot file a bug report without an owning engine");
213 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
215 bool EnableNullFPSuppression = false;
216 if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
217 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
218 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
220 BR.markInteresting(CalleeContext);
221 BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
222 EnableNullFPSuppression));
225 /// Returns true if any counter-suppression heuristics are enabled for
227 static bool hasCounterSuppression(AnalyzerOptions &Options) {
228 return Options.shouldAvoidSuppressingNullArgumentPaths();
231 PathDiagnosticPiece *visitNodeInitial(const ExplodedNode *N,
232 const ExplodedNode *PrevN,
233 BugReporterContext &BRC,
235 // Only print a message at the interesting return statement.
236 if (N->getLocationContext() != StackFrame)
239 Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
243 const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
247 // Okay, we're at the right return statement, but do we have the return
249 ProgramStateRef State = N->getState();
250 SVal V = State->getSVal(Ret, StackFrame);
251 if (V.isUnknownOrUndef())
254 // Don't print any more notes after this one.
257 const Expr *RetE = Ret->getRetValue();
258 assert(RetE && "Tracking a return value for a void function");
260 // Handle cases where a reference is returned and then immediately used.
261 Optional<Loc> LValue;
262 if (RetE->isGLValue()) {
263 if ((LValue = V.getAs<Loc>())) {
264 SVal RValue = State->getRawSVal(*LValue, RetE->getType());
265 if (RValue.getAs<DefinedSVal>())
270 // Ignore aggregate rvalues.
271 if (V.getAs<nonloc::LazyCompoundVal>() ||
272 V.getAs<nonloc::CompoundVal>())
275 RetE = RetE->IgnoreParenCasts();
277 // If we can't prove the return value is 0, just mark it interesting, and
278 // make sure to track it into any further inner functions.
279 if (!State->isNull(V).isConstrainedTrue()) {
280 BR.markInteresting(V);
281 ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
282 EnableNullFPSuppression);
286 // If we're returning 0, we should track where that 0 came from.
287 bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
288 EnableNullFPSuppression);
290 // Build an appropriate message based on the return value.
292 llvm::raw_svector_ostream Out(Msg);
294 if (V.getAs<Loc>()) {
295 // If we have counter-suppression enabled, make sure we keep visiting
296 // future nodes. We want to emit a path note as well, in case
297 // the report is resurrected as valid later on.
298 ExprEngine &Eng = BRC.getBugReporter().getEngine();
299 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
300 if (EnableNullFPSuppression && hasCounterSuppression(Options))
301 Mode = MaybeUnsuppress;
303 if (RetE->getType()->isObjCObjectPointerType())
304 Out << "Returning nil";
306 Out << "Returning null pointer";
308 Out << "Returning zero";
312 if (const MemRegion *MR = LValue->getAsRegion()) {
313 if (MR->canPrintPretty()) {
314 Out << " (reference to ";
315 MR->printPretty(Out);
320 // FIXME: We should have a more generalized location printing mechanism.
321 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
322 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
323 Out << " (loaded from '" << *DD << "')";
326 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
327 return new PathDiagnosticEventPiece(L, Out.str());
330 PathDiagnosticPiece *visitNodeMaybeUnsuppress(const ExplodedNode *N,
331 const ExplodedNode *PrevN,
332 BugReporterContext &BRC,
335 ExprEngine &Eng = BRC.getBugReporter().getEngine();
336 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
337 assert(hasCounterSuppression(Options));
340 // Are we at the entry node for this call?
341 Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
345 if (CE->getCalleeContext() != StackFrame)
350 // Don't automatically suppress a report if one of the arguments is
351 // known to be a null pointer. Instead, start tracking /that/ null
352 // value back to its origin.
353 ProgramStateManager &StateMgr = BRC.getStateManager();
354 CallEventManager &CallMgr = StateMgr.getCallEventManager();
356 ProgramStateRef State = N->getState();
357 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
358 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
359 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
363 const Expr *ArgE = Call->getArgExpr(I);
367 // Is it possible for this argument to be non-null?
368 if (!State->isNull(*ArgV).isConstrainedTrue())
371 if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
372 EnableNullFPSuppression))
373 BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
375 // If we /can't/ track the null pointer, we should err on the side of
376 // false negatives, and continue towards marking this report invalid.
377 // (We will still look at the other arguments, though.)
383 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
384 const ExplodedNode *PrevN,
385 BugReporterContext &BRC,
386 BugReport &BR) override {
389 return visitNodeInitial(N, PrevN, BRC, BR);
390 case MaybeUnsuppress:
391 return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
396 llvm_unreachable("Invalid visit mode!");
399 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
400 const ExplodedNode *N,
401 BugReport &BR) override {
402 if (EnableNullFPSuppression)
403 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
407 } // end anonymous namespace
410 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
415 ID.AddBoolean(EnableNullFPSuppression);
418 /// Returns true if \p N represents the DeclStmt declaring and initializing
420 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
421 Optional<PostStmt> P = N->getLocationAs<PostStmt>();
425 const DeclStmt *DS = P->getStmtAs<DeclStmt>();
429 if (DS->getSingleDecl() != VR->getDecl())
432 const MemSpaceRegion *VarSpace = VR->getMemorySpace();
433 const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
435 // If we ever directly evaluate global DeclStmts, this assertion will be
436 // invalid, but this still seems preferable to silently accepting an
437 // initialization that may be for a path-sensitive variable.
438 assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
442 assert(VR->getDecl()->hasLocalStorage());
443 const LocationContext *LCtx = N->getLocationContext();
444 return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
447 PathDiagnosticPiece *FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
448 const ExplodedNode *Pred,
449 BugReporterContext &BRC,
455 const ExplodedNode *StoreSite = nullptr;
456 const Expr *InitE = nullptr;
457 bool IsParam = false;
459 // First see if we reached the declaration of the region.
460 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
461 if (isInitializationOfVar(Pred, VR)) {
463 InitE = VR->getDecl()->getInit();
467 // If this is a post initializer expression, initializing the region, we
468 // should track the initializer expression.
469 if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
470 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
471 if (FieldReg && FieldReg == R) {
473 InitE = PIP->getInitializer()->getInit();
477 // Otherwise, see if this is the store site:
478 // (1) Succ has this binding and Pred does not, i.e. this is
479 // where the binding first occurred.
480 // (2) Succ has this binding and is a PostStore node for this region, i.e.
481 // the same binding was re-assigned here.
483 if (Succ->getState()->getSVal(R) != V)
486 if (Pred->getState()->getSVal(R) == V) {
487 Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
488 if (!PS || PS->getLocationValue() != R)
494 // If this is an assignment expression, we can track the value
496 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
497 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
498 if (BO->isAssignmentOp())
499 InitE = BO->getRHS();
501 // If this is a call entry, the variable should be a parameter.
502 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
503 // 'this' should never be NULL, but this visitor isn't just for NULL and
505 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
506 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
507 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
509 ProgramStateManager &StateMgr = BRC.getStateManager();
510 CallEventManager &CallMgr = StateMgr.getCallEventManager();
512 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
514 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
519 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
520 // is wrapped inside of it.
521 if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
522 InitE = TmpR->getExpr();
529 // If we have an expression that provided the value, try to track where it
533 V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
535 InitE = InitE->IgnoreParenCasts();
536 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
537 EnableNullFPSuppression);
539 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
540 BR, EnableNullFPSuppression);
544 // Okay, we've found the binding. Emit an appropriate message.
545 SmallString<256> sbuf;
546 llvm::raw_svector_ostream os(sbuf);
548 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
549 const Stmt *S = PS->getStmt();
550 const char *action = nullptr;
551 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
552 const VarRegion *VR = dyn_cast<VarRegion>(R);
555 action = R->canPrintPretty() ? "initialized to " :
557 } else if (isa<BlockExpr>(S)) {
558 action = R->canPrintPretty() ? "captured by block as " :
559 "Captured by block as ";
561 // See if we can get the BlockVarRegion.
562 ProgramStateRef State = StoreSite->getState();
563 SVal V = State->getSVal(S, PS->getLocationContext());
564 if (const BlockDataRegion *BDR =
565 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
566 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
567 if (Optional<KnownSVal> KV =
568 State->getSVal(OriginalR).getAs<KnownSVal>())
569 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
570 *KV, OriginalR, EnableNullFPSuppression));
577 if (R->canPrintPretty()) {
582 if (V.getAs<loc::ConcreteInt>()) {
584 if (R->isBoundable()) {
585 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
586 if (TR->getValueType()->isObjCObjectPointerType()) {
587 os << action << "nil";
594 os << action << "a null pointer value";
595 } else if (Optional<nonloc::ConcreteInt> CVal =
596 V.getAs<nonloc::ConcreteInt>()) {
597 os << action << CVal->getValue();
601 if (isa<VarRegion>(R)) {
602 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
604 os << (R->canPrintPretty() ? "initialized" : "Initializing")
605 << " to a garbage value";
607 os << (R->canPrintPretty() ? "declared" : "Declaring")
608 << " without an initial value";
613 os << (R->canPrintPretty() ? "initialized" : "Initialized")
618 } else if (StoreSite->getLocation().getAs<CallEnter>()) {
619 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
620 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
624 if (V.getAs<loc::ConcreteInt>()) {
625 if (Param->getType()->isObjCObjectPointerType())
626 os << "nil object reference";
628 os << "null pointer value";
629 } else if (V.isUndef()) {
630 os << "uninitialized value";
631 } else if (Optional<nonloc::ConcreteInt> CI =
632 V.getAs<nonloc::ConcreteInt>()) {
633 os << "the value " << CI->getValue();
638 // Printed parameter indexes are 1-based, not 0-based.
639 unsigned Idx = Param->getFunctionScopeIndex() + 1;
640 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
641 if (R->canPrintPretty()) {
648 if (os.str().empty()) {
649 if (V.getAs<loc::ConcreteInt>()) {
651 if (R->isBoundable()) {
652 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
653 if (TR->getValueType()->isObjCObjectPointerType()) {
654 os << "nil object reference stored";
660 if (R->canPrintPretty())
661 os << "Null pointer value stored";
663 os << "Storing null pointer value";
666 } else if (V.isUndef()) {
667 if (R->canPrintPretty())
668 os << "Uninitialized value stored";
670 os << "Storing uninitialized value";
672 } else if (Optional<nonloc::ConcreteInt> CV =
673 V.getAs<nonloc::ConcreteInt>()) {
674 if (R->canPrintPretty())
675 os << "The value " << CV->getValue() << " is assigned";
677 os << "Assigning " << CV->getValue();
680 if (R->canPrintPretty())
681 os << "Value assigned";
683 os << "Assigning value";
686 if (R->canPrintPretty()) {
692 // Construct a new PathDiagnosticPiece.
693 ProgramPoint P = StoreSite->getLocation();
694 PathDiagnosticLocation L;
695 if (P.getAs<CallEnter>() && InitE)
696 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
697 P.getLocationContext());
699 if (!L.isValid() || !L.asLocation().isValid())
700 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
702 if (!L.isValid() || !L.asLocation().isValid())
705 return new PathDiagnosticEventPiece(L, os.str());
708 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
711 ID.AddBoolean(Assumption);
715 /// Return the tag associated with this visitor. This tag will be used
716 /// to make all PathDiagnosticPieces created by this visitor.
717 const char *TrackConstraintBRVisitor::getTag() {
718 return "TrackConstraintBRVisitor";
721 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
723 return N->getState()->isNull(Constraint).isUnderconstrained();
724 return (bool)N->getState()->assume(Constraint, !Assumption);
727 PathDiagnosticPiece *
728 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
729 const ExplodedNode *PrevN,
730 BugReporterContext &BRC,
735 // Start tracking after we see the first state in which the value is
737 if (!IsTrackingTurnedOn)
738 if (!isUnderconstrained(N))
739 IsTrackingTurnedOn = true;
740 if (!IsTrackingTurnedOn)
743 // Check if in the previous state it was feasible for this constraint
745 if (isUnderconstrained(PrevN)) {
749 // As a sanity check, make sure that the negation of the constraint
750 // was infeasible in the current state. If it is feasible, we somehow
751 // missed the transition point.
752 assert(!isUnderconstrained(N));
754 // We found the transition point for the constraint. We now need to
755 // pretty-print the constraint. (work-in-progress)
756 SmallString<64> sbuf;
757 llvm::raw_svector_ostream os(sbuf);
759 if (Constraint.getAs<Loc>()) {
760 os << "Assuming pointer value is ";
761 os << (Assumption ? "non-null" : "null");
764 if (os.str().empty())
767 // Construct a new PathDiagnosticPiece.
768 ProgramPoint P = N->getLocation();
769 PathDiagnosticLocation L =
770 PathDiagnosticLocation::create(P, BRC.getSourceManager());
774 PathDiagnosticEventPiece *X = new PathDiagnosticEventPiece(L, os.str());
782 SuppressInlineDefensiveChecksVisitor::
783 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
784 : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
786 // Check if the visitor is disabled.
787 SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
788 assert(Eng && "Cannot file a bug report without an owning engine");
789 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
790 if (!Options.shouldSuppressInlinedDefensiveChecks())
793 assert(N->getState()->isNull(V).isConstrainedTrue() &&
794 "The visitor only tracks the cases where V is constrained to 0");
797 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
803 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
807 PathDiagnosticPiece *
808 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
809 const ExplodedNode *Pred,
810 BugReporterContext &BRC,
815 // Start tracking after we see the first state in which the value is null.
816 if (!IsTrackingTurnedOn)
817 if (Succ->getState()->isNull(V).isConstrainedTrue())
818 IsTrackingTurnedOn = true;
819 if (!IsTrackingTurnedOn)
822 // Check if in the previous state it was feasible for this value
824 if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
827 assert(Succ->getState()->isNull(V).isConstrainedTrue());
829 // Check if this is inlined defensive checks.
830 const LocationContext *CurLC =Succ->getLocationContext();
831 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
832 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC))
833 BR.markInvalid("Suppress IDC", CurLC);
838 static const MemRegion *getLocationRegionIfReference(const Expr *E,
839 const ExplodedNode *N) {
840 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
841 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
842 if (!VD->getType()->isReferenceType())
844 ProgramStateManager &StateMgr = N->getState()->getStateManager();
845 MemRegionManager &MRMgr = StateMgr.getRegionManager();
846 return MRMgr.getVarRegion(VD, N->getLocationContext());
850 // FIXME: This does not handle other kinds of null references,
851 // for example, references from FieldRegions:
852 // struct Wrapper { int &ref; };
853 // Wrapper w = { *(int *)0 };
859 static const Expr *peelOffOuterExpr(const Expr *Ex,
860 const ExplodedNode *N) {
861 Ex = Ex->IgnoreParenCasts();
862 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
863 return peelOffOuterExpr(EWC->getSubExpr(), N);
864 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
865 return peelOffOuterExpr(OVE->getSourceExpr(), N);
867 // Peel off the ternary operator.
868 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
869 // Find a node where the branching occurred and find out which branch
870 // we took (true/false) by looking at the ExplodedGraph.
871 const ExplodedNode *NI = N;
873 ProgramPoint ProgPoint = NI->getLocation();
874 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
875 const CFGBlock *srcBlk = BE->getSrc();
876 if (const Stmt *term = srcBlk->getTerminator()) {
878 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
880 return peelOffOuterExpr(CO->getTrueExpr(), N);
882 return peelOffOuterExpr(CO->getFalseExpr(), N);
886 NI = NI->getFirstPred();
892 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
894 BugReport &report, bool IsArg,
895 bool EnableNullFPSuppression) {
899 if (const Expr *Ex = dyn_cast<Expr>(S)) {
900 Ex = Ex->IgnoreParenCasts();
901 const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
906 const Expr *Inner = nullptr;
907 if (const Expr *Ex = dyn_cast<Expr>(S)) {
908 Ex = Ex->IgnoreParenCasts();
909 if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
913 if (IsArg && !Inner) {
914 assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
916 // Walk through nodes until we get one that matches the statement exactly.
917 // Alternately, if we hit a known lvalue for the statement, we know we've
918 // gone too far (though we can likely track the lvalue better anyway).
920 const ProgramPoint &pp = N->getLocation();
921 if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
922 if (ps->getStmt() == S || ps->getStmt() == Inner)
924 } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
925 if (CEE->getCalleeContext()->getCallSite() == S ||
926 CEE->getCalleeContext()->getCallSite() == Inner)
929 N = N->getFirstPred();
936 ProgramStateRef state = N->getState();
938 // The message send could be nil due to the receiver being nil.
939 // At this point in the path, the receiver should be live since we are at the
940 // message send expr. If it is nil, start tracking it.
941 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
942 trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
945 // See if the expression we're interested refers to a variable.
946 // If so, we can track both its contents and constraints on its value.
947 if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
948 const MemRegion *R = nullptr;
950 // Find the ExplodedNode where the lvalue (the value of 'Ex')
951 // was computed. We need this for getting the location value.
952 const ExplodedNode *LVNode = N;
954 if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
955 if (P->getStmt() == Inner)
958 LVNode = LVNode->getFirstPred();
960 assert(LVNode && "Unable to find the lvalue node.");
961 ProgramStateRef LVState = LVNode->getState();
962 SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
964 if (LVState->isNull(LVal).isConstrainedTrue()) {
965 // In case of C++ references, we want to differentiate between a null
966 // reference and reference to null pointer.
967 // If the LVal is null, check if we are dealing with null reference.
968 // For those, we want to track the location of the reference.
969 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
972 R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
974 // If this is a C++ reference to a null pointer, we are tracking the
975 // pointer. In additon, we should find the store at which the reference
977 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
978 if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
979 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
980 *KV, RR, EnableNullFPSuppression));
985 // Mark both the variable region and its contents as interesting.
986 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
988 report.markInteresting(R);
989 report.markInteresting(V);
990 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
992 // If the contents are symbolic, find out when they became null.
993 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
994 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
995 V.castAs<DefinedSVal>(), false));
997 // Add visitor, which will suppress inline defensive checks.
998 if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
999 if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1000 EnableNullFPSuppression) {
1002 llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1007 if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1008 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1009 *KV, R, 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(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1042 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1043 report.markInteresting(RegionRVal);
1044 report.addVisitor(llvm::make_unique<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)) {
1084 ME->getSelector().print(OS);
1085 OS << "' not called";
1088 OS << "No method is called";
1090 OS << " because the receiver is nil";
1092 // The receiver was nil, and hence the method was skipped.
1093 // Register a BugReporterVisitor to issue a message telling us how
1094 // the receiver was null.
1095 bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1096 /*EnableNullFPSuppression*/ false);
1097 // Issue a message saying that the method was skipped.
1098 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1099 N->getLocationContext());
1100 return new PathDiagnosticEventPiece(L, OS.str());
1103 // Registers every VarDecl inside a Stmt with a last store visitor.
1104 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1106 bool EnableNullFPSuppression) {
1107 const ExplodedNode *N = BR.getErrorNode();
1108 std::deque<const Stmt *> WorkList;
1109 WorkList.push_back(S);
1111 while (!WorkList.empty()) {
1112 const Stmt *Head = WorkList.front();
1113 WorkList.pop_front();
1115 ProgramStateRef state = N->getState();
1116 ProgramStateManager &StateMgr = state->getStateManager();
1118 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1119 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1120 const VarRegion *R =
1121 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1123 // What did we load?
1124 SVal V = state->getSVal(S, N->getLocationContext());
1126 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1127 // Register a new visitor with the BugReport.
1128 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1129 V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1134 for (Stmt::const_child_iterator I = Head->child_begin();
1135 I != Head->child_end(); ++I)
1136 WorkList.push_back(*I);
1140 //===----------------------------------------------------------------------===//
1141 // Visitor that tries to report interesting diagnostics from conditions.
1142 //===----------------------------------------------------------------------===//
1144 /// Return the tag associated with this visitor. This tag will be used
1145 /// to make all PathDiagnosticPieces created by this visitor.
1146 const char *ConditionBRVisitor::getTag() {
1147 return "ConditionBRVisitor";
1150 PathDiagnosticPiece *ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1151 const ExplodedNode *Prev,
1152 BugReporterContext &BRC,
1154 PathDiagnosticPiece *piece = VisitNodeImpl(N, Prev, BRC, BR);
1156 piece->setTag(getTag());
1157 if (PathDiagnosticEventPiece *ev=dyn_cast<PathDiagnosticEventPiece>(piece))
1158 ev->setPrunable(true, /* override */ false);
1163 PathDiagnosticPiece *ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1164 const ExplodedNode *Prev,
1165 BugReporterContext &BRC,
1168 ProgramPoint progPoint = N->getLocation();
1169 ProgramStateRef CurrentState = N->getState();
1170 ProgramStateRef PrevState = Prev->getState();
1172 // Compare the GDMs of the state, because that is where constraints
1173 // are managed. Note that ensure that we only look at nodes that
1174 // were generated by the analyzer engine proper, not checkers.
1175 if (CurrentState->getGDM().getRoot() ==
1176 PrevState->getGDM().getRoot())
1179 // If an assumption was made on a branch, it should be caught
1180 // here by looking at the state transition.
1181 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1182 const CFGBlock *srcBlk = BE->getSrc();
1183 if (const Stmt *term = srcBlk->getTerminator())
1184 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1188 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1189 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1191 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1192 cast<GRBugReporter>(BRC.getBugReporter()).
1193 getEngine().geteagerlyAssumeBinOpBifurcationTags();
1195 const ProgramPointTag *tag = PS->getTag();
1196 if (tag == tags.first)
1197 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1199 if (tag == tags.second)
1200 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1209 PathDiagnosticPiece *
1210 ConditionBRVisitor::VisitTerminator(const Stmt *Term,
1211 const ExplodedNode *N,
1212 const CFGBlock *srcBlk,
1213 const CFGBlock *dstBlk,
1215 BugReporterContext &BRC) {
1216 const Expr *Cond = nullptr;
1218 switch (Term->getStmtClass()) {
1221 case Stmt::IfStmtClass:
1222 Cond = cast<IfStmt>(Term)->getCond();
1224 case Stmt::ConditionalOperatorClass:
1225 Cond = cast<ConditionalOperator>(Term)->getCond();
1230 assert(srcBlk->succ_size() == 2);
1231 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1232 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1235 PathDiagnosticPiece *
1236 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1238 BugReporterContext &BRC,
1240 const ExplodedNode *N) {
1242 const Expr *Ex = Cond;
1245 Ex = Ex->IgnoreParenCasts();
1246 switch (Ex->getStmtClass()) {
1249 case Stmt::BinaryOperatorClass:
1250 return VisitTrueTest(Cond, cast<BinaryOperator>(Ex), tookTrue, BRC,
1252 case Stmt::DeclRefExprClass:
1253 return VisitTrueTest(Cond, cast<DeclRefExpr>(Ex), tookTrue, BRC,
1255 case Stmt::UnaryOperatorClass: {
1256 const UnaryOperator *UO = cast<UnaryOperator>(Ex);
1257 if (UO->getOpcode() == UO_LNot) {
1258 tookTrue = !tookTrue;
1259 Ex = UO->getSubExpr();
1268 bool ConditionBRVisitor::patternMatch(const Expr *Ex, raw_ostream &Out,
1269 BugReporterContext &BRC,
1271 const ExplodedNode *N,
1272 Optional<bool> &prunable) {
1273 const Expr *OriginalExpr = Ex;
1274 Ex = Ex->IgnoreParenCasts();
1276 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1277 const bool quotes = isa<VarDecl>(DR->getDecl());
1280 const LocationContext *LCtx = N->getLocationContext();
1281 const ProgramState *state = N->getState().get();
1282 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1283 LCtx).getAsRegion()) {
1284 if (report.isInteresting(R))
1287 const ProgramState *state = N->getState().get();
1288 SVal V = state->getSVal(R);
1289 if (report.isInteresting(V))
1294 Out << DR->getDecl()->getDeclName().getAsString();
1300 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1301 QualType OriginalTy = OriginalExpr->getType();
1302 if (OriginalTy->isPointerType()) {
1303 if (IL->getValue() == 0) {
1308 else if (OriginalTy->isObjCObjectPointerType()) {
1309 if (IL->getValue() == 0) {
1315 Out << IL->getValue();
1322 PathDiagnosticPiece *
1323 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1324 const BinaryOperator *BExpr,
1325 const bool tookTrue,
1326 BugReporterContext &BRC,
1328 const ExplodedNode *N) {
1330 bool shouldInvert = false;
1331 Optional<bool> shouldPrune;
1333 SmallString<128> LhsString, RhsString;
1335 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1336 const bool isVarLHS = patternMatch(BExpr->getLHS(), OutLHS, BRC, R, N,
1338 const bool isVarRHS = patternMatch(BExpr->getRHS(), OutRHS, BRC, R, N,
1341 shouldInvert = !isVarLHS && isVarRHS;
1344 BinaryOperator::Opcode Op = BExpr->getOpcode();
1346 if (BinaryOperator::isAssignmentOp(Op)) {
1347 // For assignment operators, all that we care about is that the LHS
1348 // evaluates to "true" or "false".
1349 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1353 // For non-assignment operations, we require that we can understand
1354 // both the LHS and RHS.
1355 if (LhsString.empty() || RhsString.empty() ||
1356 !BinaryOperator::isComparisonOp(Op))
1359 // Should we invert the strings if the LHS is not a variable name?
1360 SmallString<256> buf;
1361 llvm::raw_svector_ostream Out(buf);
1362 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1364 // Do we need to invert the opcode?
1368 case BO_LT: Op = BO_GT; break;
1369 case BO_GT: Op = BO_LT; break;
1370 case BO_LE: Op = BO_GE; break;
1371 case BO_GE: Op = BO_LE; break;
1376 case BO_EQ: Op = BO_NE; break;
1377 case BO_NE: Op = BO_EQ; break;
1378 case BO_LT: Op = BO_GE; break;
1379 case BO_GT: Op = BO_LE; break;
1380 case BO_LE: Op = BO_GT; break;
1381 case BO_GE: Op = BO_LT; break;
1391 Out << "not equal to ";
1394 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1398 Out << (shouldInvert ? LhsString : RhsString);
1399 const LocationContext *LCtx = N->getLocationContext();
1400 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1401 PathDiagnosticEventPiece *event =
1402 new PathDiagnosticEventPiece(Loc, Out.str());
1403 if (shouldPrune.hasValue())
1404 event->setPrunable(shouldPrune.getValue());
1408 PathDiagnosticPiece *
1409 ConditionBRVisitor::VisitConditionVariable(StringRef LhsString,
1410 const Expr *CondVarExpr,
1411 const bool tookTrue,
1412 BugReporterContext &BRC,
1414 const ExplodedNode *N) {
1415 // FIXME: If there's already a constraint tracker for this variable,
1416 // we shouldn't emit anything here (c.f. the double note in
1417 // test/Analysis/inlining/path-notes.c)
1418 SmallString<256> buf;
1419 llvm::raw_svector_ostream Out(buf);
1420 Out << "Assuming " << LhsString << " is ";
1422 QualType Ty = CondVarExpr->getType();
1424 if (Ty->isPointerType())
1425 Out << (tookTrue ? "not null" : "null");
1426 else if (Ty->isObjCObjectPointerType())
1427 Out << (tookTrue ? "not nil" : "nil");
1428 else if (Ty->isBooleanType())
1429 Out << (tookTrue ? "true" : "false");
1430 else if (Ty->isIntegralOrEnumerationType())
1431 Out << (tookTrue ? "non-zero" : "zero");
1435 const LocationContext *LCtx = N->getLocationContext();
1436 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1437 PathDiagnosticEventPiece *event =
1438 new PathDiagnosticEventPiece(Loc, Out.str());
1440 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1441 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1442 const ProgramState *state = N->getState().get();
1443 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1444 if (report.isInteresting(R))
1445 event->setPrunable(false);
1453 PathDiagnosticPiece *
1454 ConditionBRVisitor::VisitTrueTest(const Expr *Cond,
1455 const DeclRefExpr *DR,
1456 const bool tookTrue,
1457 BugReporterContext &BRC,
1459 const ExplodedNode *N) {
1461 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1465 SmallString<256> Buf;
1466 llvm::raw_svector_ostream Out(Buf);
1468 Out << "Assuming '" << VD->getDeclName() << "' is ";
1470 QualType VDTy = VD->getType();
1472 if (VDTy->isPointerType())
1473 Out << (tookTrue ? "non-null" : "null");
1474 else if (VDTy->isObjCObjectPointerType())
1475 Out << (tookTrue ? "non-nil" : "nil");
1476 else if (VDTy->isScalarType())
1477 Out << (tookTrue ? "not equal to 0" : "0");
1481 const LocationContext *LCtx = N->getLocationContext();
1482 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1483 PathDiagnosticEventPiece *event =
1484 new PathDiagnosticEventPiece(Loc, Out.str());
1486 const ProgramState *state = N->getState().get();
1487 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1488 if (report.isInteresting(R))
1489 event->setPrunable(false);
1491 SVal V = state->getSVal(R);
1492 if (report.isInteresting(V))
1493 event->setPrunable(false);
1500 // FIXME: Copied from ExprEngineCallAndReturn.cpp.
1501 static bool isInStdNamespace(const Decl *D) {
1502 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
1503 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
1507 while (const NamespaceDecl *Parent = dyn_cast<NamespaceDecl>(ND->getParent()))
1510 return ND->isStdNamespace();
1513 std::unique_ptr<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.
1519 ExprEngine &Eng = BRC.getBugReporter().getEngine();
1520 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1521 const Decl *D = N->getLocationContext()->getDecl();
1523 if (isInStdNamespace(D)) {
1524 // Skip reports within the 'std' namespace. Although these can sometimes be
1525 // the user's fault, we currently don't report them very well, and
1526 // Note that this will not help for any other data structure libraries, like
1527 // TR1, Boost, or llvm/ADT.
1528 if (Options.shouldSuppressFromCXXStandardLibrary()) {
1529 BR.markInvalid(getTag(), nullptr);
1533 // If the the complete 'std' suppression is not enabled, suppress reports
1534 // from the 'std' namespace that are known to produce false positives.
1536 // The analyzer issues a false use-after-free when std::list::pop_front
1537 // or std::list::pop_back are called multiple times because we cannot
1538 // reason about the internal invariants of the datastructure.
1539 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1540 const CXXRecordDecl *CD = MD->getParent();
1541 if (CD->getName() == "list") {
1542 BR.markInvalid(getTag(), nullptr);
1547 // The analyzer issues a false positive on
1548 // std::basic_string<uint8_t> v; v.push_back(1);
1550 // std::u16string s; s += u'a';
1551 // because we cannot reason about the internal invariants of the
1553 for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
1554 LCtx = LCtx->getParent()) {
1555 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
1559 const CXXRecordDecl *CD = MD->getParent();
1560 if (CD->getName() == "basic_string") {
1561 BR.markInvalid(getTag(), nullptr);
1568 // Skip reports within the sys/queue.h macros as we do not have the ability to
1569 // reason about data structure shapes.
1570 SourceManager &SM = BRC.getSourceManager();
1571 FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1572 while (Loc.isMacroID()) {
1573 Loc = Loc.getSpellingLoc();
1574 if (SM.getFilename(Loc).endswith("sys/queue.h")) {
1575 BR.markInvalid(getTag(), nullptr);
1583 PathDiagnosticPiece *
1584 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1585 const ExplodedNode *PrevN,
1586 BugReporterContext &BRC,
1589 ProgramStateRef State = N->getState();
1590 ProgramPoint ProgLoc = N->getLocation();
1592 // We are only interested in visiting CallEnter nodes.
1593 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1597 // Check if one of the arguments is the region the visitor is tracking.
1598 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1599 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1601 ArrayRef<ParmVarDecl*> parms = Call->parameters();
1603 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1604 I != E; ++I, ++Idx) {
1605 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1607 // Are we tracking the argument or its subregion?
1608 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1611 // Check the function parameter type.
1612 const ParmVarDecl *ParamDecl = *I;
1613 assert(ParamDecl && "Formal parameter has no decl?");
1614 QualType T = ParamDecl->getType();
1616 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1617 // Function can only change the value passed in by address.
1621 // If it is a const pointer value, the function does not intend to
1622 // change the value.
1623 if (T->getPointeeType().isConstQualified())
1626 // Mark the call site (LocationContext) as interesting if the value of the
1627 // argument is undefined or '0'/'NULL'.
1628 SVal BoundVal = State->getSVal(R);
1629 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1630 BR.markInteresting(CEnter->getCalleeContext());