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->isArrow() || isDeclRefExprToReference(ME->getBase())) {
65 return ME->getBase()->IgnoreParenCasts();
67 // If we have a member expr with a dot, the base must have been
69 return getDerefExpr(ME->getBase());
72 else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
73 return IvarRef->getBase()->IgnoreParenCasts();
75 else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
78 else if (isDeclRefExprToReference(E)) {
87 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
88 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
89 if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
94 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
95 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
96 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
97 return RS->getRetValue();
101 //===----------------------------------------------------------------------===//
102 // Definitions for bug reporter visitors.
103 //===----------------------------------------------------------------------===//
105 std::unique_ptr<PathDiagnosticPiece>
106 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
107 const ExplodedNode *EndPathNode, BugReport &BR) {
111 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
112 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
113 PathDiagnosticLocation L =
114 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
116 const auto &Ranges = BR.getRanges();
118 // Only add the statement itself as a range if we didn't specify any
119 // special ranges for this report.
120 auto P = llvm::make_unique<PathDiagnosticEventPiece>(
121 L, BR.getDescription(), Ranges.begin() == Ranges.end());
122 for (SourceRange Range : Ranges)
130 /// Emits an extra note at the return statement of an interesting stack frame.
132 /// The returned value is marked as an interesting value, and if it's null,
133 /// adds a visitor to track where it became null.
135 /// This visitor is intended to be used when another visitor discovers that an
136 /// interesting value comes from an inlined function call.
137 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
138 const StackFrameContext *StackFrame;
145 bool EnableNullFPSuppression;
148 ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
149 : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
151 static void *getTag() {
153 return static_cast<void *>(&Tag);
156 void Profile(llvm::FoldingSetNodeID &ID) const override {
157 ID.AddPointer(ReturnVisitor::getTag());
158 ID.AddPointer(StackFrame);
159 ID.AddBoolean(EnableNullFPSuppression);
162 /// Adds a ReturnVisitor if the given statement represents a call that was
165 /// This will search back through the ExplodedGraph, starting from the given
166 /// node, looking for when the given statement was processed. If it turns out
167 /// the statement is a call that was inlined, we add the visitor to the
168 /// bug report, so it can print a note later.
169 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
171 bool InEnableNullFPSuppression) {
172 if (!CallEvent::isCallStmt(S))
175 // First, find when we processed the statement.
177 if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
178 if (CEE->getCalleeContext()->getCallSite() == S)
180 if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
181 if (SP->getStmt() == S)
184 Node = Node->getFirstPred();
187 // Next, step over any post-statement checks.
188 while (Node && Node->getLocation().getAs<PostStmt>())
189 Node = Node->getFirstPred();
193 // Finally, see if we inlined the call.
194 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
198 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
199 if (CalleeContext->getCallSite() != S)
202 // Check the return value.
203 ProgramStateRef State = Node->getState();
204 SVal RetVal = State->getSVal(S, Node->getLocationContext());
206 // Handle cases where a reference is returned and then immediately used.
207 if (cast<Expr>(S)->isGLValue())
208 if (Optional<Loc> LValue = RetVal.getAs<Loc>())
209 RetVal = State->getSVal(*LValue);
211 // See if the return value is NULL. If so, suppress the report.
212 SubEngine *Eng = State->getStateManager().getOwningEngine();
213 assert(Eng && "Cannot file a bug report without an owning engine");
214 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
216 bool EnableNullFPSuppression = false;
217 if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
218 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
219 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
221 BR.markInteresting(CalleeContext);
222 BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
223 EnableNullFPSuppression));
226 /// Returns true if any counter-suppression heuristics are enabled for
228 static bool hasCounterSuppression(AnalyzerOptions &Options) {
229 return Options.shouldAvoidSuppressingNullArgumentPaths();
232 std::shared_ptr<PathDiagnosticPiece>
233 visitNodeInitial(const ExplodedNode *N, const ExplodedNode *PrevN,
234 BugReporterContext &BRC, BugReport &BR) {
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 if (!L.isValid() || !L.asLocation().isValid())
330 return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
333 std::shared_ptr<PathDiagnosticPiece>
334 visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
335 BugReporterContext &BRC, BugReport &BR) {
337 ExprEngine &Eng = BRC.getBugReporter().getEngine();
338 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
339 assert(hasCounterSuppression(Options));
342 // Are we at the entry node for this call?
343 Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
347 if (CE->getCalleeContext() != StackFrame)
352 // Don't automatically suppress a report if one of the arguments is
353 // known to be a null pointer. Instead, start tracking /that/ null
354 // value back to its origin.
355 ProgramStateManager &StateMgr = BRC.getStateManager();
356 CallEventManager &CallMgr = StateMgr.getCallEventManager();
358 ProgramStateRef State = N->getState();
359 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
360 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
361 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
365 const Expr *ArgE = Call->getArgExpr(I);
369 // Is it possible for this argument to be non-null?
370 if (!State->isNull(*ArgV).isConstrainedTrue())
373 if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
374 EnableNullFPSuppression))
375 BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
377 // If we /can't/ track the null pointer, we should err on the side of
378 // false negatives, and continue towards marking this report invalid.
379 // (We will still look at the other arguments, though.)
385 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
386 const ExplodedNode *PrevN,
387 BugReporterContext &BRC,
388 BugReport &BR) override {
391 return visitNodeInitial(N, PrevN, BRC, BR);
392 case MaybeUnsuppress:
393 return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
398 llvm_unreachable("Invalid visit mode!");
401 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
402 const ExplodedNode *N,
403 BugReport &BR) override {
404 if (EnableNullFPSuppression)
405 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
409 } // end anonymous namespace
412 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
417 ID.AddBoolean(EnableNullFPSuppression);
420 /// Returns true if \p N represents the DeclStmt declaring and initializing
422 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
423 Optional<PostStmt> P = N->getLocationAs<PostStmt>();
427 const DeclStmt *DS = P->getStmtAs<DeclStmt>();
431 if (DS->getSingleDecl() != VR->getDecl())
434 const MemSpaceRegion *VarSpace = VR->getMemorySpace();
435 const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
437 // If we ever directly evaluate global DeclStmts, this assertion will be
438 // invalid, but this still seems preferable to silently accepting an
439 // initialization that may be for a path-sensitive variable.
440 assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
444 assert(VR->getDecl()->hasLocalStorage());
445 const LocationContext *LCtx = N->getLocationContext();
446 return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
449 std::shared_ptr<PathDiagnosticPiece>
450 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
451 const ExplodedNode *Pred,
452 BugReporterContext &BRC, BugReport &BR) {
457 const ExplodedNode *StoreSite = nullptr;
458 const Expr *InitE = nullptr;
459 bool IsParam = false;
461 // First see if we reached the declaration of the region.
462 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
463 if (isInitializationOfVar(Pred, VR)) {
465 InitE = VR->getDecl()->getInit();
469 // If this is a post initializer expression, initializing the region, we
470 // should track the initializer expression.
471 if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
472 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
473 if (FieldReg && FieldReg == R) {
475 InitE = PIP->getInitializer()->getInit();
479 // Otherwise, see if this is the store site:
480 // (1) Succ has this binding and Pred does not, i.e. this is
481 // where the binding first occurred.
482 // (2) Succ has this binding and is a PostStore node for this region, i.e.
483 // the same binding was re-assigned here.
485 if (Succ->getState()->getSVal(R) != V)
488 if (Pred->getState()->getSVal(R) == V) {
489 Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
490 if (!PS || PS->getLocationValue() != R)
496 // If this is an assignment expression, we can track the value
498 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
499 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
500 if (BO->isAssignmentOp())
501 InitE = BO->getRHS();
503 // If this is a call entry, the variable should be a parameter.
504 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
505 // 'this' should never be NULL, but this visitor isn't just for NULL and
507 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
508 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
509 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
511 ProgramStateManager &StateMgr = BRC.getStateManager();
512 CallEventManager &CallMgr = StateMgr.getCallEventManager();
514 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
516 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
521 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
522 // is wrapped inside of it.
523 if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
524 InitE = TmpR->getExpr();
531 // If we have an expression that provided the value, try to track where it
535 V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
537 InitE = InitE->IgnoreParenCasts();
538 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
539 EnableNullFPSuppression);
541 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
542 BR, EnableNullFPSuppression);
546 // Okay, we've found the binding. Emit an appropriate message.
547 SmallString<256> sbuf;
548 llvm::raw_svector_ostream os(sbuf);
550 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
551 const Stmt *S = PS->getStmt();
552 const char *action = nullptr;
553 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
554 const VarRegion *VR = dyn_cast<VarRegion>(R);
557 action = R->canPrintPretty() ? "initialized to " :
559 } else if (isa<BlockExpr>(S)) {
560 action = R->canPrintPretty() ? "captured by block as " :
561 "Captured by block as ";
563 // See if we can get the BlockVarRegion.
564 ProgramStateRef State = StoreSite->getState();
565 SVal V = State->getSVal(S, PS->getLocationContext());
566 if (const BlockDataRegion *BDR =
567 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
568 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
569 if (Optional<KnownSVal> KV =
570 State->getSVal(OriginalR).getAs<KnownSVal>())
571 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
572 *KV, OriginalR, EnableNullFPSuppression));
579 if (R->canPrintPretty()) {
584 if (V.getAs<loc::ConcreteInt>()) {
586 if (R->isBoundable()) {
587 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
588 if (TR->getValueType()->isObjCObjectPointerType()) {
589 os << action << "nil";
596 os << action << "a null pointer value";
597 } else if (Optional<nonloc::ConcreteInt> CVal =
598 V.getAs<nonloc::ConcreteInt>()) {
599 os << action << CVal->getValue();
603 if (isa<VarRegion>(R)) {
604 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
606 os << (R->canPrintPretty() ? "initialized" : "Initializing")
607 << " to a garbage value";
609 os << (R->canPrintPretty() ? "declared" : "Declaring")
610 << " without an initial value";
615 os << (R->canPrintPretty() ? "initialized" : "Initialized")
620 } else if (StoreSite->getLocation().getAs<CallEnter>()) {
621 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
622 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
626 if (V.getAs<loc::ConcreteInt>()) {
627 if (Param->getType()->isObjCObjectPointerType())
628 os << "nil object reference";
630 os << "null pointer value";
631 } else if (V.isUndef()) {
632 os << "uninitialized value";
633 } else if (Optional<nonloc::ConcreteInt> CI =
634 V.getAs<nonloc::ConcreteInt>()) {
635 os << "the value " << CI->getValue();
640 // Printed parameter indexes are 1-based, not 0-based.
641 unsigned Idx = Param->getFunctionScopeIndex() + 1;
642 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
643 if (R->canPrintPretty()) {
650 if (os.str().empty()) {
651 if (V.getAs<loc::ConcreteInt>()) {
653 if (R->isBoundable()) {
654 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
655 if (TR->getValueType()->isObjCObjectPointerType()) {
656 os << "nil object reference stored";
662 if (R->canPrintPretty())
663 os << "Null pointer value stored";
665 os << "Storing null pointer value";
668 } else if (V.isUndef()) {
669 if (R->canPrintPretty())
670 os << "Uninitialized value stored";
672 os << "Storing uninitialized value";
674 } else if (Optional<nonloc::ConcreteInt> CV =
675 V.getAs<nonloc::ConcreteInt>()) {
676 if (R->canPrintPretty())
677 os << "The value " << CV->getValue() << " is assigned";
679 os << "Assigning " << CV->getValue();
682 if (R->canPrintPretty())
683 os << "Value assigned";
685 os << "Assigning value";
688 if (R->canPrintPretty()) {
694 // Construct a new PathDiagnosticPiece.
695 ProgramPoint P = StoreSite->getLocation();
696 PathDiagnosticLocation L;
697 if (P.getAs<CallEnter>() && InitE)
698 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
699 P.getLocationContext());
701 if (!L.isValid() || !L.asLocation().isValid())
702 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
704 if (!L.isValid() || !L.asLocation().isValid())
707 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
710 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
713 ID.AddBoolean(Assumption);
717 /// Return the tag associated with this visitor. This tag will be used
718 /// to make all PathDiagnosticPieces created by this visitor.
719 const char *TrackConstraintBRVisitor::getTag() {
720 return "TrackConstraintBRVisitor";
723 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
725 return N->getState()->isNull(Constraint).isUnderconstrained();
726 return (bool)N->getState()->assume(Constraint, !Assumption);
729 std::shared_ptr<PathDiagnosticPiece>
730 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
731 const ExplodedNode *PrevN,
732 BugReporterContext &BRC, BugReport &BR) {
736 // Start tracking after we see the first state in which the value is
738 if (!IsTrackingTurnedOn)
739 if (!isUnderconstrained(N))
740 IsTrackingTurnedOn = true;
741 if (!IsTrackingTurnedOn)
744 // Check if in the previous state it was feasible for this constraint
746 if (isUnderconstrained(PrevN)) {
750 // As a sanity check, make sure that the negation of the constraint
751 // was infeasible in the current state. If it is feasible, we somehow
752 // missed the transition point.
753 assert(!isUnderconstrained(N));
755 // We found the transition point for the constraint. We now need to
756 // pretty-print the constraint. (work-in-progress)
757 SmallString<64> sbuf;
758 llvm::raw_svector_ostream os(sbuf);
760 if (Constraint.getAs<Loc>()) {
761 os << "Assuming pointer value is ";
762 os << (Assumption ? "non-null" : "null");
765 if (os.str().empty())
768 // Construct a new PathDiagnosticPiece.
769 ProgramPoint P = N->getLocation();
770 PathDiagnosticLocation L =
771 PathDiagnosticLocation::create(P, BRC.getSourceManager());
775 auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
783 SuppressInlineDefensiveChecksVisitor::
784 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
785 : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
787 // Check if the visitor is disabled.
788 SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
789 assert(Eng && "Cannot file a bug report without an owning engine");
790 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
791 if (!Options.shouldSuppressInlinedDefensiveChecks())
794 assert(N->getState()->isNull(V).isConstrainedTrue() &&
795 "The visitor only tracks the cases where V is constrained to 0");
798 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
804 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
808 std::shared_ptr<PathDiagnosticPiece>
809 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
810 const ExplodedNode *Pred,
811 BugReporterContext &BRC,
816 // Start tracking after we see the first state in which the value is null.
817 if (!IsTrackingTurnedOn)
818 if (Succ->getState()->isNull(V).isConstrainedTrue())
819 IsTrackingTurnedOn = true;
820 if (!IsTrackingTurnedOn)
823 // Check if in the previous state it was feasible for this value
825 if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
828 assert(Succ->getState()->isNull(V).isConstrainedTrue());
830 // Check if this is inlined defensive checks.
831 const LocationContext *CurLC =Succ->getLocationContext();
832 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
833 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
834 BR.markInvalid("Suppress IDC", CurLC);
838 // Treat defensive checks in function-like macros as if they were an inlined
839 // defensive check. If the bug location is not in a macro and the
840 // terminator for the current location is in a macro then suppress the
842 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
847 SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
848 if (BugLoc.isMacroID())
851 ProgramPoint CurPoint = Succ->getLocation();
852 const Stmt *CurTerminatorStmt = nullptr;
853 if (auto BE = CurPoint.getAs<BlockEdge>()) {
854 CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
855 } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
856 const Stmt *CurStmt = SP->getStmt();
857 if (!CurStmt->getLocStart().isMacroID())
860 CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
861 CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
866 if (!CurTerminatorStmt)
869 SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
870 if (TerminatorLoc.isMacroID()) {
871 const SourceManager &SMgr = BRC.getSourceManager();
872 std::pair<FileID, unsigned> TLInfo = SMgr.getDecomposedLoc(TerminatorLoc);
873 SrcMgr::SLocEntry SE = SMgr.getSLocEntry(TLInfo.first);
874 const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
875 if (EInfo.isFunctionMacroExpansion()) {
876 BR.markInvalid("Suppress Macro IDC", CurLC);
884 static const MemRegion *getLocationRegionIfReference(const Expr *E,
885 const ExplodedNode *N) {
886 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
887 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
888 if (!VD->getType()->isReferenceType())
890 ProgramStateManager &StateMgr = N->getState()->getStateManager();
891 MemRegionManager &MRMgr = StateMgr.getRegionManager();
892 return MRMgr.getVarRegion(VD, N->getLocationContext());
896 // FIXME: This does not handle other kinds of null references,
897 // for example, references from FieldRegions:
898 // struct Wrapper { int &ref; };
899 // Wrapper w = { *(int *)0 };
905 static const Expr *peelOffOuterExpr(const Expr *Ex,
906 const ExplodedNode *N) {
907 Ex = Ex->IgnoreParenCasts();
908 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
909 return peelOffOuterExpr(EWC->getSubExpr(), N);
910 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
911 return peelOffOuterExpr(OVE->getSourceExpr(), N);
912 if (auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
913 auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
914 if (PropRef && PropRef->isMessagingGetter()) {
915 const Expr *GetterMessageSend =
916 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
917 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
918 return peelOffOuterExpr(GetterMessageSend, N);
922 // Peel off the ternary operator.
923 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
924 // Find a node where the branching occurred and find out which branch
925 // we took (true/false) by looking at the ExplodedGraph.
926 const ExplodedNode *NI = N;
928 ProgramPoint ProgPoint = NI->getLocation();
929 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
930 const CFGBlock *srcBlk = BE->getSrc();
931 if (const Stmt *term = srcBlk->getTerminator()) {
933 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
935 return peelOffOuterExpr(CO->getTrueExpr(), N);
937 return peelOffOuterExpr(CO->getFalseExpr(), N);
941 NI = NI->getFirstPred();
947 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
949 BugReport &report, bool IsArg,
950 bool EnableNullFPSuppression) {
954 if (const Expr *Ex = dyn_cast<Expr>(S)) {
955 Ex = Ex->IgnoreParenCasts();
956 const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
961 const Expr *Inner = nullptr;
962 if (const Expr *Ex = dyn_cast<Expr>(S)) {
963 Ex = Ex->IgnoreParenCasts();
964 if (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex))
968 if (IsArg && !Inner) {
969 assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
971 // Walk through nodes until we get one that matches the statement exactly.
972 // Alternately, if we hit a known lvalue for the statement, we know we've
973 // gone too far (though we can likely track the lvalue better anyway).
975 const ProgramPoint &pp = N->getLocation();
976 if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
977 if (ps->getStmt() == S || ps->getStmt() == Inner)
979 } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
980 if (CEE->getCalleeContext()->getCallSite() == S ||
981 CEE->getCalleeContext()->getCallSite() == Inner)
984 N = N->getFirstPred();
991 ProgramStateRef state = N->getState();
993 // The message send could be nil due to the receiver being nil.
994 // At this point in the path, the receiver should be live since we are at the
995 // message send expr. If it is nil, start tracking it.
996 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
997 trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
1000 // See if the expression we're interested refers to a variable.
1001 // If so, we can track both its contents and constraints on its value.
1002 if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
1003 const MemRegion *R = nullptr;
1005 // Find the ExplodedNode where the lvalue (the value of 'Ex')
1006 // was computed. We need this for getting the location value.
1007 const ExplodedNode *LVNode = N;
1009 if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
1010 if (P->getStmt() == Inner)
1013 LVNode = LVNode->getFirstPred();
1015 assert(LVNode && "Unable to find the lvalue node.");
1016 ProgramStateRef LVState = LVNode->getState();
1017 SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
1019 if (LVState->isNull(LVal).isConstrainedTrue()) {
1020 // In case of C++ references, we want to differentiate between a null
1021 // reference and reference to null pointer.
1022 // If the LVal is null, check if we are dealing with null reference.
1023 // For those, we want to track the location of the reference.
1024 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
1027 R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
1029 // If this is a C++ reference to a null pointer, we are tracking the
1030 // pointer. In additon, we should find the store at which the reference
1032 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
1033 if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
1034 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1035 *KV, RR, EnableNullFPSuppression));
1040 // Mark both the variable region and its contents as interesting.
1041 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1043 report.markInteresting(R);
1044 report.markInteresting(V);
1045 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1047 // If the contents are symbolic, find out when they became null.
1048 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1049 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1050 V.castAs<DefinedSVal>(), false));
1052 // Add visitor, which will suppress inline defensive checks.
1053 if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
1054 if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1055 EnableNullFPSuppression) {
1057 llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1062 if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1063 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1064 *KV, R, EnableNullFPSuppression));
1069 // If the expression is not an "lvalue expression", we can still
1070 // track the constraints on its contents.
1071 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1073 // If the value came from an inlined function call, we should at least make
1074 // sure that function isn't pruned in our output.
1075 if (const Expr *E = dyn_cast<Expr>(S))
1076 S = E->IgnoreParenCasts();
1078 ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1080 // Uncomment this to find cases where we aren't properly getting the
1081 // base value that was dereferenced.
1082 // assert(!V.isUnknownOrUndef());
1083 // Is it a symbolic value?
1084 if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
1085 // At this point we are dealing with the region's LValue.
1086 // However, if the rvalue is a symbolic region, we should track it as well.
1087 // Try to use the correct type when looking up the value.
1089 if (const Expr *E = dyn_cast<Expr>(S))
1090 RVal = state->getRawSVal(L.getValue(), E->getType());
1092 RVal = state->getSVal(L->getRegion());
1094 const MemRegion *RegionRVal = RVal.getAsRegion();
1095 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1097 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1098 report.markInteresting(RegionRVal);
1099 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1100 loc::MemRegionVal(RegionRVal), false));
1107 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1108 const ExplodedNode *N) {
1109 const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1112 if (const Expr *Receiver = ME->getInstanceReceiver()) {
1113 ProgramStateRef state = N->getState();
1114 SVal V = state->getSVal(Receiver, N->getLocationContext());
1115 if (state->isNull(V).isConstrainedTrue())
1121 std::shared_ptr<PathDiagnosticPiece>
1122 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1123 const ExplodedNode *PrevN,
1124 BugReporterContext &BRC, BugReport &BR) {
1125 Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1129 const Stmt *S = P->getStmt();
1130 const Expr *Receiver = getNilReceiver(S, N);
1134 llvm::SmallString<256> Buf;
1135 llvm::raw_svector_ostream OS(Buf);
1137 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1139 ME->getSelector().print(OS);
1140 OS << "' not called";
1143 OS << "No method is called";
1145 OS << " because the receiver is nil";
1147 // The receiver was nil, and hence the method was skipped.
1148 // Register a BugReporterVisitor to issue a message telling us how
1149 // the receiver was null.
1150 bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1151 /*EnableNullFPSuppression*/ false);
1152 // Issue a message saying that the method was skipped.
1153 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1154 N->getLocationContext());
1155 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1158 // Registers every VarDecl inside a Stmt with a last store visitor.
1159 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1161 bool EnableNullFPSuppression) {
1162 const ExplodedNode *N = BR.getErrorNode();
1163 std::deque<const Stmt *> WorkList;
1164 WorkList.push_back(S);
1166 while (!WorkList.empty()) {
1167 const Stmt *Head = WorkList.front();
1168 WorkList.pop_front();
1170 ProgramStateRef state = N->getState();
1171 ProgramStateManager &StateMgr = state->getStateManager();
1173 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1174 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1175 const VarRegion *R =
1176 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1178 // What did we load?
1179 SVal V = state->getSVal(S, N->getLocationContext());
1181 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1182 // Register a new visitor with the BugReport.
1183 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1184 V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1189 for (const Stmt *SubStmt : Head->children())
1190 WorkList.push_back(SubStmt);
1194 //===----------------------------------------------------------------------===//
1195 // Visitor that tries to report interesting diagnostics from conditions.
1196 //===----------------------------------------------------------------------===//
1198 /// Return the tag associated with this visitor. This tag will be used
1199 /// to make all PathDiagnosticPieces created by this visitor.
1200 const char *ConditionBRVisitor::getTag() {
1201 return "ConditionBRVisitor";
1204 std::shared_ptr<PathDiagnosticPiece>
1205 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
1206 BugReporterContext &BRC, BugReport &BR) {
1207 auto piece = VisitNodeImpl(N, Prev, BRC, BR);
1209 piece->setTag(getTag());
1210 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1211 ev->setPrunable(true, /* override */ false);
1216 std::shared_ptr<PathDiagnosticPiece>
1217 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1218 const ExplodedNode *Prev,
1219 BugReporterContext &BRC, BugReport &BR) {
1221 ProgramPoint progPoint = N->getLocation();
1222 ProgramStateRef CurrentState = N->getState();
1223 ProgramStateRef PrevState = Prev->getState();
1225 // Compare the GDMs of the state, because that is where constraints
1226 // are managed. Note that ensure that we only look at nodes that
1227 // were generated by the analyzer engine proper, not checkers.
1228 if (CurrentState->getGDM().getRoot() ==
1229 PrevState->getGDM().getRoot())
1232 // If an assumption was made on a branch, it should be caught
1233 // here by looking at the state transition.
1234 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1235 const CFGBlock *srcBlk = BE->getSrc();
1236 if (const Stmt *term = srcBlk->getTerminator())
1237 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1241 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1242 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1244 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1245 cast<GRBugReporter>(BRC.getBugReporter()).
1246 getEngine().geteagerlyAssumeBinOpBifurcationTags();
1248 const ProgramPointTag *tag = PS->getTag();
1249 if (tag == tags.first)
1250 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1252 if (tag == tags.second)
1253 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1262 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1263 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1264 const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1265 const Expr *Cond = nullptr;
1267 // In the code below, Term is a CFG terminator and Cond is a branch condition
1268 // expression upon which the decision is made on this terminator.
1270 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1271 // and "x == 0" is the respective condition.
1273 // Another example: in "if (x && y)", we've got two terminators and two
1274 // conditions due to short-circuit nature of operator "&&":
1275 // 1. The "if (x && y)" statement is a terminator,
1276 // and "y" is the respective condition.
1277 // 2. Also "x && ..." is another terminator,
1278 // and "x" is its condition.
1280 switch (Term->getStmtClass()) {
1281 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1282 // more tricky because there are more than two branches to account for.
1285 case Stmt::IfStmtClass:
1286 Cond = cast<IfStmt>(Term)->getCond();
1288 case Stmt::ConditionalOperatorClass:
1289 Cond = cast<ConditionalOperator>(Term)->getCond();
1291 case Stmt::BinaryOperatorClass:
1292 // When we encounter a logical operator (&& or ||) as a CFG terminator,
1293 // then the condition is actually its LHS; otheriwse, we'd encounter
1294 // the parent, such as if-statement, as a terminator.
1295 const auto *BO = cast<BinaryOperator>(Term);
1296 assert(BO->isLogicalOp() &&
1297 "CFG terminator is not a short-circuit operator!");
1298 Cond = BO->getLHS();
1302 // However, when we encounter a logical operator as a branch condition,
1303 // then the condition is actually its RHS, because LHS would be
1304 // the condition for the logical operator terminator.
1305 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1306 if (!InnerBO->isLogicalOp())
1308 Cond = InnerBO->getRHS()->IgnoreParens();
1312 assert(srcBlk->succ_size() == 2);
1313 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1314 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1317 std::shared_ptr<PathDiagnosticPiece>
1318 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1319 BugReporterContext &BRC, BugReport &R,
1320 const ExplodedNode *N) {
1321 // These will be modified in code below, but we need to preserve the original
1322 // values in case we want to throw the generic message.
1323 const Expr *CondTmp = Cond;
1324 bool tookTrueTmp = tookTrue;
1327 CondTmp = CondTmp->IgnoreParenCasts();
1328 switch (CondTmp->getStmtClass()) {
1331 case Stmt::BinaryOperatorClass:
1332 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1333 tookTrueTmp, BRC, R, N))
1336 case Stmt::DeclRefExprClass:
1337 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1338 tookTrueTmp, BRC, R, N))
1341 case Stmt::UnaryOperatorClass: {
1342 const UnaryOperator *UO = cast<UnaryOperator>(CondTmp);
1343 if (UO->getOpcode() == UO_LNot) {
1344 tookTrueTmp = !tookTrueTmp;
1345 CondTmp = UO->getSubExpr();
1354 // Condition too complex to explain? Just say something so that the user
1355 // knew we've made some path decision at this point.
1356 const LocationContext *LCtx = N->getLocationContext();
1357 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1358 if (!Loc.isValid() || !Loc.asLocation().isValid())
1361 return std::make_shared<PathDiagnosticEventPiece>(
1362 Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1365 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1366 const Expr *ParentEx,
1368 BugReporterContext &BRC,
1370 const ExplodedNode *N,
1371 Optional<bool> &prunable) {
1372 const Expr *OriginalExpr = Ex;
1373 Ex = Ex->IgnoreParenCasts();
1375 // Use heuristics to determine if Ex is a macro expending to a literal and
1376 // if so, use the macro's name.
1377 SourceLocation LocStart = Ex->getLocStart();
1378 SourceLocation LocEnd = Ex->getLocEnd();
1379 if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1380 (isa<GNUNullExpr>(Ex) ||
1381 isa<ObjCBoolLiteralExpr>(Ex) ||
1382 isa<CXXBoolLiteralExpr>(Ex) ||
1383 isa<IntegerLiteral>(Ex) ||
1384 isa<FloatingLiteral>(Ex))) {
1386 StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1387 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1388 StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1389 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1390 bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1392 bool partOfParentMacro = false;
1393 if (ParentEx->getLocStart().isMacroID()) {
1394 StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
1395 ParentEx->getLocStart(), BRC.getSourceManager(),
1396 BRC.getASTContext().getLangOpts());
1397 partOfParentMacro = PName.equals(StartName);
1400 if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
1401 // Get the location of the macro name as written by the caller.
1402 SourceLocation Loc = LocStart;
1403 while (LocStart.isMacroID()) {
1405 LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
1407 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
1408 Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1410 // Return the macro name.
1416 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1417 const bool quotes = isa<VarDecl>(DR->getDecl());
1420 const LocationContext *LCtx = N->getLocationContext();
1421 const ProgramState *state = N->getState().get();
1422 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1423 LCtx).getAsRegion()) {
1424 if (report.isInteresting(R))
1427 const ProgramState *state = N->getState().get();
1428 SVal V = state->getSVal(R);
1429 if (report.isInteresting(V))
1434 Out << DR->getDecl()->getDeclName().getAsString();
1440 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1441 QualType OriginalTy = OriginalExpr->getType();
1442 if (OriginalTy->isPointerType()) {
1443 if (IL->getValue() == 0) {
1448 else if (OriginalTy->isObjCObjectPointerType()) {
1449 if (IL->getValue() == 0) {
1455 Out << IL->getValue();
1462 std::shared_ptr<PathDiagnosticPiece>
1463 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
1464 const bool tookTrue, BugReporterContext &BRC,
1465 BugReport &R, const ExplodedNode *N) {
1467 bool shouldInvert = false;
1468 Optional<bool> shouldPrune;
1470 SmallString<128> LhsString, RhsString;
1472 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1473 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
1474 BRC, R, N, shouldPrune);
1475 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
1476 BRC, R, N, shouldPrune);
1478 shouldInvert = !isVarLHS && isVarRHS;
1481 BinaryOperator::Opcode Op = BExpr->getOpcode();
1483 if (BinaryOperator::isAssignmentOp(Op)) {
1484 // For assignment operators, all that we care about is that the LHS
1485 // evaluates to "true" or "false".
1486 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1490 // For non-assignment operations, we require that we can understand
1491 // both the LHS and RHS.
1492 if (LhsString.empty() || RhsString.empty() ||
1493 !BinaryOperator::isComparisonOp(Op))
1496 // Should we invert the strings if the LHS is not a variable name?
1497 SmallString<256> buf;
1498 llvm::raw_svector_ostream Out(buf);
1499 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1501 // Do we need to invert the opcode?
1505 case BO_LT: Op = BO_GT; break;
1506 case BO_GT: Op = BO_LT; break;
1507 case BO_LE: Op = BO_GE; break;
1508 case BO_GE: Op = BO_LE; break;
1513 case BO_EQ: Op = BO_NE; break;
1514 case BO_NE: Op = BO_EQ; break;
1515 case BO_LT: Op = BO_GE; break;
1516 case BO_GT: Op = BO_LE; break;
1517 case BO_LE: Op = BO_GT; break;
1518 case BO_GE: Op = BO_LT; break;
1528 Out << "not equal to ";
1531 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1535 Out << (shouldInvert ? LhsString : RhsString);
1536 const LocationContext *LCtx = N->getLocationContext();
1537 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1538 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1539 if (shouldPrune.hasValue())
1540 event->setPrunable(shouldPrune.getValue());
1544 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
1545 StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
1546 BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
1547 // FIXME: If there's already a constraint tracker for this variable,
1548 // we shouldn't emit anything here (c.f. the double note in
1549 // test/Analysis/inlining/path-notes.c)
1550 SmallString<256> buf;
1551 llvm::raw_svector_ostream Out(buf);
1552 Out << "Assuming " << LhsString << " is ";
1554 QualType Ty = CondVarExpr->getType();
1556 if (Ty->isPointerType())
1557 Out << (tookTrue ? "not null" : "null");
1558 else if (Ty->isObjCObjectPointerType())
1559 Out << (tookTrue ? "not nil" : "nil");
1560 else if (Ty->isBooleanType())
1561 Out << (tookTrue ? "true" : "false");
1562 else if (Ty->isIntegralOrEnumerationType())
1563 Out << (tookTrue ? "non-zero" : "zero");
1567 const LocationContext *LCtx = N->getLocationContext();
1568 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1569 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1571 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1572 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1573 const ProgramState *state = N->getState().get();
1574 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1575 if (report.isInteresting(R))
1576 event->setPrunable(false);
1584 std::shared_ptr<PathDiagnosticPiece>
1585 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
1586 const bool tookTrue, BugReporterContext &BRC,
1587 BugReport &report, const ExplodedNode *N) {
1589 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1593 SmallString<256> Buf;
1594 llvm::raw_svector_ostream Out(Buf);
1596 Out << "Assuming '" << VD->getDeclName() << "' is ";
1598 QualType VDTy = VD->getType();
1600 if (VDTy->isPointerType())
1601 Out << (tookTrue ? "non-null" : "null");
1602 else if (VDTy->isObjCObjectPointerType())
1603 Out << (tookTrue ? "non-nil" : "nil");
1604 else if (VDTy->isScalarType())
1605 Out << (tookTrue ? "not equal to 0" : "0");
1609 const LocationContext *LCtx = N->getLocationContext();
1610 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1611 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1613 const ProgramState *state = N->getState().get();
1614 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1615 if (report.isInteresting(R))
1616 event->setPrunable(false);
1618 SVal V = state->getSVal(R);
1619 if (report.isInteresting(V))
1620 event->setPrunable(false);
1623 return std::move(event);
1626 const char *const ConditionBRVisitor::GenericTrueMessage =
1627 "Assuming the condition is true";
1628 const char *const ConditionBRVisitor::GenericFalseMessage =
1629 "Assuming the condition is false";
1631 bool ConditionBRVisitor::isPieceMessageGeneric(
1632 const PathDiagnosticPiece *Piece) {
1633 return Piece->getString() == GenericTrueMessage ||
1634 Piece->getString() == GenericFalseMessage;
1637 std::unique_ptr<PathDiagnosticPiece>
1638 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1639 const ExplodedNode *N,
1641 // Here we suppress false positives coming from system headers. This list is
1642 // based on known issues.
1643 ExprEngine &Eng = BRC.getBugReporter().getEngine();
1644 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1645 const Decl *D = N->getLocationContext()->getDecl();
1647 if (AnalysisDeclContext::isInStdNamespace(D)) {
1648 // Skip reports within the 'std' namespace. Although these can sometimes be
1649 // the user's fault, we currently don't report them very well, and
1650 // Note that this will not help for any other data structure libraries, like
1651 // TR1, Boost, or llvm/ADT.
1652 if (Options.shouldSuppressFromCXXStandardLibrary()) {
1653 BR.markInvalid(getTag(), nullptr);
1657 // If the complete 'std' suppression is not enabled, suppress reports
1658 // from the 'std' namespace that are known to produce false positives.
1660 // The analyzer issues a false use-after-free when std::list::pop_front
1661 // or std::list::pop_back are called multiple times because we cannot
1662 // reason about the internal invariants of the datastructure.
1663 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1664 const CXXRecordDecl *CD = MD->getParent();
1665 if (CD->getName() == "list") {
1666 BR.markInvalid(getTag(), nullptr);
1671 // The analyzer issues a false positive when the constructor of
1672 // std::__independent_bits_engine from algorithms is used.
1673 if (const CXXConstructorDecl *MD = dyn_cast<CXXConstructorDecl>(D)) {
1674 const CXXRecordDecl *CD = MD->getParent();
1675 if (CD->getName() == "__independent_bits_engine") {
1676 BR.markInvalid(getTag(), nullptr);
1681 for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
1682 LCtx = LCtx->getParent()) {
1683 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
1687 const CXXRecordDecl *CD = MD->getParent();
1688 // The analyzer issues a false positive on
1689 // std::basic_string<uint8_t> v; v.push_back(1);
1691 // std::u16string s; s += u'a';
1692 // because we cannot reason about the internal invariants of the
1694 if (CD->getName() == "basic_string") {
1695 BR.markInvalid(getTag(), nullptr);
1699 // The analyzer issues a false positive on
1700 // std::shared_ptr<int> p(new int(1)); p = nullptr;
1701 // because it does not reason properly about temporary destructors.
1702 if (CD->getName() == "shared_ptr") {
1703 BR.markInvalid(getTag(), nullptr);
1710 // Skip reports within the sys/queue.h macros as we do not have the ability to
1711 // reason about data structure shapes.
1712 SourceManager &SM = BRC.getSourceManager();
1713 FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1714 while (Loc.isMacroID()) {
1715 Loc = Loc.getSpellingLoc();
1716 if (SM.getFilename(Loc).endswith("sys/queue.h")) {
1717 BR.markInvalid(getTag(), nullptr);
1725 std::shared_ptr<PathDiagnosticPiece>
1726 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1727 const ExplodedNode *PrevN,
1728 BugReporterContext &BRC, BugReport &BR) {
1730 ProgramStateRef State = N->getState();
1731 ProgramPoint ProgLoc = N->getLocation();
1733 // We are only interested in visiting CallEnter nodes.
1734 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1738 // Check if one of the arguments is the region the visitor is tracking.
1739 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1740 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1742 ArrayRef<ParmVarDecl*> parms = Call->parameters();
1744 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1745 I != E; ++I, ++Idx) {
1746 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1748 // Are we tracking the argument or its subregion?
1749 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1752 // Check the function parameter type.
1753 const ParmVarDecl *ParamDecl = *I;
1754 assert(ParamDecl && "Formal parameter has no decl?");
1755 QualType T = ParamDecl->getType();
1757 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1758 // Function can only change the value passed in by address.
1762 // If it is a const pointer value, the function does not intend to
1763 // change the value.
1764 if (T->getPointeeType().isConstQualified())
1767 // Mark the call site (LocationContext) as interesting if the value of the
1768 // argument is undefined or '0'/'NULL'.
1769 SVal BoundVal = State->getSVal(R);
1770 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1771 BR.markInteresting(CEnter->getCalleeContext());
1778 std::shared_ptr<PathDiagnosticPiece>
1779 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
1780 const ExplodedNode *Pred,
1781 BugReporterContext &BRC, BugReport &BR) {
1785 auto Edge = Succ->getLocation().getAs<BlockEdge>();
1786 if (!Edge.hasValue())
1789 auto Tag = Edge->getTag();
1793 if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
1799 dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
1800 assert(Met && "Not a C++ method.");
1801 assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
1802 "Not a copy/move assignment operator.");
1804 const auto *LCtx = Edge->getLocationContext();
1806 const auto &State = Succ->getState();
1807 auto &SVB = State->getStateManager().getSValBuilder();
1810 State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
1812 State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame()));
1814 auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
1816 if (!L.isValid() || !L.asLocation().isValid())
1819 SmallString<256> Buf;
1820 llvm::raw_svector_ostream Out(Buf);
1822 Out << "Assuming " << Met->getParamDecl(0)->getName() <<
1823 ((Param == This) ? " == " : " != ") << "*this";
1825 auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
1826 Piece->addRange(Met->getSourceRange());
1828 return std::move(Piece);