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/BugReporterVisitors.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 /// Given that expression S represents a pointer that would be dereferenced,
46 /// try to find a sub-expression from which the pointer came from.
47 /// This is used for tracking down origins of a null or undefined value:
48 /// "this is null because that is null because that is null" etc.
49 /// We wipe away field and element offsets because they merely add offsets.
50 /// We also wipe away all casts except lvalue-to-rvalue casts, because the
51 /// latter represent an actual pointer dereference; however, we remove
52 /// the final lvalue-to-rvalue cast before returning from this function
53 /// because it demonstrates more clearly from where the pointer rvalue was
55 /// x->y.z ==> x (lvalue)
56 /// foo()->y.z ==> foo() (rvalue)
57 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
58 const Expr *E = dyn_cast<Expr>(S);
63 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
64 if (CE->getCastKind() == CK_LValueToRValue) {
65 // This cast represents the load we're looking for.
69 } else if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E)) {
70 // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
71 if (B->getType()->isPointerType()) {
72 if (B->getLHS()->getType()->isPointerType()) {
74 } else if (B->getRHS()->getType()->isPointerType()) {
80 // Probably more arithmetic can be pattern-matched here,
81 // but for now give up.
84 } else if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
85 if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
86 (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
87 // Operators '*' and '&' don't actually mean anything.
88 // We look at casts instead.
91 // Probably more arithmetic can be pattern-matched here,
92 // but for now give up.
96 // Pattern match for a few useful cases: a[0], p->f, *p etc.
97 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
99 } else if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
100 E = IvarRef->getBase();
101 } else if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(E)) {
103 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
104 E = PE->getSubExpr();
106 // Other arbitrary stuff.
111 // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
112 // deeper into the sub-expression. This way we return the lvalue from which
113 // our pointer rvalue was loaded.
114 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
115 if (CE->getCastKind() == CK_LValueToRValue)
116 E = CE->getSubExpr();
121 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
122 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
123 if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(S))
128 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
129 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
130 if (const ReturnStmt *RS = dyn_cast<ReturnStmt>(S))
131 return RS->getRetValue();
135 //===----------------------------------------------------------------------===//
136 // Definitions for bug reporter visitors.
137 //===----------------------------------------------------------------------===//
139 std::unique_ptr<PathDiagnosticPiece>
140 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
141 const ExplodedNode *EndPathNode, BugReport &BR) {
145 std::unique_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
146 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
147 PathDiagnosticLocation L =
148 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
150 const auto &Ranges = BR.getRanges();
152 // Only add the statement itself as a range if we didn't specify any
153 // special ranges for this report.
154 auto P = llvm::make_unique<PathDiagnosticEventPiece>(
155 L, BR.getDescription(), Ranges.begin() == Ranges.end());
156 for (SourceRange Range : Ranges)
164 /// Emits an extra note at the return statement of an interesting stack frame.
166 /// The returned value is marked as an interesting value, and if it's null,
167 /// adds a visitor to track where it became null.
169 /// This visitor is intended to be used when another visitor discovers that an
170 /// interesting value comes from an inlined function call.
171 class ReturnVisitor : public BugReporterVisitorImpl<ReturnVisitor> {
172 const StackFrameContext *StackFrame;
179 bool EnableNullFPSuppression;
182 ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
183 : StackFrame(Frame), Mode(Initial), EnableNullFPSuppression(Suppressed) {}
185 static void *getTag() {
187 return static_cast<void *>(&Tag);
190 void Profile(llvm::FoldingSetNodeID &ID) const override {
191 ID.AddPointer(ReturnVisitor::getTag());
192 ID.AddPointer(StackFrame);
193 ID.AddBoolean(EnableNullFPSuppression);
196 /// Adds a ReturnVisitor if the given statement represents a call that was
199 /// This will search back through the ExplodedGraph, starting from the given
200 /// node, looking for when the given statement was processed. If it turns out
201 /// the statement is a call that was inlined, we add the visitor to the
202 /// bug report, so it can print a note later.
203 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
205 bool InEnableNullFPSuppression) {
206 if (!CallEvent::isCallStmt(S))
209 // First, find when we processed the statement.
211 if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
212 if (CEE->getCalleeContext()->getCallSite() == S)
214 if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
215 if (SP->getStmt() == S)
218 Node = Node->getFirstPred();
221 // Next, step over any post-statement checks.
222 while (Node && Node->getLocation().getAs<PostStmt>())
223 Node = Node->getFirstPred();
227 // Finally, see if we inlined the call.
228 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
232 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
233 if (CalleeContext->getCallSite() != S)
236 // Check the return value.
237 ProgramStateRef State = Node->getState();
238 SVal RetVal = State->getSVal(S, Node->getLocationContext());
240 // Handle cases where a reference is returned and then immediately used.
241 if (cast<Expr>(S)->isGLValue())
242 if (Optional<Loc> LValue = RetVal.getAs<Loc>())
243 RetVal = State->getSVal(*LValue);
245 // See if the return value is NULL. If so, suppress the report.
246 SubEngine *Eng = State->getStateManager().getOwningEngine();
247 assert(Eng && "Cannot file a bug report without an owning engine");
248 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
250 bool EnableNullFPSuppression = false;
251 if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
252 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
253 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
255 BR.markInteresting(CalleeContext);
256 BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
257 EnableNullFPSuppression));
260 /// Returns true if any counter-suppression heuristics are enabled for
262 static bool hasCounterSuppression(AnalyzerOptions &Options) {
263 return Options.shouldAvoidSuppressingNullArgumentPaths();
266 std::shared_ptr<PathDiagnosticPiece>
267 visitNodeInitial(const ExplodedNode *N, const ExplodedNode *PrevN,
268 BugReporterContext &BRC, BugReport &BR) {
269 // Only print a message at the interesting return statement.
270 if (N->getLocationContext() != StackFrame)
273 Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
277 const ReturnStmt *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
281 // Okay, we're at the right return statement, but do we have the return
283 ProgramStateRef State = N->getState();
284 SVal V = State->getSVal(Ret, StackFrame);
285 if (V.isUnknownOrUndef())
288 // Don't print any more notes after this one.
291 const Expr *RetE = Ret->getRetValue();
292 assert(RetE && "Tracking a return value for a void function");
294 // Handle cases where a reference is returned and then immediately used.
295 Optional<Loc> LValue;
296 if (RetE->isGLValue()) {
297 if ((LValue = V.getAs<Loc>())) {
298 SVal RValue = State->getRawSVal(*LValue, RetE->getType());
299 if (RValue.getAs<DefinedSVal>())
304 // Ignore aggregate rvalues.
305 if (V.getAs<nonloc::LazyCompoundVal>() ||
306 V.getAs<nonloc::CompoundVal>())
309 RetE = RetE->IgnoreParenCasts();
311 // If we can't prove the return value is 0, just mark it interesting, and
312 // make sure to track it into any further inner functions.
313 if (!State->isNull(V).isConstrainedTrue()) {
314 BR.markInteresting(V);
315 ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
316 EnableNullFPSuppression);
320 // If we're returning 0, we should track where that 0 came from.
321 bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
322 EnableNullFPSuppression);
324 // Build an appropriate message based on the return value.
326 llvm::raw_svector_ostream Out(Msg);
328 if (V.getAs<Loc>()) {
329 // If we have counter-suppression enabled, make sure we keep visiting
330 // future nodes. We want to emit a path note as well, in case
331 // the report is resurrected as valid later on.
332 ExprEngine &Eng = BRC.getBugReporter().getEngine();
333 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
334 if (EnableNullFPSuppression && hasCounterSuppression(Options))
335 Mode = MaybeUnsuppress;
337 if (RetE->getType()->isObjCObjectPointerType())
338 Out << "Returning nil";
340 Out << "Returning null pointer";
342 Out << "Returning zero";
346 if (const MemRegion *MR = LValue->getAsRegion()) {
347 if (MR->canPrintPretty()) {
348 Out << " (reference to ";
349 MR->printPretty(Out);
354 // FIXME: We should have a more generalized location printing mechanism.
355 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetE))
356 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
357 Out << " (loaded from '" << *DD << "')";
360 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
361 if (!L.isValid() || !L.asLocation().isValid())
364 return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
367 std::shared_ptr<PathDiagnosticPiece>
368 visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
369 BugReporterContext &BRC, BugReport &BR) {
371 ExprEngine &Eng = BRC.getBugReporter().getEngine();
372 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
373 assert(hasCounterSuppression(Options));
376 // Are we at the entry node for this call?
377 Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
381 if (CE->getCalleeContext() != StackFrame)
386 // Don't automatically suppress a report if one of the arguments is
387 // known to be a null pointer. Instead, start tracking /that/ null
388 // value back to its origin.
389 ProgramStateManager &StateMgr = BRC.getStateManager();
390 CallEventManager &CallMgr = StateMgr.getCallEventManager();
392 ProgramStateRef State = N->getState();
393 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
394 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
395 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
399 const Expr *ArgE = Call->getArgExpr(I);
403 // Is it possible for this argument to be non-null?
404 if (!State->isNull(*ArgV).isConstrainedTrue())
407 if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
408 EnableNullFPSuppression))
409 BR.removeInvalidation(ReturnVisitor::getTag(), StackFrame);
411 // If we /can't/ track the null pointer, we should err on the side of
412 // false negatives, and continue towards marking this report invalid.
413 // (We will still look at the other arguments, though.)
419 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
420 const ExplodedNode *PrevN,
421 BugReporterContext &BRC,
422 BugReport &BR) override {
425 return visitNodeInitial(N, PrevN, BRC, BR);
426 case MaybeUnsuppress:
427 return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
432 llvm_unreachable("Invalid visit mode!");
435 std::unique_ptr<PathDiagnosticPiece> getEndPath(BugReporterContext &BRC,
436 const ExplodedNode *N,
437 BugReport &BR) override {
438 if (EnableNullFPSuppression)
439 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
443 } // end anonymous namespace
446 void FindLastStoreBRVisitor ::Profile(llvm::FoldingSetNodeID &ID) const {
451 ID.AddBoolean(EnableNullFPSuppression);
454 /// Returns true if \p N represents the DeclStmt declaring and initializing
456 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
457 Optional<PostStmt> P = N->getLocationAs<PostStmt>();
461 const DeclStmt *DS = P->getStmtAs<DeclStmt>();
465 if (DS->getSingleDecl() != VR->getDecl())
468 const MemSpaceRegion *VarSpace = VR->getMemorySpace();
469 const StackSpaceRegion *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
471 // If we ever directly evaluate global DeclStmts, this assertion will be
472 // invalid, but this still seems preferable to silently accepting an
473 // initialization that may be for a path-sensitive variable.
474 assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
478 assert(VR->getDecl()->hasLocalStorage());
479 const LocationContext *LCtx = N->getLocationContext();
480 return FrameSpace->getStackFrame() == LCtx->getCurrentStackFrame();
483 std::shared_ptr<PathDiagnosticPiece>
484 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
485 const ExplodedNode *Pred,
486 BugReporterContext &BRC, BugReport &BR) {
491 const ExplodedNode *StoreSite = nullptr;
492 const Expr *InitE = nullptr;
493 bool IsParam = false;
495 // First see if we reached the declaration of the region.
496 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
497 if (isInitializationOfVar(Pred, VR)) {
499 InitE = VR->getDecl()->getInit();
503 // If this is a post initializer expression, initializing the region, we
504 // should track the initializer expression.
505 if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
506 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
507 if (FieldReg && FieldReg == R) {
509 InitE = PIP->getInitializer()->getInit();
513 // Otherwise, see if this is the store site:
514 // (1) Succ has this binding and Pred does not, i.e. this is
515 // where the binding first occurred.
516 // (2) Succ has this binding and is a PostStore node for this region, i.e.
517 // the same binding was re-assigned here.
519 if (Succ->getState()->getSVal(R) != V)
522 if (Pred->getState()->getSVal(R) == V) {
523 Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
524 if (!PS || PS->getLocationValue() != R)
530 // If this is an assignment expression, we can track the value
532 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
533 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
534 if (BO->isAssignmentOp())
535 InitE = BO->getRHS();
537 // If this is a call entry, the variable should be a parameter.
538 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
539 // 'this' should never be NULL, but this visitor isn't just for NULL and
541 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
542 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
543 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
545 ProgramStateManager &StateMgr = BRC.getStateManager();
546 CallEventManager &CallMgr = StateMgr.getCallEventManager();
548 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
550 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
555 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
556 // is wrapped inside of it.
557 if (const CXXTempObjectRegion *TmpR = dyn_cast<CXXTempObjectRegion>(R))
558 InitE = TmpR->getExpr();
565 // If we have an expression that provided the value, try to track where it
569 V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
571 InitE = InitE->IgnoreParenCasts();
572 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
573 EnableNullFPSuppression);
575 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
576 BR, EnableNullFPSuppression);
580 // Okay, we've found the binding. Emit an appropriate message.
581 SmallString<256> sbuf;
582 llvm::raw_svector_ostream os(sbuf);
584 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
585 const Stmt *S = PS->getStmt();
586 const char *action = nullptr;
587 const DeclStmt *DS = dyn_cast<DeclStmt>(S);
588 const VarRegion *VR = dyn_cast<VarRegion>(R);
591 action = R->canPrintPretty() ? "initialized to " :
593 } else if (isa<BlockExpr>(S)) {
594 action = R->canPrintPretty() ? "captured by block as " :
595 "Captured by block as ";
597 // See if we can get the BlockVarRegion.
598 ProgramStateRef State = StoreSite->getState();
599 SVal V = State->getSVal(S, PS->getLocationContext());
600 if (const BlockDataRegion *BDR =
601 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
602 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
603 if (Optional<KnownSVal> KV =
604 State->getSVal(OriginalR).getAs<KnownSVal>())
605 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
606 *KV, OriginalR, EnableNullFPSuppression));
613 if (R->canPrintPretty()) {
618 if (V.getAs<loc::ConcreteInt>()) {
620 if (R->isBoundable()) {
621 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
622 if (TR->getValueType()->isObjCObjectPointerType()) {
623 os << action << "nil";
630 os << action << "a null pointer value";
631 } else if (Optional<nonloc::ConcreteInt> CVal =
632 V.getAs<nonloc::ConcreteInt>()) {
633 os << action << CVal->getValue();
637 if (isa<VarRegion>(R)) {
638 const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl());
640 os << (R->canPrintPretty() ? "initialized" : "Initializing")
641 << " to a garbage value";
643 os << (R->canPrintPretty() ? "declared" : "Declaring")
644 << " without an initial value";
649 os << (R->canPrintPretty() ? "initialized" : "Initialized")
654 } else if (StoreSite->getLocation().getAs<CallEnter>()) {
655 if (const VarRegion *VR = dyn_cast<VarRegion>(R)) {
656 const ParmVarDecl *Param = cast<ParmVarDecl>(VR->getDecl());
660 if (V.getAs<loc::ConcreteInt>()) {
661 if (Param->getType()->isObjCObjectPointerType())
662 os << "nil object reference";
664 os << "null pointer value";
665 } else if (V.isUndef()) {
666 os << "uninitialized value";
667 } else if (Optional<nonloc::ConcreteInt> CI =
668 V.getAs<nonloc::ConcreteInt>()) {
669 os << "the value " << CI->getValue();
674 // Printed parameter indexes are 1-based, not 0-based.
675 unsigned Idx = Param->getFunctionScopeIndex() + 1;
676 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
677 if (R->canPrintPretty()) {
684 if (os.str().empty()) {
685 if (V.getAs<loc::ConcreteInt>()) {
687 if (R->isBoundable()) {
688 if (const TypedValueRegion *TR = dyn_cast<TypedValueRegion>(R)) {
689 if (TR->getValueType()->isObjCObjectPointerType()) {
690 os << "nil object reference stored";
696 if (R->canPrintPretty())
697 os << "Null pointer value stored";
699 os << "Storing null pointer value";
702 } else if (V.isUndef()) {
703 if (R->canPrintPretty())
704 os << "Uninitialized value stored";
706 os << "Storing uninitialized value";
708 } else if (Optional<nonloc::ConcreteInt> CV =
709 V.getAs<nonloc::ConcreteInt>()) {
710 if (R->canPrintPretty())
711 os << "The value " << CV->getValue() << " is assigned";
713 os << "Assigning " << CV->getValue();
716 if (R->canPrintPretty())
717 os << "Value assigned";
719 os << "Assigning value";
722 if (R->canPrintPretty()) {
728 // Construct a new PathDiagnosticPiece.
729 ProgramPoint P = StoreSite->getLocation();
730 PathDiagnosticLocation L;
731 if (P.getAs<CallEnter>() && InitE)
732 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
733 P.getLocationContext());
735 if (!L.isValid() || !L.asLocation().isValid())
736 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
738 if (!L.isValid() || !L.asLocation().isValid())
741 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
744 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
747 ID.AddBoolean(Assumption);
751 /// Return the tag associated with this visitor. This tag will be used
752 /// to make all PathDiagnosticPieces created by this visitor.
753 const char *TrackConstraintBRVisitor::getTag() {
754 return "TrackConstraintBRVisitor";
757 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
759 return N->getState()->isNull(Constraint).isUnderconstrained();
760 return (bool)N->getState()->assume(Constraint, !Assumption);
763 std::shared_ptr<PathDiagnosticPiece>
764 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
765 const ExplodedNode *PrevN,
766 BugReporterContext &BRC, BugReport &BR) {
770 // Start tracking after we see the first state in which the value is
772 if (!IsTrackingTurnedOn)
773 if (!isUnderconstrained(N))
774 IsTrackingTurnedOn = true;
775 if (!IsTrackingTurnedOn)
778 // Check if in the previous state it was feasible for this constraint
780 if (isUnderconstrained(PrevN)) {
784 // As a sanity check, make sure that the negation of the constraint
785 // was infeasible in the current state. If it is feasible, we somehow
786 // missed the transition point.
787 assert(!isUnderconstrained(N));
789 // We found the transition point for the constraint. We now need to
790 // pretty-print the constraint. (work-in-progress)
791 SmallString<64> sbuf;
792 llvm::raw_svector_ostream os(sbuf);
794 if (Constraint.getAs<Loc>()) {
795 os << "Assuming pointer value is ";
796 os << (Assumption ? "non-null" : "null");
799 if (os.str().empty())
802 // Construct a new PathDiagnosticPiece.
803 ProgramPoint P = N->getLocation();
804 PathDiagnosticLocation L =
805 PathDiagnosticLocation::create(P, BRC.getSourceManager());
809 auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
817 SuppressInlineDefensiveChecksVisitor::
818 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
819 : V(Value), IsSatisfied(false), IsTrackingTurnedOn(false) {
821 // Check if the visitor is disabled.
822 SubEngine *Eng = N->getState()->getStateManager().getOwningEngine();
823 assert(Eng && "Cannot file a bug report without an owning engine");
824 AnalyzerOptions &Options = Eng->getAnalysisManager().options;
825 if (!Options.shouldSuppressInlinedDefensiveChecks())
828 assert(N->getState()->isNull(V).isConstrainedTrue() &&
829 "The visitor only tracks the cases where V is constrained to 0");
832 void SuppressInlineDefensiveChecksVisitor::Profile(FoldingSetNodeID &ID) const {
838 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
842 std::shared_ptr<PathDiagnosticPiece>
843 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
844 const ExplodedNode *Pred,
845 BugReporterContext &BRC,
850 // Start tracking after we see the first state in which the value is null.
851 if (!IsTrackingTurnedOn)
852 if (Succ->getState()->isNull(V).isConstrainedTrue())
853 IsTrackingTurnedOn = true;
854 if (!IsTrackingTurnedOn)
857 // Check if in the previous state it was feasible for this value
859 if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
862 assert(Succ->getState()->isNull(V).isConstrainedTrue());
864 // Check if this is inlined defensive checks.
865 const LocationContext *CurLC =Succ->getLocationContext();
866 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
867 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
868 BR.markInvalid("Suppress IDC", CurLC);
872 // Treat defensive checks in function-like macros as if they were an inlined
873 // defensive check. If the bug location is not in a macro and the
874 // terminator for the current location is in a macro then suppress the
876 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
881 SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
882 if (BugLoc.isMacroID())
885 ProgramPoint CurPoint = Succ->getLocation();
886 const Stmt *CurTerminatorStmt = nullptr;
887 if (auto BE = CurPoint.getAs<BlockEdge>()) {
888 CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
889 } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
890 const Stmt *CurStmt = SP->getStmt();
891 if (!CurStmt->getLocStart().isMacroID())
894 CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
895 CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
900 if (!CurTerminatorStmt)
903 SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
904 if (TerminatorLoc.isMacroID()) {
905 const SourceManager &SMgr = BRC.getSourceManager();
906 std::pair<FileID, unsigned> TLInfo = SMgr.getDecomposedLoc(TerminatorLoc);
907 SrcMgr::SLocEntry SE = SMgr.getSLocEntry(TLInfo.first);
908 const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
909 if (EInfo.isFunctionMacroExpansion()) {
910 BR.markInvalid("Suppress Macro IDC", CurLC);
918 static const MemRegion *getLocationRegionIfReference(const Expr *E,
919 const ExplodedNode *N) {
920 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
921 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
922 if (!VD->getType()->isReferenceType())
924 ProgramStateManager &StateMgr = N->getState()->getStateManager();
925 MemRegionManager &MRMgr = StateMgr.getRegionManager();
926 return MRMgr.getVarRegion(VD, N->getLocationContext());
930 // FIXME: This does not handle other kinds of null references,
931 // for example, references from FieldRegions:
932 // struct Wrapper { int &ref; };
933 // Wrapper w = { *(int *)0 };
939 static const Expr *peelOffOuterExpr(const Expr *Ex,
940 const ExplodedNode *N) {
941 Ex = Ex->IgnoreParenCasts();
942 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Ex))
943 return peelOffOuterExpr(EWC->getSubExpr(), N);
944 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Ex))
945 return peelOffOuterExpr(OVE->getSourceExpr(), N);
946 if (auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
947 auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
948 if (PropRef && PropRef->isMessagingGetter()) {
949 const Expr *GetterMessageSend =
950 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
951 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
952 return peelOffOuterExpr(GetterMessageSend, N);
956 // Peel off the ternary operator.
957 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Ex)) {
958 // Find a node where the branching occurred and find out which branch
959 // we took (true/false) by looking at the ExplodedGraph.
960 const ExplodedNode *NI = N;
962 ProgramPoint ProgPoint = NI->getLocation();
963 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
964 const CFGBlock *srcBlk = BE->getSrc();
965 if (const Stmt *term = srcBlk->getTerminator()) {
967 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
969 return peelOffOuterExpr(CO->getTrueExpr(), N);
971 return peelOffOuterExpr(CO->getFalseExpr(), N);
975 NI = NI->getFirstPred();
981 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
983 BugReport &report, bool IsArg,
984 bool EnableNullFPSuppression) {
988 if (const Expr *Ex = dyn_cast<Expr>(S)) {
989 Ex = Ex->IgnoreParenCasts();
990 const Expr *PeeledEx = peelOffOuterExpr(Ex, N);
995 const Expr *Inner = nullptr;
996 if (const Expr *Ex = dyn_cast<Expr>(S)) {
997 Ex = Ex->IgnoreParenCasts();
999 // Performing operator `&' on an lvalue expression is essentially a no-op.
1000 // Then, if we are taking addresses of fields or elements, these are also
1001 // unlikely to matter.
1002 // FIXME: There's a hack in our Store implementation that always computes
1003 // field offsets around null pointers as if they are always equal to 0.
1004 // The idea here is to report accesses to fields as null dereferences
1005 // even though the pointer value that's being dereferenced is actually
1006 // the offset of the field rather than exactly 0.
1007 // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1008 // This code interacts heavily with this hack; otherwise the value
1009 // would not be null at all for most fields, so we'd be unable to track it.
1010 if (const auto *Op = dyn_cast<UnaryOperator>(Ex))
1011 if (Op->getOpcode() == UO_AddrOf && Op->getSubExpr()->isLValue())
1012 if (const Expr *DerefEx = getDerefExpr(Op->getSubExpr()))
1015 if (Ex && (ExplodedGraph::isInterestingLValueExpr(Ex) || CallEvent::isCallStmt(Ex)))
1019 if (IsArg && !Inner) {
1020 assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
1022 // Walk through nodes until we get one that matches the statement exactly.
1023 // Alternately, if we hit a known lvalue for the statement, we know we've
1024 // gone too far (though we can likely track the lvalue better anyway).
1026 const ProgramPoint &pp = N->getLocation();
1027 if (Optional<StmtPoint> ps = pp.getAs<StmtPoint>()) {
1028 if (ps->getStmt() == S || ps->getStmt() == Inner)
1030 } else if (Optional<CallExitEnd> CEE = pp.getAs<CallExitEnd>()) {
1031 if (CEE->getCalleeContext()->getCallSite() == S ||
1032 CEE->getCalleeContext()->getCallSite() == Inner)
1035 N = N->getFirstPred();
1042 ProgramStateRef state = N->getState();
1044 // The message send could be nil due to the receiver being nil.
1045 // At this point in the path, the receiver should be live since we are at the
1046 // message send expr. If it is nil, start tracking it.
1047 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
1048 trackNullOrUndefValue(N, Receiver, report, false, EnableNullFPSuppression);
1051 // See if the expression we're interested refers to a variable.
1052 // If so, we can track both its contents and constraints on its value.
1053 if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
1054 const MemRegion *R = nullptr;
1056 // Find the ExplodedNode where the lvalue (the value of 'Ex')
1057 // was computed. We need this for getting the location value.
1058 const ExplodedNode *LVNode = N;
1060 if (Optional<PostStmt> P = LVNode->getLocation().getAs<PostStmt>()) {
1061 if (P->getStmt() == Inner)
1064 LVNode = LVNode->getFirstPred();
1066 assert(LVNode && "Unable to find the lvalue node.");
1067 ProgramStateRef LVState = LVNode->getState();
1068 SVal LVal = LVState->getSVal(Inner, LVNode->getLocationContext());
1070 if (LVState->isNull(LVal).isConstrainedTrue()) {
1071 // In case of C++ references, we want to differentiate between a null
1072 // reference and reference to null pointer.
1073 // If the LVal is null, check if we are dealing with null reference.
1074 // For those, we want to track the location of the reference.
1075 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N))
1078 R = LVState->getSVal(Inner, LVNode->getLocationContext()).getAsRegion();
1080 // If this is a C++ reference to a null pointer, we are tracking the
1081 // pointer. In addition, we should find the store at which the reference
1083 if (const MemRegion *RR = getLocationRegionIfReference(Inner, N)) {
1084 if (Optional<KnownSVal> KV = LVal.getAs<KnownSVal>())
1085 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1086 *KV, RR, EnableNullFPSuppression));
1091 // Mark both the variable region and its contents as interesting.
1092 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1094 report.markInteresting(R);
1095 report.markInteresting(V);
1096 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1098 // If the contents are symbolic, find out when they became null.
1099 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1100 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1101 V.castAs<DefinedSVal>(), false));
1103 // Add visitor, which will suppress inline defensive checks.
1104 if (Optional<DefinedSVal> DV = V.getAs<DefinedSVal>()) {
1105 if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1106 EnableNullFPSuppression) {
1108 llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1113 if (Optional<KnownSVal> KV = V.getAs<KnownSVal>())
1114 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1115 *KV, R, EnableNullFPSuppression));
1120 // If the expression is not an "lvalue expression", we can still
1121 // track the constraints on its contents.
1122 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1124 // If the value came from an inlined function call, we should at least make
1125 // sure that function isn't pruned in our output.
1126 if (const Expr *E = dyn_cast<Expr>(S))
1127 S = E->IgnoreParenCasts();
1129 ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1131 // Uncomment this to find cases where we aren't properly getting the
1132 // base value that was dereferenced.
1133 // assert(!V.isUnknownOrUndef());
1134 // Is it a symbolic value?
1135 if (Optional<loc::MemRegionVal> L = V.getAs<loc::MemRegionVal>()) {
1136 // At this point we are dealing with the region's LValue.
1137 // However, if the rvalue is a symbolic region, we should track it as well.
1138 // Try to use the correct type when looking up the value.
1140 if (const Expr *E = dyn_cast<Expr>(S))
1141 RVal = state->getRawSVal(L.getValue(), E->getType());
1143 RVal = state->getSVal(L->getRegion());
1145 const MemRegion *RegionRVal = RVal.getAsRegion();
1146 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1148 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1149 report.markInteresting(RegionRVal);
1150 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1151 loc::MemRegionVal(RegionRVal), false));
1158 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1159 const ExplodedNode *N) {
1160 const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
1163 if (const Expr *Receiver = ME->getInstanceReceiver()) {
1164 ProgramStateRef state = N->getState();
1165 SVal V = state->getSVal(Receiver, N->getLocationContext());
1166 if (state->isNull(V).isConstrainedTrue())
1172 std::shared_ptr<PathDiagnosticPiece>
1173 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1174 const ExplodedNode *PrevN,
1175 BugReporterContext &BRC, BugReport &BR) {
1176 Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1180 const Stmt *S = P->getStmt();
1181 const Expr *Receiver = getNilReceiver(S, N);
1185 llvm::SmallString<256> Buf;
1186 llvm::raw_svector_ostream OS(Buf);
1188 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
1190 ME->getSelector().print(OS);
1191 OS << "' not called";
1194 OS << "No method is called";
1196 OS << " because the receiver is nil";
1198 // The receiver was nil, and hence the method was skipped.
1199 // Register a BugReporterVisitor to issue a message telling us how
1200 // the receiver was null.
1201 bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1202 /*EnableNullFPSuppression*/ false);
1203 // Issue a message saying that the method was skipped.
1204 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1205 N->getLocationContext());
1206 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1209 // Registers every VarDecl inside a Stmt with a last store visitor.
1210 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1212 bool EnableNullFPSuppression) {
1213 const ExplodedNode *N = BR.getErrorNode();
1214 std::deque<const Stmt *> WorkList;
1215 WorkList.push_back(S);
1217 while (!WorkList.empty()) {
1218 const Stmt *Head = WorkList.front();
1219 WorkList.pop_front();
1221 ProgramStateRef state = N->getState();
1222 ProgramStateManager &StateMgr = state->getStateManager();
1224 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Head)) {
1225 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1226 const VarRegion *R =
1227 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1229 // What did we load?
1230 SVal V = state->getSVal(S, N->getLocationContext());
1232 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1233 // Register a new visitor with the BugReport.
1234 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1235 V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1240 for (const Stmt *SubStmt : Head->children())
1241 WorkList.push_back(SubStmt);
1245 //===----------------------------------------------------------------------===//
1246 // Visitor that tries to report interesting diagnostics from conditions.
1247 //===----------------------------------------------------------------------===//
1249 /// Return the tag associated with this visitor. This tag will be used
1250 /// to make all PathDiagnosticPieces created by this visitor.
1251 const char *ConditionBRVisitor::getTag() {
1252 return "ConditionBRVisitor";
1255 std::shared_ptr<PathDiagnosticPiece>
1256 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
1257 BugReporterContext &BRC, BugReport &BR) {
1258 auto piece = VisitNodeImpl(N, Prev, BRC, BR);
1260 piece->setTag(getTag());
1261 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1262 ev->setPrunable(true, /* override */ false);
1267 std::shared_ptr<PathDiagnosticPiece>
1268 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1269 const ExplodedNode *Prev,
1270 BugReporterContext &BRC, BugReport &BR) {
1272 ProgramPoint progPoint = N->getLocation();
1273 ProgramStateRef CurrentState = N->getState();
1274 ProgramStateRef PrevState = Prev->getState();
1276 // Compare the GDMs of the state, because that is where constraints
1277 // are managed. Note that ensure that we only look at nodes that
1278 // were generated by the analyzer engine proper, not checkers.
1279 if (CurrentState->getGDM().getRoot() ==
1280 PrevState->getGDM().getRoot())
1283 // If an assumption was made on a branch, it should be caught
1284 // here by looking at the state transition.
1285 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1286 const CFGBlock *srcBlk = BE->getSrc();
1287 if (const Stmt *term = srcBlk->getTerminator())
1288 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1292 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1293 // FIXME: Assuming that BugReporter is a GRBugReporter is a layering
1295 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1296 cast<GRBugReporter>(BRC.getBugReporter()).
1297 getEngine().geteagerlyAssumeBinOpBifurcationTags();
1299 const ProgramPointTag *tag = PS->getTag();
1300 if (tag == tags.first)
1301 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1303 if (tag == tags.second)
1304 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1313 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1314 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1315 const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1316 const Expr *Cond = nullptr;
1318 // In the code below, Term is a CFG terminator and Cond is a branch condition
1319 // expression upon which the decision is made on this terminator.
1321 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1322 // and "x == 0" is the respective condition.
1324 // Another example: in "if (x && y)", we've got two terminators and two
1325 // conditions due to short-circuit nature of operator "&&":
1326 // 1. The "if (x && y)" statement is a terminator,
1327 // and "y" is the respective condition.
1328 // 2. Also "x && ..." is another terminator,
1329 // and "x" is its condition.
1331 switch (Term->getStmtClass()) {
1332 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1333 // more tricky because there are more than two branches to account for.
1336 case Stmt::IfStmtClass:
1337 Cond = cast<IfStmt>(Term)->getCond();
1339 case Stmt::ConditionalOperatorClass:
1340 Cond = cast<ConditionalOperator>(Term)->getCond();
1342 case Stmt::BinaryOperatorClass:
1343 // When we encounter a logical operator (&& or ||) as a CFG terminator,
1344 // then the condition is actually its LHS; otherwise, we'd encounter
1345 // the parent, such as if-statement, as a terminator.
1346 const auto *BO = cast<BinaryOperator>(Term);
1347 assert(BO->isLogicalOp() &&
1348 "CFG terminator is not a short-circuit operator!");
1349 Cond = BO->getLHS();
1353 // However, when we encounter a logical operator as a branch condition,
1354 // then the condition is actually its RHS, because LHS would be
1355 // the condition for the logical operator terminator.
1356 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1357 if (!InnerBO->isLogicalOp())
1359 Cond = InnerBO->getRHS()->IgnoreParens();
1363 assert(srcBlk->succ_size() == 2);
1364 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1365 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1368 std::shared_ptr<PathDiagnosticPiece>
1369 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1370 BugReporterContext &BRC, BugReport &R,
1371 const ExplodedNode *N) {
1372 // These will be modified in code below, but we need to preserve the original
1373 // values in case we want to throw the generic message.
1374 const Expr *CondTmp = Cond;
1375 bool tookTrueTmp = tookTrue;
1378 CondTmp = CondTmp->IgnoreParenCasts();
1379 switch (CondTmp->getStmtClass()) {
1382 case Stmt::BinaryOperatorClass:
1383 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1384 tookTrueTmp, BRC, R, N))
1387 case Stmt::DeclRefExprClass:
1388 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1389 tookTrueTmp, BRC, R, N))
1392 case Stmt::UnaryOperatorClass: {
1393 const UnaryOperator *UO = cast<UnaryOperator>(CondTmp);
1394 if (UO->getOpcode() == UO_LNot) {
1395 tookTrueTmp = !tookTrueTmp;
1396 CondTmp = UO->getSubExpr();
1405 // Condition too complex to explain? Just say something so that the user
1406 // knew we've made some path decision at this point.
1407 const LocationContext *LCtx = N->getLocationContext();
1408 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1409 if (!Loc.isValid() || !Loc.asLocation().isValid())
1412 return std::make_shared<PathDiagnosticEventPiece>(
1413 Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1416 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1417 const Expr *ParentEx,
1419 BugReporterContext &BRC,
1421 const ExplodedNode *N,
1422 Optional<bool> &prunable) {
1423 const Expr *OriginalExpr = Ex;
1424 Ex = Ex->IgnoreParenCasts();
1426 // Use heuristics to determine if Ex is a macro expending to a literal and
1427 // if so, use the macro's name.
1428 SourceLocation LocStart = Ex->getLocStart();
1429 SourceLocation LocEnd = Ex->getLocEnd();
1430 if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1431 (isa<GNUNullExpr>(Ex) ||
1432 isa<ObjCBoolLiteralExpr>(Ex) ||
1433 isa<CXXBoolLiteralExpr>(Ex) ||
1434 isa<IntegerLiteral>(Ex) ||
1435 isa<FloatingLiteral>(Ex))) {
1437 StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1438 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1439 StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1440 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1441 bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1443 bool partOfParentMacro = false;
1444 if (ParentEx->getLocStart().isMacroID()) {
1445 StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
1446 ParentEx->getLocStart(), BRC.getSourceManager(),
1447 BRC.getASTContext().getLangOpts());
1448 partOfParentMacro = PName.equals(StartName);
1451 if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
1452 // Get the location of the macro name as written by the caller.
1453 SourceLocation Loc = LocStart;
1454 while (LocStart.isMacroID()) {
1456 LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
1458 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
1459 Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1461 // Return the macro name.
1467 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex)) {
1468 const bool quotes = isa<VarDecl>(DR->getDecl());
1471 const LocationContext *LCtx = N->getLocationContext();
1472 const ProgramState *state = N->getState().get();
1473 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1474 LCtx).getAsRegion()) {
1475 if (report.isInteresting(R))
1478 const ProgramState *state = N->getState().get();
1479 SVal V = state->getSVal(R);
1480 if (report.isInteresting(V))
1485 Out << DR->getDecl()->getDeclName().getAsString();
1491 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Ex)) {
1492 QualType OriginalTy = OriginalExpr->getType();
1493 if (OriginalTy->isPointerType()) {
1494 if (IL->getValue() == 0) {
1499 else if (OriginalTy->isObjCObjectPointerType()) {
1500 if (IL->getValue() == 0) {
1506 Out << IL->getValue();
1513 std::shared_ptr<PathDiagnosticPiece>
1514 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
1515 const bool tookTrue, BugReporterContext &BRC,
1516 BugReport &R, const ExplodedNode *N) {
1518 bool shouldInvert = false;
1519 Optional<bool> shouldPrune;
1521 SmallString<128> LhsString, RhsString;
1523 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
1524 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
1525 BRC, R, N, shouldPrune);
1526 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
1527 BRC, R, N, shouldPrune);
1529 shouldInvert = !isVarLHS && isVarRHS;
1532 BinaryOperator::Opcode Op = BExpr->getOpcode();
1534 if (BinaryOperator::isAssignmentOp(Op)) {
1535 // For assignment operators, all that we care about is that the LHS
1536 // evaluates to "true" or "false".
1537 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
1541 // For non-assignment operations, we require that we can understand
1542 // both the LHS and RHS.
1543 if (LhsString.empty() || RhsString.empty() ||
1544 !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
1547 // Should we invert the strings if the LHS is not a variable name?
1548 SmallString<256> buf;
1549 llvm::raw_svector_ostream Out(buf);
1550 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
1552 // Do we need to invert the opcode?
1556 case BO_LT: Op = BO_GT; break;
1557 case BO_GT: Op = BO_LT; break;
1558 case BO_LE: Op = BO_GE; break;
1559 case BO_GE: Op = BO_LE; break;
1564 case BO_EQ: Op = BO_NE; break;
1565 case BO_NE: Op = BO_EQ; break;
1566 case BO_LT: Op = BO_GE; break;
1567 case BO_GT: Op = BO_LE; break;
1568 case BO_LE: Op = BO_GT; break;
1569 case BO_GE: Op = BO_LT; break;
1579 Out << "not equal to ";
1582 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
1586 Out << (shouldInvert ? LhsString : RhsString);
1587 const LocationContext *LCtx = N->getLocationContext();
1588 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1589 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1590 if (shouldPrune.hasValue())
1591 event->setPrunable(shouldPrune.getValue());
1595 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
1596 StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
1597 BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
1598 // FIXME: If there's already a constraint tracker for this variable,
1599 // we shouldn't emit anything here (c.f. the double note in
1600 // test/Analysis/inlining/path-notes.c)
1601 SmallString<256> buf;
1602 llvm::raw_svector_ostream Out(buf);
1603 Out << "Assuming " << LhsString << " is ";
1605 QualType Ty = CondVarExpr->getType();
1607 if (Ty->isPointerType())
1608 Out << (tookTrue ? "not null" : "null");
1609 else if (Ty->isObjCObjectPointerType())
1610 Out << (tookTrue ? "not nil" : "nil");
1611 else if (Ty->isBooleanType())
1612 Out << (tookTrue ? "true" : "false");
1613 else if (Ty->isIntegralOrEnumerationType())
1614 Out << (tookTrue ? "non-zero" : "zero");
1618 const LocationContext *LCtx = N->getLocationContext();
1619 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
1620 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1622 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
1623 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1624 const ProgramState *state = N->getState().get();
1625 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1626 if (report.isInteresting(R))
1627 event->setPrunable(false);
1635 std::shared_ptr<PathDiagnosticPiece>
1636 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
1637 const bool tookTrue, BugReporterContext &BRC,
1638 BugReport &report, const ExplodedNode *N) {
1640 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1644 SmallString<256> Buf;
1645 llvm::raw_svector_ostream Out(Buf);
1647 Out << "Assuming '" << VD->getDeclName() << "' is ";
1649 QualType VDTy = VD->getType();
1651 if (VDTy->isPointerType())
1652 Out << (tookTrue ? "non-null" : "null");
1653 else if (VDTy->isObjCObjectPointerType())
1654 Out << (tookTrue ? "non-nil" : "nil");
1655 else if (VDTy->isScalarType())
1656 Out << (tookTrue ? "not equal to 0" : "0");
1660 const LocationContext *LCtx = N->getLocationContext();
1661 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1662 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
1664 const ProgramState *state = N->getState().get();
1665 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
1666 if (report.isInteresting(R))
1667 event->setPrunable(false);
1669 SVal V = state->getSVal(R);
1670 if (report.isInteresting(V))
1671 event->setPrunable(false);
1674 return std::move(event);
1677 const char *const ConditionBRVisitor::GenericTrueMessage =
1678 "Assuming the condition is true";
1679 const char *const ConditionBRVisitor::GenericFalseMessage =
1680 "Assuming the condition is false";
1682 bool ConditionBRVisitor::isPieceMessageGeneric(
1683 const PathDiagnosticPiece *Piece) {
1684 return Piece->getString() == GenericTrueMessage ||
1685 Piece->getString() == GenericFalseMessage;
1688 std::unique_ptr<PathDiagnosticPiece>
1689 LikelyFalsePositiveSuppressionBRVisitor::getEndPath(BugReporterContext &BRC,
1690 const ExplodedNode *N,
1692 // Here we suppress false positives coming from system headers. This list is
1693 // based on known issues.
1694 ExprEngine &Eng = BRC.getBugReporter().getEngine();
1695 AnalyzerOptions &Options = Eng.getAnalysisManager().options;
1696 const Decl *D = N->getLocationContext()->getDecl();
1698 if (AnalysisDeclContext::isInStdNamespace(D)) {
1699 // Skip reports within the 'std' namespace. Although these can sometimes be
1700 // the user's fault, we currently don't report them very well, and
1701 // Note that this will not help for any other data structure libraries, like
1702 // TR1, Boost, or llvm/ADT.
1703 if (Options.shouldSuppressFromCXXStandardLibrary()) {
1704 BR.markInvalid(getTag(), nullptr);
1708 // If the complete 'std' suppression is not enabled, suppress reports
1709 // from the 'std' namespace that are known to produce false positives.
1711 // The analyzer issues a false use-after-free when std::list::pop_front
1712 // or std::list::pop_back are called multiple times because we cannot
1713 // reason about the internal invariants of the data structure.
1714 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1715 const CXXRecordDecl *CD = MD->getParent();
1716 if (CD->getName() == "list") {
1717 BR.markInvalid(getTag(), nullptr);
1722 // The analyzer issues a false positive when the constructor of
1723 // std::__independent_bits_engine from algorithms is used.
1724 if (const CXXConstructorDecl *MD = dyn_cast<CXXConstructorDecl>(D)) {
1725 const CXXRecordDecl *CD = MD->getParent();
1726 if (CD->getName() == "__independent_bits_engine") {
1727 BR.markInvalid(getTag(), nullptr);
1732 for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
1733 LCtx = LCtx->getParent()) {
1734 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
1738 const CXXRecordDecl *CD = MD->getParent();
1739 // The analyzer issues a false positive on
1740 // std::basic_string<uint8_t> v; v.push_back(1);
1742 // std::u16string s; s += u'a';
1743 // because we cannot reason about the internal invariants of the
1745 if (CD->getName() == "basic_string") {
1746 BR.markInvalid(getTag(), nullptr);
1750 // The analyzer issues a false positive on
1751 // std::shared_ptr<int> p(new int(1)); p = nullptr;
1752 // because it does not reason properly about temporary destructors.
1753 if (CD->getName() == "shared_ptr") {
1754 BR.markInvalid(getTag(), nullptr);
1761 // Skip reports within the sys/queue.h macros as we do not have the ability to
1762 // reason about data structure shapes.
1763 SourceManager &SM = BRC.getSourceManager();
1764 FullSourceLoc Loc = BR.getLocation(SM).asLocation();
1765 while (Loc.isMacroID()) {
1766 Loc = Loc.getSpellingLoc();
1767 if (SM.getFilename(Loc).endswith("sys/queue.h")) {
1768 BR.markInvalid(getTag(), nullptr);
1776 std::shared_ptr<PathDiagnosticPiece>
1777 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
1778 const ExplodedNode *PrevN,
1779 BugReporterContext &BRC, BugReport &BR) {
1781 ProgramStateRef State = N->getState();
1782 ProgramPoint ProgLoc = N->getLocation();
1784 // We are only interested in visiting CallEnter nodes.
1785 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
1789 // Check if one of the arguments is the region the visitor is tracking.
1790 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
1791 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
1793 ArrayRef<ParmVarDecl*> parms = Call->parameters();
1795 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1796 I != E; ++I, ++Idx) {
1797 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
1799 // Are we tracking the argument or its subregion?
1800 if ( !ArgReg || (ArgReg != R && !R->isSubRegionOf(ArgReg->StripCasts())))
1803 // Check the function parameter type.
1804 const ParmVarDecl *ParamDecl = *I;
1805 assert(ParamDecl && "Formal parameter has no decl?");
1806 QualType T = ParamDecl->getType();
1808 if (!(T->isAnyPointerType() || T->isReferenceType())) {
1809 // Function can only change the value passed in by address.
1813 // If it is a const pointer value, the function does not intend to
1814 // change the value.
1815 if (T->getPointeeType().isConstQualified())
1818 // Mark the call site (LocationContext) as interesting if the value of the
1819 // argument is undefined or '0'/'NULL'.
1820 SVal BoundVal = State->getSVal(R);
1821 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
1822 BR.markInteresting(CEnter->getCalleeContext());
1829 std::shared_ptr<PathDiagnosticPiece>
1830 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
1831 const ExplodedNode *Pred,
1832 BugReporterContext &BRC, BugReport &BR) {
1836 auto Edge = Succ->getLocation().getAs<BlockEdge>();
1837 if (!Edge.hasValue())
1840 auto Tag = Edge->getTag();
1844 if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
1850 dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
1851 assert(Met && "Not a C++ method.");
1852 assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
1853 "Not a copy/move assignment operator.");
1855 const auto *LCtx = Edge->getLocationContext();
1857 const auto &State = Succ->getState();
1858 auto &SVB = State->getStateManager().getSValBuilder();
1861 State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
1863 State->getSVal(SVB.getCXXThis(Met, LCtx->getCurrentStackFrame()));
1865 auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
1867 if (!L.isValid() || !L.asLocation().isValid())
1870 SmallString<256> Buf;
1871 llvm::raw_svector_ostream Out(Buf);
1873 Out << "Assuming " << Met->getParamDecl(0)->getName() <<
1874 ((Param == This) ? " == " : " != ") << "*this";
1876 auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
1877 Piece->addRange(Met->getSourceRange());
1879 return std::move(Piece);