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/Analysis/CFGStmtMap.h"
18 #include "clang/Lex/Lexer.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
32 using llvm::FoldingSetNodeID;
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 bool bugreporter::isDeclRefExprToReference(const Expr *E) {
39 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
40 return DRE->getDecl()->getType()->isReferenceType();
45 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
46 // Pattern match for a few useful cases:
48 const Expr *E = dyn_cast<Expr>(S);
51 E = E->IgnoreParenCasts();
54 if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
55 assert(B->isAssignmentOp());
56 E = B->getLHS()->IgnoreParenCasts();
59 else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
60 if (U->getOpcode() == UO_Deref)
61 return U->getSubExpr()->IgnoreParenCasts();
63 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
64 if (ME->isImplicitAccess()) {
66 } else if (ME->isArrow() || isDeclRefExprToReference(ME->getBase())) {
67 return ME->getBase()->IgnoreParenCasts();
69 // If we have a member expr with a dot, the base must have been
71 return getDerefExpr(ME->getBase());
74 else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
75 return IvarRef->getBase()->IgnoreParenCasts();
77 else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
78 return getDerefExpr(AE->getBase());
80 else if (isa<DeclRefExpr>(E)) {
89 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
90 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
91 if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
96 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
97 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
98 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
99 return RS->getRetValue();
103 //===----------------------------------------------------------------------===//
104 // Definitions for bug reporter visitors.
105 //===----------------------------------------------------------------------===//
107 std::unique_ptr<PathDiagnosticPiece>
108 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
109 const ExplodedNode *EndPathNode, BugReport &BR) {
113 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
114 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
115 PathDiagnosticLocation L =
116 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
118 const auto &Ranges = BR.getRanges();
120 // Only add the statement itself as a range if we didn't specify any
121 // special ranges for this report.
122 auto P = llvm::make_unique<PathDiagnosticEventPiece>(
123 L, BR.getDescription(), Ranges.begin() == Ranges.end());
124 for (SourceRange Range : Ranges)
132 /// Emits an extra note at the return statement of an interesting stack frame.
134 /// The returned value is marked as an interesting value, and if it's null,
135 /// adds a visitor to track where it became null.
137 /// This visitor is intended to be used when another visitor discovers that an
138 /// interesting value comes from an inlined function call.
139 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
140 const StackFrameContext *StackFrame;
147 bool EnableNullFPSuppression;
150 ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
151 : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
153 static void *getTag() {
155 return static_cast<void *>(&Tag);
158 void Profile(llvm::FoldingSetNodeID &ID) const override {
159 ID.AddPointer(ReturnVisitor::getTag());
160 ID.AddPointer(StackFrame);
161 ID.AddBoolean(EnableNullFPSuppression);
164 /// Adds a ReturnVisitor if the given statement represents a call that was
167 /// This will search back through the ExplodedGraph, starting from the given
168 /// node, looking for when the given statement was processed. If it turns out
169 /// the statement is a call that was inlined, we add the visitor to the
170 /// bug report, so it can print a note later.
171 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
173 bool InEnableNullFPSuppression) {
174 if (!CallEvent::isCallStmt(S))
177 // First, find when we processed the statement.
179 if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
180 if (CEE->getCalleeContext()->getCallSite() == S)
182 if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
183 if (SP->getStmt() == S)
186 Node = Node->getFirstPred();
189 // Next, step over any post-statement checks.
190 while (Node && Node->getLocation().getAs<PostStmt>())
191 Node = Node->getFirstPred();
195 // Finally, see if we inlined the call.
196 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
200 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
201 if (CalleeContext->getCallSite() != S)
204 // Check the return value.
205 ProgramStateRef State = Node->getState();
206 SVal RetVal = State->getSVal(S, Node->getLocationContext());
208 // Handle cases where a reference is returned and then immediately used.
209 if (cast<Expr>(S)->isGLValue())
210 if (Optional<Loc> LValue = RetVal.getAs<Loc>())
211 RetVal = State->getSVal(*LValue);
213 // See if the return value is NULL. If so, suppress the report.
214 SubEngine *Eng = State->getStateManager().getOwningEngine();
215 assert(Eng && "Cannot file a bug report without an owning engine");
216 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
218 bool EnableNullFPSuppression = false;
219 if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
220 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
221 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
223 BR.markInteresting(CalleeContext);
224 BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
225 EnableNullFPSuppression));
228 /// Returns true if any counter-suppression heuristics are enabled for
230 static bool hasCounterSuppression(AnalyzerOptions &Options) {
231 return Options.shouldAvoidSuppressingNullArgumentPaths();
234 std::shared_ptr<PathDiagnosticPiece>
235 visitNodeInitial(const ExplodedNode *N, const ExplodedNode *PrevN,
236 BugReporterContext &BRC, BugReport &BR) {
237 // Only print a message at the interesting return statement.
238 if (N->getLocationContext() != StackFrame)
241 Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
245 const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
249 // Okay, we're at the right return statement, but do we have the return
251 ProgramStateRef State = N->getState();
252 SVal V = State->getSVal(Ret, StackFrame);
253 if (V.isUnknownOrUndef())
256 // Don't print any more notes after this one.
259 const Expr *RetE = Ret->getRetValue();
260 assert(RetE && "Tracking a return value for a void function");
262 // Handle cases where a reference is returned and then immediately used.
263 Optional<Loc> LValue;
264 if (RetE->isGLValue()) {
265 if ((LValue = V.getAs<Loc>())) {
266 SVal RValue = State->getRawSVal(*LValue, RetE->getType());
267 if (RValue.getAs<DefinedSVal>())
272 // Ignore aggregate rvalues.
273 if (V.getAs<nonloc::LazyCompoundVal>() ||
274 V.getAs<nonloc::CompoundVal>())
277 RetE = RetE->IgnoreParenCasts();
279 // If we can't prove the return value is 0, just mark it interesting, and
280 // make sure to track it into any further inner functions.
281 if (!State->isNull(V).isConstrainedTrue()) {
282 BR.markInteresting(V);
283 ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
284 EnableNullFPSuppression);
288 // If we're returning 0, we should track where that 0 came from.
289 bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
290 EnableNullFPSuppression);
292 // Build an appropriate message based on the return value.
294 llvm::raw_svector_ostream Out(Msg);
296 if (V.getAs<Loc>()) {
297 // If we have counter-suppression enabled, make sure we keep visiting
298 // future nodes. We want to emit a path note as well, in case
299 // the report is resurrected as valid later on.
300 ExprEngine &Eng = BRC.getBugReporter().getEngine();
301 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
302 if (EnableNullFPSuppression && hasCounterSuppression(Options))
303 Mode = MaybeUnsuppress;
305 if (RetE->getType()->isObjCObjectPointerType())
306 Out << "Returning nil";
308 Out << "Returning null pointer";
310 Out << "Returning zero";
314 if (const MemRegion *MR = LValue->getAsRegion()) {
315 if (MR->canPrintPretty()) {
316 Out << " (reference to ";
317 MR->printPretty(Out);
322 // FIXME: We should have a more generalized location printing mechanism.
323 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
324 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
325 Out << " (loaded from '" << *DD << "')";
328 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
329 if (!L.isValid() || !L.asLocation().isValid())
332 return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
335 std::shared_ptr<PathDiagnosticPiece>
336 visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
337 BugReporterContext &BRC, BugReport &BR) {
339 ExprEngine &Eng = BRC.getBugReporter().getEngine();
340 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
341 assert(hasCounterSuppression(Options));
344 // Are we at the entry node for this call?
345 Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
349 if (CE->getCalleeContext() != StackFrame)
354 // Don't automatically suppress a report if one of the arguments is
355 // known to be a null pointer. Instead, start tracking /that/ null
356 // value back to its origin.
357 ProgramStateManager &StateMgr = BRC.getStateManager();
358 CallEventManager &CallMgr = StateMgr.getCallEventManager();
360 ProgramStateRef State = N->getState();
361 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
362 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
363 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
367 const Expr *ArgE = Call->getArgExpr(I);
371 // Is it possible for this argument to be non-null?
372 if (!State->isNull(*ArgV).isConstrainedTrue())
375 if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
376 EnableNullFPSuppression))
377 BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
379 // If we /can't/ track the null pointer, we should err on the side of
380 // false negatives, and continue towards marking this report invalid.
381 // (We will still look at the other arguments, though.)
387 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
388 const ExplodedNode *PrevN,
389 BugReporterContext &BRC,
390 BugReport &BR) override {
393 return visitNodeInitial(N, PrevN, BRC, BR);
394 case MaybeUnsuppress:
395 return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
400 llvm_unreachable("Invalid visit mode!");
403 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
404 const ExplodedNode *N,
405 BugReport &BR) override {
406 if (EnableNullFPSuppression)
407 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
411 } // end anonymous namespace
414 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
419 ID.AddBoolean(EnableNullFPSuppression);
422 /// Returns true if \p N represents the DeclStmt declaring and initializing
424 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
425 Optional<PostStmt> P = N->getLocationAs<PostStmt>();
429 const DeclStmt *DS = P->getStmtAs<DeclStmt>();
433 if (DS->getSingleDecl() != VR->getDecl())
436 const MemSpaceRegion *VarSpace = VR->getMemorySpace();
437 const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
439 // If we ever directly evaluate global DeclStmts, this assertion will be
440 // invalid, but this still seems preferable to silently accepting an
441 // initialization that may be for a path-sensitive variable.
442 assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
446 assert(VR->getDecl()->hasLocalStorage());
447 const LocationContext *LCtx = N->getLocationContext();
448 return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
451 std::shared_ptr<PathDiagnosticPiece>
452 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
453 const ExplodedNode *Pred,
454 BugReporterContext &BRC, BugReport &BR) {
459 const ExplodedNode *StoreSite = nullptr;
460 const Expr *InitE = nullptr;
461 bool IsParam = false;
463 // First see if we reached the declaration of the region.
464 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
465 if (isInitializationOfVar(Pred, VR)) {
467 InitE = VR->getDecl()->getInit();
471 // If this is a post initializer expression, initializing the region, we
472 // should track the initializer expression.
473 if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
474 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
475 if (FieldReg && FieldReg == R) {
477 InitE = PIP->getInitializer()->getInit();
481 // Otherwise, see if this is the store site:
482 // (1) Succ has this binding and Pred does not, i.e. this is
483 // where the binding first occurred.
484 // (2) Succ has this binding and is a PostStore node for this region, i.e.
485 // the same binding was re-assigned here.
487 if (Succ->getState()->getSVal(R) != V)
490 if (Pred->getState()->getSVal(R) == V) {
491 Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
492 if (!PS || PS->getLocationValue() != R)
498 // If this is an assignment expression, we can track the value
500 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
501 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
502 if (BO->isAssignmentOp())
503 InitE = BO->getRHS();
505 // If this is a call entry, the variable should be a parameter.
506 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
507 // 'this' should never be NULL, but this visitor isn't just for NULL and
509 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
510 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
511 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
513 ProgramStateManager &StateMgr = BRC.getStateManager();
514 CallEventManager &CallMgr = StateMgr.getCallEventManager();
516 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
518 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
523 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
524 // is wrapped inside of it.
525 if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
526 InitE = TmpR->getExpr();
533 // If we have an expression that provided the value, try to track where it
537 V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
539 InitE = InitE->IgnoreParenCasts();
540 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
541 EnableNullFPSuppression);
543 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
544 BR, EnableNullFPSuppression);
548 // Okay, we've found the binding. Emit an appropriate message.
549 SmallString<256> sbuf;
550 llvm::raw_svector_ostream os(sbuf);
552 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
553 const Stmt *S = PS->getStmt();
554 const char *action = nullptr;
555 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
556 const VarRegion *VR = dyn_cast<VarRegion>(R);
559 action = R->canPrintPretty() ? "initialized to " :
561 } else if (isa<BlockExpr>(S)) {
562 action = R->canPrintPretty() ? "captured by block as " :
563 "Captured by block as ";
565 // See if we can get the BlockVarRegion.
566 ProgramStateRef State = StoreSite->getState();
567 SVal V = State->getSVal(S, PS->getLocationContext());
568 if (const BlockDataRegion *BDR =
569 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
570 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
571 if (Optional<KnownSVal> KV =
572 State->getSVal(OriginalR).getAs<KnownSVal>())
573 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
574 *KV, OriginalR, EnableNullFPSuppression));
581 if (R->canPrintPretty()) {
586 if (V.getAs<loc::ConcreteInt>()) {
588 if (R->isBoundable()) {
589 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
590 if (TR->getValueType()->isObjCObjectPointerType()) {
591 os << action << "nil";
598 os << action << "a null pointer value";
599 } else if (Optional<nonloc::ConcreteInt> CVal =
600 V.getAs<nonloc::ConcreteInt>()) {
601 os << action << CVal->getValue();
605 if (isa<VarRegion>(R)) {
606 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
608 os << (R->canPrintPretty() ? "initialized" : "Initializing")
609 << " to a garbage value";
611 os << (R->canPrintPretty() ? "declared" : "Declaring")
612 << " without an initial value";
617 os << (R->canPrintPretty() ? "initialized" : "Initialized")
622 } else if (StoreSite->getLocation().getAs<CallEnter>()) {
623 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
624 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
628 if (V.getAs<loc::ConcreteInt>()) {
629 if (Param->getType()->isObjCObjectPointerType())
630 os << "nil object reference";
632 os << "null pointer value";
633 } else if (V.isUndef()) {
634 os << "uninitialized value";
635 } else if (Optional<nonloc::ConcreteInt> CI =
636 V.getAs<nonloc::ConcreteInt>()) {
637 os << "the value " << CI->getValue();
642 // Printed parameter indexes are 1-based, not 0-based.
643 unsigned Idx = Param->getFunctionScopeIndex() + 1;
644 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
645 if (R->canPrintPretty()) {
652 if (os.str().empty()) {
653 if (V.getAs<loc::ConcreteInt>()) {
655 if (R->isBoundable()) {
656 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
657 if (TR->getValueType()->isObjCObjectPointerType()) {
658 os << "nil object reference stored";
664 if (R->canPrintPretty())
665 os << "Null pointer value stored";
667 os << "Storing null pointer value";
670 } else if (V.isUndef()) {
671 if (R->canPrintPretty())
672 os << "Uninitialized value stored";
674 os << "Storing uninitialized value";
676 } else if (Optional<nonloc::ConcreteInt> CV =
677 V.getAs<nonloc::ConcreteInt>()) {
678 if (R->canPrintPretty())
679 os << "The value " << CV->getValue() << " is assigned";
681 os << "Assigning " << CV->getValue();
684 if (R->canPrintPretty())
685 os << "Value assigned";
687 os << "Assigning value";
690 if (R->canPrintPretty()) {
696 // Construct a new PathDiagnosticPiece.
697 ProgramPoint P = StoreSite->getLocation();
698 PathDiagnosticLocation L;
699 if (P.getAs<CallEnter>() && InitE)
700 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
701 P.getLocationContext());
703 if (!L.isValid() || !L.asLocation().isValid())
704 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
706 if (!L.isValid() || !L.asLocation().isValid())
709 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
712 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
715 ID.AddBoolean(Assumption);
719 /// Return the tag associated with this visitor. This tag will be used
720 /// to make all PathDiagnosticPieces created by this visitor.
721 const char *TrackConstraintBRVisitor::getTag() {
722 return "TrackConstraintBRVisitor";
725 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
727 return N->getState()->isNull(Constraint).isUnderconstrained();
728 return (bool)N->getState()->assume(Constraint, !Assumption);
731 std::shared_ptr<PathDiagnosticPiece>
732 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
733 const ExplodedNode *PrevN,
734 BugReporterContext &BRC, BugReport &BR) {
738 // Start tracking after we see the first state in which the value is
740 if (!IsTrackingTurnedOn)
741 if (!isUnderconstrained(N))
742 IsTrackingTurnedOn = true;
743 if (!IsTrackingTurnedOn)
746 // Check if in the previous state it was feasible for this constraint
748 if (isUnderconstrained(PrevN)) {
752 // As a sanity check, make sure that the negation of the constraint
753 // was infeasible in the current state. If it is feasible, we somehow
754 // missed the transition point.
755 assert(!isUnderconstrained(N));
757 // We found the transition point for the constraint. We now need to
758 // pretty-print the constraint. (work-in-progress)
759 SmallString<64> sbuf;
760 llvm::raw_svector_ostream os(sbuf);
762 if (Constraint.getAs<Loc>()) {
763 os << "Assuming pointer value is ";
764 os << (Assumption ? "non-null" : "null");
767 if (os.str().empty())
770 // Construct a new PathDiagnosticPiece.
771 ProgramPoint P = N->getLocation();
772 PathDiagnosticLocation L =
773 PathDiagnosticLocation::create(P, BRC.getSourceManager());
777 auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
785 SuppressInlineDefensiveChecksVisitor::
786 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
787 : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
789 // Check if the visitor is disabled.
790 SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
791 assert(Eng && "Cannot file a bug report without an owning engine");
792 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
793 if (!Options.shouldSuppressInlinedDefensiveChecks())
796 assert(N->getState()->isNull(V).isConstrainedTrue() &&
797 "The visitor only tracks the cases where V is constrained to 0");
800 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
806 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
810 std::shared_ptr<PathDiagnosticPiece>
811 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
812 const ExplodedNode *Pred,
813 BugReporterContext &BRC,
818 // Start tracking after we see the first state in which the value is null.
819 if (!IsTrackingTurnedOn)
820 if (Succ->getState()->isNull(V).isConstrainedTrue())
821 IsTrackingTurnedOn = true;
822 if (!IsTrackingTurnedOn)
825 // Check if in the previous state it was feasible for this value
827 if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
830 assert(Succ->getState()->isNull(V).isConstrainedTrue());
832 // Check if this is inlined defensive checks.
833 const LocationContext *CurLC =Succ->getLocationContext();
834 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
835 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
836 BR.markInvalid("Suppress IDC", CurLC);
840 // Treat defensive checks in function-like macros as if they were an inlined
841 // defensive check. If the bug location is not in a macro and the
842 // terminator for the current location is in a macro then suppress the
844 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
849 SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
850 if (BugLoc.isMacroID())
853 ProgramPoint CurPoint = Succ->getLocation();
854 const Stmt *CurTerminatorStmt = nullptr;
855 if (auto BE = CurPoint.getAs<BlockEdge>()) {
856 CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
857 } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
858 const Stmt *CurStmt = SP->getStmt();
859 if (!CurStmt->getLocStart().isMacroID())
862 CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
863 CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
868 if (!CurTerminatorStmt)
871 SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
872 if (TerminatorLoc.isMacroID()) {
873 const SourceManager &SMgr = BRC.getSourceManager();
874 std::pair<FileID, unsigned> TLInfo = SMgr.getDecomposedLoc(TerminatorLoc);
875 SrcMgr::SLocEntry SE = SMgr.getSLocEntry(TLInfo.first);
876 const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
877 if (EInfo.isFunctionMacroExpansion()) {
878 BR.markInvalid("Suppress Macro IDC", CurLC);
886 static const MemRegion *getLocationRegionIfReference(const Expr *E,
887 const ExplodedNode *N) {
888 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
889 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
890 if (!VD->getType()->isReferenceType())
892 ProgramStateManager &StateMgr = N->getState()->getStateManager();
893 MemRegionManager &MRMgr = StateMgr.getRegionManager();
894 return MRMgr.getVarRegion(VD, N->getLocationContext());
898 // FIXME: This does not handle other kinds of null references,
899 // for example, references from FieldRegions:
900 // struct Wrapper { int &ref; };
901 // Wrapper w = { *(int *)0 };
907 static const Expr *peelOffOuterExpr(const Expr *Ex,
908 const ExplodedNode *N) {
909 Ex = Ex->IgnoreParenCasts();
910 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
911 return peelOffOuterExpr(EWC->getSubExpr(), N);
912 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
913 return peelOffOuterExpr(OVE->getSourceExpr(), N);
914 if (auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
915 auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
916 if (PropRef && PropRef->isMessagingGetter()) {
917 const Expr *GetterMessageSend =
918 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
919 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
920 return peelOffOuterExpr(GetterMessageSend, N);
924 // Peel off the ternary operator.
925 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
926 // Find a node where the branching occurred and find out which branch
927 // we took (true/false) by looking at the ExplodedGraph.
928 const ExplodedNode *NI = N;
930 ProgramPoint ProgPoint = NI->getLocation();
931 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
932 const CFGBlock *srcBlk = BE->getSrc();
933 if (const Stmt *term = srcBlk->getTerminator()) {
935 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
937 return peelOffOuterExpr(CO->getTrueExpr(), N);
939 return peelOffOuterExpr(CO->getFalseExpr(), N);
943 NI = NI->getFirstPred();
949 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
951 BugReport &report, bool IsArg,
952 bool EnableNullFPSuppression) {
956 if (const Expr *Ex = dyn_cast<Expr>(S)) {
957 Ex = Ex->IgnoreParenCasts();
958 const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
963 const Expr *Inner = nullptr;
964 if (const Expr *Ex = dyn_cast<Expr>(S)) {
965 Ex = Ex->IgnoreParenCasts();
967 // Performing operator `&' on an lvalue expression is essentially a no-op.
968 // Then, if we are taking addresses of fields or elements, these are also
969 // unlikely to matter.
970 // FIXME: There's a hack in our Store implementation that always computes
971 // field offsets around null pointers as if they are always equal to 0.
972 // The idea here is to report accesses to fields as null dereferences
973 // even though the pointer value that's being dereferenced is actually
974 // the offset of the field rather than exactly 0.
975 // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
976 // This code interacts heavily with this hack; otherwise the value
977 // would not be null at all for most fields, so we'd be unable to track it.
978 if (const auto *Op = dyn_cast<UnaryOperator>(Ex))
979 if (Op->getOpcode() == UO_AddrOf && Op->getSubExpr()->isLValue())
980 if (const Expr *DerefEx = getDerefExpr(Op->getSubExpr()))
983 if (Ex && (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex)))
987 if (IsArg && !Inner) {
988 assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
990 // Walk through nodes until we get one that matches the statement exactly.
991 // Alternately, if we hit a known lvalue for the statement, we know we've
992 // gone too far (though we can likely track the lvalue better anyway).
994 const ProgramPoint &pp = N->getLocation();
995 if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
996 if (ps->getStmt() == S || ps->getStmt() == Inner)
998 } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
999 if (CEE->getCalleeContext()->getCallSite() == S ||
1000 CEE->getCalleeContext()->getCallSite() == Inner)
1003 N = N->getFirstPred();
1010 ProgramStateRef state = N->getState();
1012 // The message send could be nil due to the receiver being nil.
1013 // At this point in the path, the receiver should be live since we are at the
1014 // message send expr. If it is nil, start tracking it.
1015 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
1016 trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
1019 // See if the expression we're interested refers to a variable.
1020 // If so, we can track both its contents and constraints on its value.
1021 if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
1022 const MemRegion *R = nullptr;
1024 // Find the ExplodedNode where the lvalue (the value of 'Ex')
1025 // was computed. We need this for getting the location value.
1026 const ExplodedNode *LVNode = N;
1028 if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
1029 if (P->getStmt() == Inner)
1032 LVNode = LVNode->getFirstPred();
1034 assert(LVNode && "Unable to find the lvalue node.");
1035 ProgramStateRef LVState = LVNode->getState();
1036 SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
1038 if (LVState->isNull(LVal).isConstrainedTrue()) {
1039 // In case of C++ references, we want to differentiate between a null
1040 // reference and reference to null pointer.
1041 // If the LVal is null, check if we are dealing with null reference.
1042 // For those, we want to track the location of the reference.
1043 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
1046 R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
1048 // If this is a C++ reference to a null pointer, we are tracking the
1049 // pointer. In addition, we should find the store at which the reference
1051 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
1052 if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
1053 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1054 *KV, RR, EnableNullFPSuppression));
1059 // Mark both the variable region and its contents as interesting.
1060 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1062 report.markInteresting(R);
1063 report.markInteresting(V);
1064 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1066 // If the contents are symbolic, find out when they became null.
1067 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1068 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1069 V.castAs<DefinedSVal>(), false));
1071 // Add visitor, which will suppress inline defensive checks.
1072 if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
1073 if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1074 EnableNullFPSuppression) {
1076 llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1081 if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1082 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1083 *KV, R, EnableNullFPSuppression));
1088 // If the expression is not an "lvalue expression", we can still
1089 // track the constraints on its contents.
1090 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1092 // If the value came from an inlined function call, we should at least make
1093 // sure that function isn't pruned in our output.
1094 if (const Expr *E = dyn_cast<Expr>(S))
1095 S = E->IgnoreParenCasts();
1097 ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1099 // Uncomment this to find cases where we aren't properly getting the
1100 // base value that was dereferenced.
1101 // assert(!V.isUnknownOrUndef());
1102 // Is it a symbolic value?
1103 if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
1104 // At this point we are dealing with the region's LValue.
1105 // However, if the rvalue is a symbolic region, we should track it as well.
1106 // Try to use the correct type when looking up the value.
1108 if (const Expr *E = dyn_cast<Expr>(S))
1109 RVal = state->getRawSVal(L.getValue(), E->getType());
1111 RVal = state->getSVal(L->getRegion());
1113 const MemRegion *RegionRVal = RVal.getAsRegion();
1114 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1116 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1117 report.markInteresting(RegionRVal);
1118 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1119 loc::MemRegionVal(RegionRVal), false));
1126 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1127 const ExplodedNode *N) {
1128 const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1131 if (const Expr *Receiver = ME->getInstanceReceiver()) {
1132 ProgramStateRef state = N->getState();
1133 SVal V = state->getSVal(Receiver, N->getLocationContext());
1134 if (state->isNull(V).isConstrainedTrue())
1140 std::shared_ptr<PathDiagnosticPiece>
1141 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1142 const ExplodedNode *PrevN,
1143 BugReporterContext &BRC, BugReport &BR) {
1144 Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1148 const Stmt *S = P->getStmt();
1149 const Expr *Receiver = getNilReceiver(S, N);
1153 llvm::SmallString<256> Buf;
1154 llvm::raw_svector_ostream OS(Buf);
1156 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1158 ME->getSelector().print(OS);
1159 OS << "' not called";
1162 OS << "No method is called";
1164 OS << " because the receiver is nil";
1166 // The receiver was nil, and hence the method was skipped.
1167 // Register a BugReporterVisitor to issue a message telling us how
1168 // the receiver was null.
1169 bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1170 /*EnableNullFPSuppression*/ false);
1171 // Issue a message saying that the method was skipped.
1172 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1173 N->getLocationContext());
1174 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1177 // Registers every VarDecl inside a Stmt with a last store visitor.
1178 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1180 bool EnableNullFPSuppression) {
1181 const ExplodedNode *N = BR.getErrorNode();
1182 std::deque<const Stmt *> WorkList;
1183 WorkList.push_back(S);
1185 while (!WorkList.empty()) {
1186 const Stmt *Head = WorkList.front();
1187 WorkList.pop_front();
1189 ProgramStateRef state = N->getState();
1190 ProgramStateManager &StateMgr = state->getStateManager();
1192 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1193 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1194 const VarRegion *R =
1195 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1197 // What did we load?
1198 SVal V = state->getSVal(S, N->getLocationContext());
1200 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1201 // Register a new visitor with the BugReport.
1202 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1203 V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1208 for (const Stmt *SubStmt : Head->children())
1209 WorkList.push_back(SubStmt);
1213 //===----------------------------------------------------------------------===//
1214 // Visitor that tries to report interesting diagnostics from conditions.
1215 //===----------------------------------------------------------------------===//
1217 /// Return the tag associated with this visitor. This tag will be used
1218 /// to make all PathDiagnosticPieces created by this visitor.
1219 const char *ConditionBRVisitor::getTag() {
1220 return "ConditionBRVisitor";
1223 std::shared_ptr<PathDiagnosticPiece>
1224 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
1225 BugReporterContext &BRC, BugReport &BR) {
1226 auto piece = VisitNodeImpl(N, Prev, BRC, BR);
1228 piece->setTag(getTag());
1229 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1230 ev->setPrunable(true, /* override */ false);
1235 std::shared_ptr<PathDiagnosticPiece>
1236 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1237 const ExplodedNode *Prev,
1238 BugReporterContext &BRC, BugReport &BR) {
1240 ProgramPoint progPoint = N->getLocation();
1241 ProgramStateRef CurrentState = N->getState();
1242 ProgramStateRef PrevState = Prev->getState();
1244 // Compare the GDMs of the state, because that is where constraints
1245 // are managed. Note that ensure that we only look at nodes that
1246 // were generated by the analyzer engine proper, not checkers.
1247 if (CurrentState->getGDM().getRoot() ==
1248 PrevState->getGDM().getRoot())
1251 // If an assumption was made on a branch, it should be caught
1252 // here by looking at the state transition.
1253 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1254 const CFGBlock *srcBlk = BE->getSrc();
1255 if (const Stmt *term = srcBlk->getTerminator())
1256 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1260 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1261 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1263 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1264 cast<GRBugReporter>(BRC.getBugReporter()).
1265 getEngine().geteagerlyAssumeBinOpBifurcationTags();
1267 const ProgramPointTag *tag = PS->getTag();
1268 if (tag == tags.first)
1269 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1271 if (tag == tags.second)
1272 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1281 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1282 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1283 const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1284 const Expr *Cond = nullptr;
1286 // In the code below, Term is a CFG terminator and Cond is a branch condition
1287 // expression upon which the decision is made on this terminator.
1289 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1290 // and "x == 0" is the respective condition.
1292 // Another example: in "if (x && y)", we've got two terminators and two
1293 // conditions due to short-circuit nature of operator "&&":
1294 // 1. The "if (x && y)" statement is a terminator,
1295 // and "y" is the respective condition.
1296 // 2. Also "x && ..." is another terminator,
1297 // and "x" is its condition.
1299 switch (Term->getStmtClass()) {
1300 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1301 // more tricky because there are more than two branches to account for.
1304 case Stmt::IfStmtClass:
1305 Cond = cast<IfStmt>(Term)->getCond();
1307 case Stmt::ConditionalOperatorClass:
1308 Cond = cast<ConditionalOperator>(Term)->getCond();
1310 case Stmt::BinaryOperatorClass:
1311 // When we encounter a logical operator (&& or ||) as a CFG terminator,
1312 // then the condition is actually its LHS; otherwise, we'd encounter
1313 // the parent, such as if-statement, as a terminator.
1314 const auto *BO = cast<BinaryOperator>(Term);
1315 assert(BO->isLogicalOp() &&
1316 "CFG terminator is not a short-circuit operator!");
1317 Cond = BO->getLHS();
1321 // However, when we encounter a logical operator as a branch condition,
1322 // then the condition is actually its RHS, because LHS would be
1323 // the condition for the logical operator terminator.
1324 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1325 if (!InnerBO->isLogicalOp())
1327 Cond = InnerBO->getRHS()->IgnoreParens();
1331 assert(srcBlk->succ_size() == 2);
1332 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1333 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1336 std::shared_ptr<PathDiagnosticPiece>
1337 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1338 BugReporterContext &BRC, BugReport &R,
1339 const ExplodedNode *N) {
1340 // These will be modified in code below, but we need to preserve the original
1341 // values in case we want to throw the generic message.
1342 const Expr *CondTmp = Cond;
1343 bool tookTrueTmp = tookTrue;
1346 CondTmp = CondTmp->IgnoreParenCasts();
1347 switch (CondTmp->getStmtClass()) {
1350 case Stmt::BinaryOperatorClass:
1351 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1352 tookTrueTmp, BRC, R, N))
1355 case Stmt::DeclRefExprClass:
1356 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1357 tookTrueTmp, BRC, R, N))
1360 case Stmt::UnaryOperatorClass: {
1361 const UnaryOperator *UO = cast<UnaryOperator>(CondTmp);
1362 if (UO->getOpcode() == UO_LNot) {
1363 tookTrueTmp = !tookTrueTmp;
1364 CondTmp = UO->getSubExpr();
1373 // Condition too complex to explain? Just say something so that the user
1374 // knew we've made some path decision at this point.
1375 const LocationContext *LCtx = N->getLocationContext();
1376 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1377 if (!Loc.isValid() || !Loc.asLocation().isValid())
1380 return std::make_shared<PathDiagnosticEventPiece>(
1381 Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1384 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1385 const Expr *ParentEx,
1387 BugReporterContext &BRC,
1389 const ExplodedNode *N,
1390 Optional<bool> &prunable) {
1391 const Expr *OriginalExpr = Ex;
1392 Ex = Ex->IgnoreParenCasts();
1394 // Use heuristics to determine if Ex is a macro expending to a literal and
1395 // if so, use the macro's name.
1396 SourceLocation LocStart = Ex->getLocStart();
1397 SourceLocation LocEnd = Ex->getLocEnd();
1398 if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1399 (isa<GNUNullExpr>(Ex) ||
1400 isa<ObjCBoolLiteralExpr>(Ex) ||
1401 isa<CXXBoolLiteralExpr>(Ex) ||
1402 isa<IntegerLiteral>(Ex) ||
1403 isa<FloatingLiteral>(Ex))) {
1405 StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1406 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1407 StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1408 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1409 bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1411 bool partOfParentMacro = false;
1412 if (ParentEx->getLocStart().isMacroID()) {
1413 StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
1414 ParentEx->getLocStart(), BRC.getSourceManager(),
1415 BRC.getASTContext().getLangOpts());
1416 partOfParentMacro = PName.equals(StartName);
1419 if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
1420 // Get the location of the macro name as written by the caller.
1421 SourceLocation Loc = LocStart;
1422 while (LocStart.isMacroID()) {
1424 LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
1426 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
1427 Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1429 // Return the macro name.
1435 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1436 const bool quotes = isa<VarDecl>(DR->getDecl());
1439 const LocationContext *LCtx = N->getLocationContext();
1440 const ProgramState *state = N->getState().get();
1441 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1442 LCtx).getAsRegion()) {
1443 if (report.isInteresting(R))
1446 const ProgramState *state = N->getState().get();
1447 SVal V = state->getSVal(R);
1448 if (report.isInteresting(V))
1453 Out << DR->getDecl()->getDeclName().getAsString();
1459 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1460 QualType OriginalTy = OriginalExpr->getType();
1461 if (OriginalTy->isPointerType()) {
1462 if (IL->getValue() == 0) {
1467 else if (OriginalTy->isObjCObjectPointerType()) {
1468 if (IL->getValue() == 0) {
1474 Out << IL->getValue();
1481 std::shared_ptr<PathDiagnosticPiece>
1482 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
1483 const bool tookTrue, BugReporterContext &BRC,
1484 BugReport &R, const ExplodedNode *N) {
1486 bool shouldInvert = false;
1487 Optional<bool> shouldPrune;
1489 SmallString<128> LhsString, RhsString;
1491 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1492 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
1493 BRC, R, N, shouldPrune);
1494 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
1495 BRC, R, N, shouldPrune);
1497 shouldInvert = !isVarLHS && isVarRHS;
1500 BinaryOperator::Opcode Op = BExpr->getOpcode();
1502 if (BinaryOperator::isAssignmentOp(Op)) {
1503 // For assignment operators, all that we care about is that the LHS
1504 // evaluates to "true" or "false".
1505 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1509 // For non-assignment operations, we require that we can understand
1510 // both the LHS and RHS.
1511 if (LhsString.empty() || RhsString.empty() ||
1512 !BinaryOperator::isComparisonOp(Op))
1515 // Should we invert the strings if the LHS is not a variable name?
1516 SmallString<256> buf;
1517 llvm::raw_svector_ostream Out(buf);
1518 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1520 // Do we need to invert the opcode?
1524 case BO_LT: Op = BO_GT; break;
1525 case BO_GT: Op = BO_LT; break;
1526 case BO_LE: Op = BO_GE; break;
1527 case BO_GE: Op = BO_LE; break;
1532 case BO_EQ: Op = BO_NE; break;
1533 case BO_NE: Op = BO_EQ; break;
1534 case BO_LT: Op = BO_GE; break;
1535 case BO_GT: Op = BO_LE; break;
1536 case BO_LE: Op = BO_GT; break;
1537 case BO_GE: Op = BO_LT; break;
1547 Out << "not equal to ";
1550 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1554 Out << (shouldInvert ? LhsString : RhsString);
1555 const LocationContext *LCtx = N->getLocationContext();
1556 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1557 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1558 if (shouldPrune.hasValue())
1559 event->setPrunable(shouldPrune.getValue());
1563 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
1564 StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
1565 BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
1566 // FIXME: If there's already a constraint tracker for this variable,
1567 // we shouldn't emit anything here (c.f. the double note in
1568 // test/Analysis/inlining/path-notes.c)
1569 SmallString<256> buf;
1570 llvm::raw_svector_ostream Out(buf);
1571 Out << "Assuming " << LhsString << " is ";
1573 QualType Ty = CondVarExpr->getType();
1575 if (Ty->isPointerType())
1576 Out << (tookTrue ? "not null" : "null");
1577 else if (Ty->isObjCObjectPointerType())
1578 Out << (tookTrue ? "not nil" : "nil");
1579 else if (Ty->isBooleanType())
1580 Out << (tookTrue ? "true" : "false");
1581 else if (Ty->isIntegralOrEnumerationType())
1582 Out << (tookTrue ? "non-zero" : "zero");
1586 const LocationContext *LCtx = N->getLocationContext();
1587 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1588 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1590 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1591 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1592 const ProgramState *state = N->getState().get();
1593 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1594 if (report.isInteresting(R))
1595 event->setPrunable(false);
1603 std::shared_ptr<PathDiagnosticPiece>
1604 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
1605 const bool tookTrue, BugReporterContext &BRC,
1606 BugReport &report, const ExplodedNode *N) {
1608 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1612 SmallString<256> Buf;
1613 llvm::raw_svector_ostream Out(Buf);
1615 Out << "Assuming '" << VD->getDeclName() << "' is ";
1617 QualType VDTy = VD->getType();
1619 if (VDTy->isPointerType())
1620 Out << (tookTrue ? "non-null" : "null");
1621 else if (VDTy->isObjCObjectPointerType())
1622 Out << (tookTrue ? "non-nil" : "nil");
1623 else if (VDTy->isScalarType())
1624 Out << (tookTrue ? "not equal to 0" : "0");
1628 const LocationContext *LCtx = N->getLocationContext();
1629 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1630 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1632 const ProgramState *state = N->getState().get();
1633 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1634 if (report.isInteresting(R))
1635 event->setPrunable(false);
1637 SVal V = state->getSVal(R);
1638 if (report.isInteresting(V))
1639 event->setPrunable(false);
1642 return std::move(event);
1645 const char *const ConditionBRVisitor::GenericTrueMessage =
1646 "Assuming the condition is true";
1647 const char *const ConditionBRVisitor::GenericFalseMessage =
1648 "Assuming the condition is false";
1650 bool ConditionBRVisitor::isPieceMessageGeneric(
1651 const PathDiagnosticPiece *Piece) {
1652 return Piece->getString() == GenericTrueMessage ||
1653 Piece->getString() == GenericFalseMessage;
1656 std::unique_ptr<PathDiagnosticPiece>
1657 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1658 const ExplodedNode *N,
1660 // Here we suppress false positives coming from system headers. This list is
1661 // based on known issues.
1662 ExprEngine &Eng = BRC.getBugReporter().getEngine();
1663 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1664 const Decl *D = N->getLocationContext()->getDecl();
1666 if (AnalysisDeclContext::isInStdNamespace(D)) {
1667 // Skip reports within the 'std' namespace. Although these can sometimes be
1668 // the user's fault, we currently don't report them very well, and
1669 // Note that this will not help for any other data structure libraries, like
1670 // TR1, Boost, or llvm/ADT.
1671 if (Options.shouldSuppressFromCXXStandardLibrary()) {
1672 BR.markInvalid(getTag(), nullptr);
1676 // If the complete 'std' suppression is not enabled, suppress reports
1677 // from the 'std' namespace that are known to produce false positives.
1679 // The analyzer issues a false use-after-free when std::list::pop_front
1680 // or std::list::pop_back are called multiple times because we cannot
1681 // reason about the internal invariants of the data structure.
1682 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1683 const CXXRecordDecl *CD = MD->getParent();
1684 if (CD->getName() == "list") {
1685 BR.markInvalid(getTag(), nullptr);
1690 // The analyzer issues a false positive when the constructor of
1691 // std::__independent_bits_engine from algorithms is used.
1692 if (const CXXConstructorDecl *MD = dyn_cast<CXXConstructorDecl>(D)) {
1693 const CXXRecordDecl *CD = MD->getParent();
1694 if (CD->getName() == "__independent_bits_engine") {
1695 BR.markInvalid(getTag(), nullptr);
1700 for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
1701 LCtx = LCtx->getParent()) {
1702 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
1706 const CXXRecordDecl *CD = MD->getParent();
1707 // The analyzer issues a false positive on
1708 // std::basic_string<uint8_t> v; v.push_back(1);
1710 // std::u16string s; s += u'a';
1711 // because we cannot reason about the internal invariants of the
1713 if (CD->getName() == "basic_string") {
1714 BR.markInvalid(getTag(), nullptr);
1718 // The analyzer issues a false positive on
1719 // std::shared_ptr<int> p(new int(1)); p = nullptr;
1720 // because it does not reason properly about temporary destructors.
1721 if (CD->getName() == "shared_ptr") {
1722 BR.markInvalid(getTag(), nullptr);
1729 // Skip reports within the sys/queue.h macros as we do not have the ability to
1730 // reason about data structure shapes.
1731 SourceManager &SM = BRC.getSourceManager();
1732 FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1733 while (Loc.isMacroID()) {
1734 Loc = Loc.getSpellingLoc();
1735 if (SM.getFilename(Loc).endswith("sys/queue.h")) {
1736 BR.markInvalid(getTag(), nullptr);
1744 std::shared_ptr<PathDiagnosticPiece>
1745 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1746 const ExplodedNode *PrevN,
1747 BugReporterContext &BRC, BugReport &BR) {
1749 ProgramStateRef State = N->getState();
1750 ProgramPoint ProgLoc = N->getLocation();
1752 // We are only interested in visiting CallEnter nodes.
1753 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1757 // Check if one of the arguments is the region the visitor is tracking.
1758 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1759 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1761 ArrayRef<ParmVarDecl*> parms = Call->parameters();
1763 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1764 I != E; ++I, ++Idx) {
1765 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1767 // Are we tracking the argument or its subregion?
1768 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1771 // Check the function parameter type.
1772 const ParmVarDecl *ParamDecl = *I;
1773 assert(ParamDecl && "Formal parameter has no decl?");
1774 QualType T = ParamDecl->getType();
1776 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1777 // Function can only change the value passed in by address.
1781 // If it is a const pointer value, the function does not intend to
1782 // change the value.
1783 if (T->getPointeeType().isConstQualified())
1786 // Mark the call site (LocationContext) as interesting if the value of the
1787 // argument is undefined or '0'/'NULL'.
1788 SVal BoundVal = State->getSVal(R);
1789 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1790 BR.markInteresting(CEnter->getCalleeContext());
1797 std::shared_ptr<PathDiagnosticPiece>
1798 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
1799 const ExplodedNode *Pred,
1800 BugReporterContext &BRC, BugReport &BR) {
1804 auto Edge = Succ->getLocation().getAs<BlockEdge>();
1805 if (!Edge.hasValue())
1808 auto Tag = Edge->getTag();
1812 if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
1818 dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
1819 assert(Met && "Not a C++ method.");
1820 assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
1821 "Not a copy/move assignment operator.");
1823 const auto *LCtx = Edge->getLocationContext();
1825 const auto &State = Succ->getState();
1826 auto &SVB = State->getStateManager().getSValBuilder();
1829 State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
1831 State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame()));
1833 auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
1835 if (!L.isValid() || !L.asLocation().isValid())
1838 SmallString<256> Buf;
1839 llvm::raw_svector_ostream Out(Buf);
1841 Out << "Assuming " << Met->getParamDecl(0)->getName() <<
1842 ((Param == This) ? " == " : " != ") << "*this";
1844 auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
1845 Piece->addRange(Met->getSourceRange());
1847 return std::move(Piece);