1 //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
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 //===----------------------------------------------------------------------===//
15 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/Stmt.h"
24 #include "clang/AST/Type.h"
25 #include "clang/ASTMatchers/ASTMatchFinder.h"
26 #include "clang/Analysis/AnalysisDeclContext.h"
27 #include "clang/Analysis/CFG.h"
28 #include "clang/Analysis/CFGStmtMap.h"
29 #include "clang/Analysis/ProgramPoint.h"
30 #include "clang/Basic/IdentifierTable.h"
31 #include "clang/Basic/LLVM.h"
32 #include "clang/Basic/SourceLocation.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Lex/Lexer.h"
35 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
36 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
37 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
38 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
39 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
40 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
41 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
43 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
45 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
48 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/None.h"
51 #include "llvm/ADT/Optional.h"
52 #include "llvm/ADT/STLExtras.h"
53 #include "llvm/ADT/SmallPtrSet.h"
54 #include "llvm/ADT/SmallString.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/ADT/StringRef.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/raw_ostream.h"
67 using namespace clang;
70 //===----------------------------------------------------------------------===//
72 //===----------------------------------------------------------------------===//
74 bool bugreporter::isDeclRefExprToReference(const Expr *E) {
75 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
76 return DRE->getDecl()->getType()->isReferenceType();
80 static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
81 if (B->isAdditiveOp() && B->getType()->isPointerType()) {
82 if (B->getLHS()->getType()->isPointerType()) {
84 } else if (B->getRHS()->getType()->isPointerType()) {
91 /// Given that expression S represents a pointer that would be dereferenced,
92 /// try to find a sub-expression from which the pointer came from.
93 /// This is used for tracking down origins of a null or undefined value:
94 /// "this is null because that is null because that is null" etc.
95 /// We wipe away field and element offsets because they merely add offsets.
96 /// We also wipe away all casts except lvalue-to-rvalue casts, because the
97 /// latter represent an actual pointer dereference; however, we remove
98 /// the final lvalue-to-rvalue cast before returning from this function
99 /// because it demonstrates more clearly from where the pointer rvalue was
100 /// loaded. Examples:
101 /// x->y.z ==> x (lvalue)
102 /// foo()->y.z ==> foo() (rvalue)
103 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
104 const auto *E = dyn_cast<Expr>(S);
109 if (const auto *CE = dyn_cast<CastExpr>(E)) {
110 if (CE->getCastKind() == CK_LValueToRValue) {
111 // This cast represents the load we're looking for.
114 E = CE->getSubExpr();
115 } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
116 // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
117 if (const Expr *Inner = peelOffPointerArithmetic(B)) {
120 // Probably more arithmetic can be pattern-matched here,
121 // but for now give up.
124 } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
125 if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
126 (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
127 // Operators '*' and '&' don't actually mean anything.
128 // We look at casts instead.
131 // Probably more arithmetic can be pattern-matched here,
132 // but for now give up.
136 // Pattern match for a few useful cases: a[0], p->f, *p etc.
137 else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
139 } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
140 E = IvarRef->getBase();
141 } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
143 } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
144 E = PE->getSubExpr();
145 } else if (const auto *EWC = dyn_cast<ExprWithCleanups>(E)) {
146 E = EWC->getSubExpr();
148 // Other arbitrary stuff.
153 // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
154 // deeper into the sub-expression. This way we return the lvalue from which
155 // our pointer rvalue was loaded.
156 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
157 if (CE->getCastKind() == CK_LValueToRValue)
158 E = CE->getSubExpr();
163 const Stmt *bugreporter::GetDenomExpr(const ExplodedNode *N) {
164 const Stmt *S = N->getLocationAs<PreStmt>()->getStmt();
165 if (const auto *BE = dyn_cast<BinaryOperator>(S))
170 const Stmt *bugreporter::GetRetValExpr(const ExplodedNode *N) {
171 const Stmt *S = N->getLocationAs<PostStmt>()->getStmt();
172 if (const auto *RS = dyn_cast<ReturnStmt>(S))
173 return RS->getRetValue();
177 //===----------------------------------------------------------------------===//
178 // Definitions for bug reporter visitors.
179 //===----------------------------------------------------------------------===//
181 std::shared_ptr<PathDiagnosticPiece>
182 BugReporterVisitor::getEndPath(BugReporterContext &BRC,
183 const ExplodedNode *EndPathNode, BugReport &BR) {
188 BugReporterVisitor::finalizeVisitor(BugReporterContext &BRC,
189 const ExplodedNode *EndPathNode,
192 std::shared_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
193 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
194 PathDiagnosticLocation L =
195 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
197 const auto &Ranges = BR.getRanges();
199 // Only add the statement itself as a range if we didn't specify any
200 // special ranges for this report.
201 auto P = std::make_shared<PathDiagnosticEventPiece>(
202 L, BR.getDescription(), Ranges.begin() == Ranges.end());
203 for (SourceRange Range : Ranges)
209 /// \return name of the macro inside the location \p Loc.
210 static StringRef getMacroName(SourceLocation Loc,
211 BugReporterContext &BRC) {
212 return Lexer::getImmediateMacroName(
214 BRC.getSourceManager(),
215 BRC.getASTContext().getLangOpts());
218 /// \return Whether given spelling location corresponds to an expansion
219 /// of a function-like macro.
220 static bool isFunctionMacroExpansion(SourceLocation Loc,
221 const SourceManager &SM) {
222 if (!Loc.isMacroID())
224 while (SM.isMacroArgExpansion(Loc))
225 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
226 std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
227 SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
228 const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
229 return EInfo.isFunctionMacroExpansion();
232 /// \return Whether \c RegionOfInterest was modified at \p N,
233 /// where \p ReturnState is a state associated with the return
234 /// from the current frame.
235 static bool wasRegionOfInterestModifiedAt(
236 const SubRegion *RegionOfInterest,
237 const ExplodedNode *N,
239 ProgramStateRef State = N->getState();
240 ProgramStateManager &Mgr = N->getState()->getStateManager();
242 if (!N->getLocationAs<PostStore>()
243 && !N->getLocationAs<PostInitializer>()
244 && !N->getLocationAs<PostStmt>())
247 // Writing into region of interest.
248 if (auto PS = N->getLocationAs<PostStmt>())
249 if (auto *BO = PS->getStmtAs<BinaryOperator>())
250 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
251 N->getSVal(BO->getLHS()).getAsRegion()))
254 // SVal after the state is possibly different.
255 SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
256 if (!Mgr.getSValBuilder().areEqual(State, ValueAtN, ValueAfter).isConstrainedTrue() &&
257 (!ValueAtN.isUndef() || !ValueAfter.isUndef()))
266 /// Put a diagnostic on return statement of all inlined functions
267 /// for which the region of interest \p RegionOfInterest was passed into,
268 /// but not written inside, and it has caused an undefined read or a null
269 /// pointer dereference outside.
270 class NoStoreFuncVisitor final : public BugReporterVisitor {
271 const SubRegion *RegionOfInterest;
272 const SourceManager &SM;
273 const PrintingPolicy &PP;
274 static constexpr const char *DiagnosticsMsg =
275 "Returning without writing to '";
277 /// Frames writing into \c RegionOfInterest.
278 /// This visitor generates a note only if a function does not write into
279 /// a region of interest. This information is not immediately available
280 /// by looking at the node associated with the exit from the function
281 /// (usually the return statement). To avoid recomputing the same information
282 /// many times (going up the path for each node and checking whether the
283 /// region was written into) we instead lazily compute the
284 /// stack frames along the path which write into the region of interest.
285 llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
286 llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
289 NoStoreFuncVisitor(const SubRegion *R)
290 : RegionOfInterest(R),
291 SM(R->getMemRegionManager()->getContext().getSourceManager()),
292 PP(R->getMemRegionManager()->getContext().getPrintingPolicy()) {}
294 void Profile(llvm::FoldingSetNodeID &ID) const override {
299 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
300 const ExplodedNode *PrevN,
301 BugReporterContext &BRC,
302 BugReport &BR) override {
304 const LocationContext *Ctx = N->getLocationContext();
305 const StackFrameContext *SCtx = Ctx->getStackFrame();
306 ProgramStateRef State = N->getState();
307 auto CallExitLoc = N->getLocationAs<CallExitBegin>();
309 // No diagnostic if region was modified inside the frame.
313 CallEventRef<> Call =
314 BRC.getStateManager().getCallEventManager().getCaller(SCtx, State);
316 // Region of interest corresponds to an IVar, exiting a method
317 // which could have written into that IVar, but did not.
318 if (const auto *MC = dyn_cast<ObjCMethodCall>(Call))
319 if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest))
320 if (potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
322 !isRegionOfInterestModifiedInFrame(N))
323 return notModifiedMemberDiagnostics(
324 Ctx, *CallExitLoc, Call, MC->getReceiverSVal().getAsRegion());
326 if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
327 const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
328 if (RegionOfInterest->isSubRegionOf(ThisR)
329 && !CCall->getDecl()->isImplicit()
330 && !isRegionOfInterestModifiedInFrame(N))
331 return notModifiedMemberDiagnostics(Ctx, *CallExitLoc, Call, ThisR);
334 ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
335 for (unsigned I = 0; I < Call->getNumArgs() && I < parameters.size(); ++I) {
336 const ParmVarDecl *PVD = parameters[I];
337 SVal S = Call->getArgSVal(I);
338 unsigned IndirectionLevel = 1;
339 QualType T = PVD->getType();
340 while (const MemRegion *R = S.getAsRegion()) {
341 if (RegionOfInterest->isSubRegionOf(R)
342 && !isPointerToConst(PVD->getType())) {
344 if (isRegionOfInterestModifiedInFrame(N))
347 return notModifiedParameterDiagnostics(
348 Ctx, *CallExitLoc, Call, PVD, R, IndirectionLevel);
350 QualType PT = T->getPointeeType();
351 if (PT.isNull() || PT->isVoidType()) break;
352 S = State->getSVal(R, PT);
363 /// \return Whether the method declaration \p Parent
364 /// syntactically has a binary operation writing into the ivar \p Ivar.
365 bool potentiallyWritesIntoIvar(const Decl *Parent,
366 const ObjCIvarDecl *Ivar) {
367 using namespace ast_matchers;
368 if (!Parent || !Parent->getBody())
370 StatementMatcher WriteIntoIvarM = binaryOperator(
371 hasOperatorName("="), hasLHS(ignoringParenImpCasts(objcIvarRefExpr(
372 hasDeclaration(equalsNode(Ivar))))));
373 StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
374 auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
375 return !Matches.empty();
378 /// Check and lazily calculate whether the region of interest is
379 /// modified in the stack frame to which \p N belongs.
380 /// The calculation is cached in FramesModifyingRegion.
381 bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
382 const LocationContext *Ctx = N->getLocationContext();
383 const StackFrameContext *SCtx = Ctx->getStackFrame();
384 if (!FramesModifyingCalculated.count(SCtx))
385 findModifyingFrames(N);
386 return FramesModifyingRegion.count(SCtx);
390 /// Write to \c FramesModifyingRegion all stack frames along
391 /// the path in the current stack frame which modify \c RegionOfInterest.
392 void findModifyingFrames(const ExplodedNode *N) {
393 assert(N->getLocationAs<CallExitBegin>());
394 ProgramStateRef LastReturnState = N->getState();
395 SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
396 const LocationContext *Ctx = N->getLocationContext();
397 const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
400 ProgramStateRef State = N->getState();
401 auto CallExitLoc = N->getLocationAs<CallExitBegin>();
403 LastReturnState = State;
404 ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
407 FramesModifyingCalculated.insert(
408 N->getLocationContext()->getStackFrame());
410 if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) {
411 const StackFrameContext *SCtx = N->getStackFrame();
412 while (!SCtx->inTopFrame()) {
413 auto p = FramesModifyingRegion.insert(SCtx);
415 break; // Frame and all its parents already inserted.
416 SCtx = SCtx->getParent()->getStackFrame();
420 // Stop calculation at the call to the current function.
421 if (auto CE = N->getLocationAs<CallEnter>())
422 if (CE->getCalleeContext() == OriginalSCtx)
425 N = N->getFirstPred();
429 /// Get parameters associated with runtime definition in order
430 /// to get the correct parameter name.
431 ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
432 // Use runtime definition, if available.
433 RuntimeDefinition RD = Call->getRuntimeDefinition();
434 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
435 return FD->parameters();
437 return Call->parameters();
440 /// \return whether \p Ty points to a const type, or is a const reference.
441 bool isPointerToConst(QualType Ty) {
442 return !Ty->getPointeeType().isNull() &&
443 Ty->getPointeeType().getCanonicalType().isConstQualified();
446 /// \return Diagnostics piece for the member field not modified
447 /// in a given function.
448 std::shared_ptr<PathDiagnosticPiece> notModifiedMemberDiagnostics(
449 const LocationContext *Ctx,
450 CallExitBegin &CallExitLoc,
452 const MemRegion *ArgRegion) {
453 const char *TopRegionName = isa<ObjCMethodCall>(Call) ? "self" : "this";
454 SmallString<256> sbuf;
455 llvm::raw_svector_ostream os(sbuf);
456 os << DiagnosticsMsg;
457 bool out = prettyPrintRegionName(TopRegionName, "->", /*IsReference=*/true,
458 /*IndirectionLevel=*/1, ArgRegion, os, PP);
460 // Return nothing if we have failed to pretty-print.
465 PathDiagnosticLocation L =
466 getPathDiagnosticLocation(CallExitLoc.getReturnStmt(), SM, Ctx, Call);
467 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
470 /// \return Diagnostics piece for the parameter \p PVD not modified
471 /// in a given function.
472 /// \p IndirectionLevel How many times \c ArgRegion has to be dereferenced
473 /// before we get to the super region of \c RegionOfInterest
474 std::shared_ptr<PathDiagnosticPiece>
475 notModifiedParameterDiagnostics(const LocationContext *Ctx,
476 CallExitBegin &CallExitLoc,
478 const ParmVarDecl *PVD,
479 const MemRegion *ArgRegion,
480 unsigned IndirectionLevel) {
481 PathDiagnosticLocation L = getPathDiagnosticLocation(
482 CallExitLoc.getReturnStmt(), SM, Ctx, Call);
483 SmallString<256> sbuf;
484 llvm::raw_svector_ostream os(sbuf);
485 os << DiagnosticsMsg;
486 bool IsReference = PVD->getType()->isReferenceType();
487 const char *Sep = IsReference && IndirectionLevel == 1 ? "." : "->";
488 bool Success = prettyPrintRegionName(
489 PVD->getQualifiedNameAsString().c_str(),
490 Sep, IsReference, IndirectionLevel, ArgRegion, os, PP);
492 // Print the parameter name if the pretty-printing has failed.
494 PVD->printQualifiedName(os);
496 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
499 /// \return a path diagnostic location for the optionally
500 /// present return statement \p RS.
501 PathDiagnosticLocation getPathDiagnosticLocation(const ReturnStmt *RS,
502 const SourceManager &SM,
503 const LocationContext *Ctx,
504 CallEventRef<> Call) {
506 return PathDiagnosticLocation::createBegin(RS, SM, Ctx);
507 return PathDiagnosticLocation(
508 Call->getRuntimeDefinition().getDecl()->getSourceRange().getEnd(), SM);
511 /// Pretty-print region \p ArgRegion starting from parent to \p os.
512 /// \return whether printing has succeeded
513 bool prettyPrintRegionName(StringRef TopRegionName,
516 int IndirectionLevel,
517 const MemRegion *ArgRegion,
518 llvm::raw_svector_ostream &os,
519 const PrintingPolicy &PP) {
520 SmallVector<const MemRegion *, 5> Subregions;
521 const MemRegion *R = RegionOfInterest;
522 while (R != ArgRegion) {
523 if (!(isa<FieldRegion>(R) || isa<CXXBaseObjectRegion>(R) ||
524 isa<ObjCIvarRegion>(R)))
525 return false; // Pattern-matching failed.
526 Subregions.push_back(R);
527 R = cast<SubRegion>(R)->getSuperRegion();
529 bool IndirectReference = !Subregions.empty();
531 if (IndirectReference)
532 IndirectionLevel--; // Due to "->" symbol.
535 IndirectionLevel--; // Due to reference semantics.
537 bool ShouldSurround = IndirectReference && IndirectionLevel > 0;
541 for (int i = 0; i < IndirectionLevel; i++)
547 for (auto I = Subregions.rbegin(), E = Subregions.rend(); I != E; ++I) {
548 if (const auto *FR = dyn_cast<FieldRegion>(*I)) {
550 FR->getDecl()->getDeclName().print(os, PP);
552 } else if (const auto *IR = dyn_cast<ObjCIvarRegion>(*I)) {
554 IR->getDecl()->getDeclName().print(os, PP);
556 } else if (isa<CXXBaseObjectRegion>(*I)) {
557 continue; // Just keep going up to the base region.
559 llvm_unreachable("Previous check has missed an unexpected region");
566 /// Suppress null-pointer-dereference bugs where dereferenced null was returned
568 class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
569 const SubRegion *RegionOfInterest;
570 const SVal ValueAtDereference;
572 // Do not invalidate the reports where the value was modified
573 // after it got assigned to from the macro.
574 bool WasModified = false;
577 MacroNullReturnSuppressionVisitor(const SubRegion *R,
578 const SVal V) : RegionOfInterest(R),
579 ValueAtDereference(V) {}
581 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
582 const ExplodedNode *PrevN,
583 BugReporterContext &BRC,
584 BugReport &BR) override {
588 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
592 const SourceManager &SMgr = BRC.getSourceManager();
593 if (auto Loc = matchAssignment(N, BRC)) {
594 if (isFunctionMacroExpansion(*Loc, SMgr)) {
595 std::string MacroName = getMacroName(*Loc, BRC);
596 SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
597 if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
598 BR.markInvalid(getTag(), MacroName.c_str());
602 if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
608 static void addMacroVisitorIfNecessary(
609 const ExplodedNode *N, const MemRegion *R,
610 bool EnableNullFPSuppression, BugReport &BR,
612 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
613 if (EnableNullFPSuppression && Options.shouldSuppressNullReturnPaths()
615 BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
616 R->getAs<SubRegion>(), V));
619 void* getTag() const {
621 return static_cast<void *>(&Tag);
624 void Profile(llvm::FoldingSetNodeID &ID) const override {
625 ID.AddPointer(getTag());
629 /// \return Source location of right hand side of an assignment
630 /// into \c RegionOfInterest, empty optional if none found.
631 Optional<SourceLocation> matchAssignment(const ExplodedNode *N,
632 BugReporterContext &BRC) {
633 const Stmt *S = PathDiagnosticLocation::getStmt(N);
634 ProgramStateRef State = N->getState();
635 auto *LCtx = N->getLocationContext();
639 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
640 if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
641 if (const Expr *RHS = VD->getInit())
642 if (RegionOfInterest->isSubRegionOf(
643 State->getLValue(VD, LCtx).getAsRegion()))
644 return RHS->getLocStart();
645 } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
646 const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
647 const Expr *RHS = BO->getRHS();
648 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
649 return RHS->getLocStart();
656 /// Emits an extra note at the return statement of an interesting stack frame.
658 /// The returned value is marked as an interesting value, and if it's null,
659 /// adds a visitor to track where it became null.
661 /// This visitor is intended to be used when another visitor discovers that an
662 /// interesting value comes from an inlined function call.
663 class ReturnVisitor : public BugReporterVisitor {
664 const StackFrameContext *StackFrame;
671 bool EnableNullFPSuppression;
672 bool ShouldInvalidate = true;
675 ReturnVisitor(const StackFrameContext *Frame, bool Suppressed)
676 : StackFrame(Frame), EnableNullFPSuppression(Suppressed) {}
678 static void *getTag() {
680 return static_cast<void *>(&Tag);
683 void Profile(llvm::FoldingSetNodeID &ID) const override {
684 ID.AddPointer(ReturnVisitor::getTag());
685 ID.AddPointer(StackFrame);
686 ID.AddBoolean(EnableNullFPSuppression);
689 /// Adds a ReturnVisitor if the given statement represents a call that was
692 /// This will search back through the ExplodedGraph, starting from the given
693 /// node, looking for when the given statement was processed. If it turns out
694 /// the statement is a call that was inlined, we add the visitor to the
695 /// bug report, so it can print a note later.
696 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
698 bool InEnableNullFPSuppression) {
699 if (!CallEvent::isCallStmt(S))
702 // First, find when we processed the statement.
704 if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
705 if (CEE->getCalleeContext()->getCallSite() == S)
707 if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
708 if (SP->getStmt() == S)
711 Node = Node->getFirstPred();
714 // Next, step over any post-statement checks.
715 while (Node && Node->getLocation().getAs<PostStmt>())
716 Node = Node->getFirstPred();
720 // Finally, see if we inlined the call.
721 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
725 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
726 if (CalleeContext->getCallSite() != S)
729 // Check the return value.
730 ProgramStateRef State = Node->getState();
731 SVal RetVal = Node->getSVal(S);
733 // Handle cases where a reference is returned and then immediately used.
734 if (cast<Expr>(S)->isGLValue())
735 if (Optional<Loc> LValue = RetVal.getAs<Loc>())
736 RetVal = State->getSVal(*LValue);
738 // See if the return value is NULL. If so, suppress the report.
739 AnalyzerOptions &Options = State->getAnalysisManager().options;
741 bool EnableNullFPSuppression = false;
742 if (InEnableNullFPSuppression && Options.shouldSuppressNullReturnPaths())
743 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
744 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
746 BR.markInteresting(CalleeContext);
747 BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
748 EnableNullFPSuppression));
751 /// Returns true if any counter-suppression heuristics are enabled for
753 static bool hasCounterSuppression(AnalyzerOptions &Options) {
754 return Options.shouldAvoidSuppressingNullArgumentPaths();
757 std::shared_ptr<PathDiagnosticPiece>
758 visitNodeInitial(const ExplodedNode *N, const ExplodedNode *PrevN,
759 BugReporterContext &BRC, BugReport &BR) {
760 // Only print a message at the interesting return statement.
761 if (N->getLocationContext() != StackFrame)
764 Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
768 const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
772 // Okay, we're at the right return statement, but do we have the return
774 ProgramStateRef State = N->getState();
775 SVal V = State->getSVal(Ret, StackFrame);
776 if (V.isUnknownOrUndef())
779 // Don't print any more notes after this one.
782 const Expr *RetE = Ret->getRetValue();
783 assert(RetE && "Tracking a return value for a void function");
785 // Handle cases where a reference is returned and then immediately used.
786 Optional<Loc> LValue;
787 if (RetE->isGLValue()) {
788 if ((LValue = V.getAs<Loc>())) {
789 SVal RValue = State->getRawSVal(*LValue, RetE->getType());
790 if (RValue.getAs<DefinedSVal>())
795 // Ignore aggregate rvalues.
796 if (V.getAs<nonloc::LazyCompoundVal>() ||
797 V.getAs<nonloc::CompoundVal>())
800 RetE = RetE->IgnoreParenCasts();
802 // If we can't prove the return value is 0, just mark it interesting, and
803 // make sure to track it into any further inner functions.
804 if (!State->isNull(V).isConstrainedTrue()) {
805 BR.markInteresting(V);
806 ReturnVisitor::addVisitorIfNecessary(N, RetE, BR,
807 EnableNullFPSuppression);
811 // If we're returning 0, we should track where that 0 came from.
812 bugreporter::trackNullOrUndefValue(N, RetE, BR, /*IsArg*/ false,
813 EnableNullFPSuppression);
815 // Build an appropriate message based on the return value.
817 llvm::raw_svector_ostream Out(Msg);
819 if (V.getAs<Loc>()) {
820 // If we have counter-suppression enabled, make sure we keep visiting
821 // future nodes. We want to emit a path note as well, in case
822 // the report is resurrected as valid later on.
823 AnalyzerOptions &Options = BRC.getAnalyzerOptions();
824 if (EnableNullFPSuppression && hasCounterSuppression(Options))
825 Mode = MaybeUnsuppress;
827 if (RetE->getType()->isObjCObjectPointerType())
828 Out << "Returning nil";
830 Out << "Returning null pointer";
832 Out << "Returning zero";
836 if (const MemRegion *MR = LValue->getAsRegion()) {
837 if (MR->canPrintPretty()) {
838 Out << " (reference to ";
839 MR->printPretty(Out);
844 // FIXME: We should have a more generalized location printing mechanism.
845 if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
846 if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
847 Out << " (loaded from '" << *DD << "')";
850 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
851 if (!L.isValid() || !L.asLocation().isValid())
854 return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
857 std::shared_ptr<PathDiagnosticPiece>
858 visitNodeMaybeUnsuppress(const ExplodedNode *N, const ExplodedNode *PrevN,
859 BugReporterContext &BRC, BugReport &BR) {
861 AnalyzerOptions &Options = BRC.getAnalyzerOptions();
862 assert(hasCounterSuppression(Options));
865 // Are we at the entry node for this call?
866 Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
870 if (CE->getCalleeContext() != StackFrame)
875 // Don't automatically suppress a report if one of the arguments is
876 // known to be a null pointer. Instead, start tracking /that/ null
877 // value back to its origin.
878 ProgramStateManager &StateMgr = BRC.getStateManager();
879 CallEventManager &CallMgr = StateMgr.getCallEventManager();
881 ProgramStateRef State = N->getState();
882 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
883 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
884 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
888 const Expr *ArgE = Call->getArgExpr(I);
892 // Is it possible for this argument to be non-null?
893 if (!State->isNull(*ArgV).isConstrainedTrue())
896 if (bugreporter::trackNullOrUndefValue(N, ArgE, BR, /*IsArg=*/true,
897 EnableNullFPSuppression))
898 ShouldInvalidate = false;
900 // If we /can't/ track the null pointer, we should err on the side of
901 // false negatives, and continue towards marking this report invalid.
902 // (We will still look at the other arguments, though.)
908 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
909 const ExplodedNode *PrevN,
910 BugReporterContext &BRC,
911 BugReport &BR) override {
914 return visitNodeInitial(N, PrevN, BRC, BR);
915 case MaybeUnsuppress:
916 return visitNodeMaybeUnsuppress(N, PrevN, BRC, BR);
921 llvm_unreachable("Invalid visit mode!");
924 void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N,
925 BugReport &BR) override {
926 if (EnableNullFPSuppression && ShouldInvalidate)
927 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
933 void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
938 ID.AddBoolean(EnableNullFPSuppression);
941 /// Returns true if \p N represents the DeclStmt declaring and initializing
943 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
944 Optional<PostStmt> P = N->getLocationAs<PostStmt>();
948 const DeclStmt *DS = P->getStmtAs<DeclStmt>();
952 if (DS->getSingleDecl() != VR->getDecl())
955 const MemSpaceRegion *VarSpace = VR->getMemorySpace();
956 const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
958 // If we ever directly evaluate global DeclStmts, this assertion will be
959 // invalid, but this still seems preferable to silently accepting an
960 // initialization that may be for a path-sensitive variable.
961 assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
965 assert(VR->getDecl()->hasLocalStorage());
966 const LocationContext *LCtx = N->getLocationContext();
967 return FrameSpace->getStackFrame() == LCtx->getStackFrame();
970 /// Show diagnostics for initializing or declaring a region \p R with a bad value.
971 static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
972 const MemRegion *R, SVal V, const DeclStmt *DS) {
973 if (R->canPrintPretty()) {
978 if (V.getAs<loc::ConcreteInt>()) {
980 if (R->isBoundable()) {
981 if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
982 if (TR->getValueType()->isObjCObjectPointerType()) {
983 os << action << "nil";
989 os << action << "a null pointer value";
991 } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
992 os << action << CVal->getValue();
995 if (isa<VarRegion>(R)) {
996 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
998 os << (R->canPrintPretty() ? "initialized" : "Initializing")
999 << " to a garbage value";
1001 os << (R->canPrintPretty() ? "declared" : "Declaring")
1002 << " without an initial value";
1006 os << (R->canPrintPretty() ? "initialized" : "Initialized")
1012 /// Display diagnostics for passing bad region as a parameter.
1013 static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
1014 const VarRegion *VR,
1016 const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1020 if (V.getAs<loc::ConcreteInt>()) {
1021 if (Param->getType()->isObjCObjectPointerType())
1022 os << "nil object reference";
1024 os << "null pointer value";
1025 } else if (V.isUndef()) {
1026 os << "uninitialized value";
1027 } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1028 os << "the value " << CI->getValue();
1033 // Printed parameter indexes are 1-based, not 0-based.
1034 unsigned Idx = Param->getFunctionScopeIndex() + 1;
1035 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
1036 if (VR->canPrintPretty()) {
1038 VR->printPretty(os);
1042 /// Show default diagnostics for storing bad region.
1043 static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
1046 if (V.getAs<loc::ConcreteInt>()) {
1048 if (R->isBoundable()) {
1049 if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1050 if (TR->getValueType()->isObjCObjectPointerType()) {
1051 os << "nil object reference stored";
1057 if (R->canPrintPretty())
1058 os << "Null pointer value stored";
1060 os << "Storing null pointer value";
1063 } else if (V.isUndef()) {
1064 if (R->canPrintPretty())
1065 os << "Uninitialized value stored";
1067 os << "Storing uninitialized value";
1069 } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
1070 if (R->canPrintPretty())
1071 os << "The value " << CV->getValue() << " is assigned";
1073 os << "Assigning " << CV->getValue();
1076 if (R->canPrintPretty())
1077 os << "Value assigned";
1079 os << "Assigning value";
1082 if (R->canPrintPretty()) {
1088 std::shared_ptr<PathDiagnosticPiece>
1089 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
1090 const ExplodedNode *Pred,
1091 BugReporterContext &BRC, BugReport &BR) {
1095 const ExplodedNode *StoreSite = nullptr;
1096 const Expr *InitE = nullptr;
1097 bool IsParam = false;
1099 // First see if we reached the declaration of the region.
1100 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1101 if (isInitializationOfVar(Pred, VR)) {
1103 InitE = VR->getDecl()->getInit();
1107 // If this is a post initializer expression, initializing the region, we
1108 // should track the initializer expression.
1109 if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
1110 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1111 if (FieldReg && FieldReg == R) {
1113 InitE = PIP->getInitializer()->getInit();
1117 // Otherwise, see if this is the store site:
1118 // (1) Succ has this binding and Pred does not, i.e. this is
1119 // where the binding first occurred.
1120 // (2) Succ has this binding and is a PostStore node for this region, i.e.
1121 // the same binding was re-assigned here.
1123 if (Succ->getState()->getSVal(R) != V)
1126 if (Pred->getState()->getSVal(R) == V) {
1127 Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1128 if (!PS || PS->getLocationValue() != R)
1134 // If this is an assignment expression, we can track the value
1136 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
1137 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
1138 if (BO->isAssignmentOp())
1139 InitE = BO->getRHS();
1141 // If this is a call entry, the variable should be a parameter.
1142 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1143 // 'this' should never be NULL, but this visitor isn't just for NULL and
1145 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1146 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1147 const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1149 ProgramStateManager &StateMgr = BRC.getStateManager();
1150 CallEventManager &CallMgr = StateMgr.getCallEventManager();
1152 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
1154 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1159 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1160 // is wrapped inside of it.
1161 if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1162 InitE = TmpR->getExpr();
1169 // If we have an expression that provided the value, try to track where it
1173 V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1175 InitE = InitE->IgnoreParenCasts();
1176 bugreporter::trackNullOrUndefValue(StoreSite, InitE, BR, IsParam,
1177 EnableNullFPSuppression);
1179 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
1180 BR, EnableNullFPSuppression);
1184 // Okay, we've found the binding. Emit an appropriate message.
1185 SmallString<256> sbuf;
1186 llvm::raw_svector_ostream os(sbuf);
1188 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1189 const Stmt *S = PS->getStmt();
1190 const char *action = nullptr;
1191 const auto *DS = dyn_cast<DeclStmt>(S);
1192 const auto *VR = dyn_cast<VarRegion>(R);
1195 action = R->canPrintPretty() ? "initialized to " :
1197 } else if (isa<BlockExpr>(S)) {
1198 action = R->canPrintPretty() ? "captured by block as " :
1199 "Captured by block as ";
1201 // See if we can get the BlockVarRegion.
1202 ProgramStateRef State = StoreSite->getState();
1203 SVal V = StoreSite->getSVal(S);
1204 if (const auto *BDR =
1205 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1206 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1207 if (Optional<KnownSVal> KV =
1208 State->getSVal(OriginalR).getAs<KnownSVal>())
1209 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1210 *KV, OriginalR, EnableNullFPSuppression));
1216 showBRDiagnostics(action, os, R, V, DS);
1218 } else if (StoreSite->getLocation().getAs<CallEnter>()) {
1219 if (const auto *VR = dyn_cast<VarRegion>(R))
1220 showBRParamDiagnostics(os, VR, V);
1223 if (os.str().empty())
1224 showBRDefaultDiagnostics(os, R, V);
1226 // Construct a new PathDiagnosticPiece.
1227 ProgramPoint P = StoreSite->getLocation();
1228 PathDiagnosticLocation L;
1229 if (P.getAs<CallEnter>() && InitE)
1230 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
1231 P.getLocationContext());
1233 if (!L.isValid() || !L.asLocation().isValid())
1234 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
1236 if (!L.isValid() || !L.asLocation().isValid())
1239 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1242 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1244 ID.AddPointer(&tag);
1245 ID.AddBoolean(Assumption);
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 *TrackConstraintBRVisitor::getTag() {
1252 return "TrackConstraintBRVisitor";
1255 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1257 return N->getState()->isNull(Constraint).isUnderconstrained();
1258 return (bool)N->getState()->assume(Constraint, !Assumption);
1261 std::shared_ptr<PathDiagnosticPiece>
1262 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
1263 const ExplodedNode *PrevN,
1264 BugReporterContext &BRC, BugReport &BR) {
1268 // Start tracking after we see the first state in which the value is
1270 if (!IsTrackingTurnedOn)
1271 if (!isUnderconstrained(N))
1272 IsTrackingTurnedOn = true;
1273 if (!IsTrackingTurnedOn)
1276 // Check if in the previous state it was feasible for this constraint
1277 // to *not* be true.
1278 if (isUnderconstrained(PrevN)) {
1281 // As a sanity check, make sure that the negation of the constraint
1282 // was infeasible in the current state. If it is feasible, we somehow
1283 // missed the transition point.
1284 assert(!isUnderconstrained(N));
1286 // We found the transition point for the constraint. We now need to
1287 // pretty-print the constraint. (work-in-progress)
1288 SmallString<64> sbuf;
1289 llvm::raw_svector_ostream os(sbuf);
1291 if (Constraint.getAs<Loc>()) {
1292 os << "Assuming pointer value is ";
1293 os << (Assumption ? "non-null" : "null");
1296 if (os.str().empty())
1299 // Construct a new PathDiagnosticPiece.
1300 ProgramPoint P = N->getLocation();
1301 PathDiagnosticLocation L =
1302 PathDiagnosticLocation::create(P, BRC.getSourceManager());
1306 auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1307 X->setTag(getTag());
1308 return std::move(X);
1314 SuppressInlineDefensiveChecksVisitor::
1315 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
1317 // Check if the visitor is disabled.
1318 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
1319 if (!Options.shouldSuppressInlinedDefensiveChecks())
1322 assert(N->getState()->isNull(V).isConstrainedTrue() &&
1323 "The visitor only tracks the cases where V is constrained to 0");
1326 void SuppressInlineDefensiveChecksVisitor::Profile(
1327 llvm::FoldingSetNodeID &ID) const {
1333 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
1334 return "IDCVisitor";
1337 std::shared_ptr<PathDiagnosticPiece>
1338 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
1339 const ExplodedNode *Pred,
1340 BugReporterContext &BRC,
1345 // Start tracking after we see the first state in which the value is null.
1346 if (!IsTrackingTurnedOn)
1347 if (Succ->getState()->isNull(V).isConstrainedTrue())
1348 IsTrackingTurnedOn = true;
1349 if (!IsTrackingTurnedOn)
1352 // Check if in the previous state it was feasible for this value
1353 // to *not* be null.
1354 if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
1357 assert(Succ->getState()->isNull(V).isConstrainedTrue());
1359 // Check if this is inlined defensive checks.
1360 const LocationContext *CurLC =Succ->getLocationContext();
1361 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
1362 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
1363 BR.markInvalid("Suppress IDC", CurLC);
1367 // Treat defensive checks in function-like macros as if they were an inlined
1368 // defensive check. If the bug location is not in a macro and the
1369 // terminator for the current location is in a macro then suppress the
1371 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1376 ProgramPoint CurPoint = Succ->getLocation();
1377 const Stmt *CurTerminatorStmt = nullptr;
1378 if (auto BE = CurPoint.getAs<BlockEdge>()) {
1379 CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1380 } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1381 const Stmt *CurStmt = SP->getStmt();
1382 if (!CurStmt->getLocStart().isMacroID())
1385 CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1386 CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
1391 if (!CurTerminatorStmt)
1394 SourceLocation TerminatorLoc = CurTerminatorStmt->getLocStart();
1395 if (TerminatorLoc.isMacroID()) {
1396 SourceLocation BugLoc = BugPoint->getStmt()->getLocStart();
1398 // Suppress reports unless we are in that same macro.
1399 if (!BugLoc.isMacroID() ||
1400 getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1401 BR.markInvalid("Suppress Macro IDC", CurLC);
1409 static const MemRegion *getLocationRegionIfReference(const Expr *E,
1410 const ExplodedNode *N) {
1411 if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
1412 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1413 if (!VD->getType()->isReferenceType())
1415 ProgramStateManager &StateMgr = N->getState()->getStateManager();
1416 MemRegionManager &MRMgr = StateMgr.getRegionManager();
1417 return MRMgr.getVarRegion(VD, N->getLocationContext());
1421 // FIXME: This does not handle other kinds of null references,
1422 // for example, references from FieldRegions:
1423 // struct Wrapper { int &ref; };
1424 // Wrapper w = { *(int *)0 };
1430 static const Expr *peelOffOuterExpr(const Expr *Ex,
1431 const ExplodedNode *N) {
1432 Ex = Ex->IgnoreParenCasts();
1433 if (const auto *EWC = dyn_cast<ExprWithCleanups>(Ex))
1434 return peelOffOuterExpr(EWC->getSubExpr(), N);
1435 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1436 return peelOffOuterExpr(OVE->getSourceExpr(), N);
1437 if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1438 const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1439 if (PropRef && PropRef->isMessagingGetter()) {
1440 const Expr *GetterMessageSend =
1441 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1442 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1443 return peelOffOuterExpr(GetterMessageSend, N);
1447 // Peel off the ternary operator.
1448 if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
1449 // Find a node where the branching occurred and find out which branch
1450 // we took (true/false) by looking at the ExplodedGraph.
1451 const ExplodedNode *NI = N;
1453 ProgramPoint ProgPoint = NI->getLocation();
1454 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1455 const CFGBlock *srcBlk = BE->getSrc();
1456 if (const Stmt *term = srcBlk->getTerminator()) {
1458 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1460 return peelOffOuterExpr(CO->getTrueExpr(), N);
1462 return peelOffOuterExpr(CO->getFalseExpr(), N);
1466 NI = NI->getFirstPred();
1470 if (auto *BO = dyn_cast<BinaryOperator>(Ex))
1471 if (const Expr *SubEx = peelOffPointerArithmetic(BO))
1472 return peelOffOuterExpr(SubEx, N);
1477 /// Walk through nodes until we get one that matches the statement exactly.
1478 /// Alternately, if we hit a known lvalue for the statement, we know we've
1479 /// gone too far (though we can likely track the lvalue better anyway).
1480 static const ExplodedNode* findNodeForStatement(const ExplodedNode *N,
1482 const Expr *Inner) {
1484 const ProgramPoint &pp = N->getLocation();
1485 if (auto ps = pp.getAs<StmtPoint>()) {
1486 if (ps->getStmt() == S || ps->getStmt() == Inner)
1488 } else if (auto CEE = pp.getAs<CallExitEnd>()) {
1489 if (CEE->getCalleeContext()->getCallSite() == S ||
1490 CEE->getCalleeContext()->getCallSite() == Inner)
1493 N = N->getFirstPred();
1498 /// Find the ExplodedNode where the lvalue (the value of 'Ex')
1500 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1501 const Expr *Inner) {
1503 if (auto P = N->getLocation().getAs<PostStmt>()) {
1504 if (P->getStmt() == Inner)
1507 N = N->getFirstPred();
1509 assert(N && "Unable to find the lvalue node.");
1513 /// Performing operator `&' on an lvalue expression is essentially a no-op.
1514 /// Then, if we are taking addresses of fields or elements, these are also
1515 /// unlikely to matter.
1516 static const Expr* peelOfOuterAddrOf(const Expr* Ex) {
1517 Ex = Ex->IgnoreParenCasts();
1519 // FIXME: There's a hack in our Store implementation that always computes
1520 // field offsets around null pointers as if they are always equal to 0.
1521 // The idea here is to report accesses to fields as null dereferences
1522 // even though the pointer value that's being dereferenced is actually
1523 // the offset of the field rather than exactly 0.
1524 // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1525 // This code interacts heavily with this hack; otherwise the value
1526 // would not be null at all for most fields, so we'd be unable to track it.
1527 if (const auto *Op = dyn_cast<UnaryOperator>(Ex))
1528 if (Op->getOpcode() == UO_AddrOf && Op->getSubExpr()->isLValue())
1529 if (const Expr *DerefEx = bugreporter::getDerefExpr(Op->getSubExpr()))
1534 bool bugreporter::trackNullOrUndefValue(const ExplodedNode *N,
1536 BugReport &report, bool IsArg,
1537 bool EnableNullFPSuppression) {
1541 if (const auto *Ex = dyn_cast<Expr>(S))
1542 S = peelOffOuterExpr(Ex, N);
1544 const Expr *Inner = nullptr;
1545 if (const auto *Ex = dyn_cast<Expr>(S)) {
1546 Ex = peelOfOuterAddrOf(Ex);
1547 Ex = Ex->IgnoreParenCasts();
1549 if (Ex && (ExplodedGraph::isInterestingLValueExpr(Ex)
1550 || CallEvent::isCallStmt(Ex)))
1554 if (IsArg && !Inner) {
1555 assert(N->getLocation().getAs<CallEnter>() && "Tracking arg but not at call");
1557 N = findNodeForStatement(N, S, Inner);
1562 ProgramStateRef state = N->getState();
1564 // The message send could be nil due to the receiver being nil.
1565 // At this point in the path, the receiver should be live since we are at the
1566 // message send expr. If it is nil, start tracking it.
1567 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(S, N))
1568 trackNullOrUndefValue(N, Receiver, report, /* IsArg=*/ false,
1569 EnableNullFPSuppression);
1571 // See if the expression we're interested refers to a variable.
1572 // If so, we can track both its contents and constraints on its value.
1573 if (Inner && ExplodedGraph::isInterestingLValueExpr(Inner)) {
1574 const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
1575 ProgramStateRef LVState = LVNode->getState();
1576 SVal LVal = LVNode->getSVal(Inner);
1578 const MemRegion *RR = getLocationRegionIfReference(Inner, N);
1579 bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1581 // If this is a C++ reference to a null pointer, we are tracking the
1582 // pointer. In addition, we should find the store at which the reference
1584 if (RR && !LVIsNull) {
1585 if (auto KV = LVal.getAs<KnownSVal>())
1586 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1587 *KV, RR, EnableNullFPSuppression));
1590 // In case of C++ references, we want to differentiate between a null
1591 // reference and reference to null pointer.
1592 // If the LVal is null, check if we are dealing with null reference.
1593 // For those, we want to track the location of the reference.
1594 const MemRegion *R = (RR && LVIsNull) ? RR :
1595 LVNode->getSVal(Inner).getAsRegion();
1599 // Mark both the variable region and its contents as interesting.
1600 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1602 llvm::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R)));
1604 MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1605 N, R, EnableNullFPSuppression, report, V);
1607 report.markInteresting(R);
1608 report.markInteresting(V);
1609 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1611 // If the contents are symbolic, find out when they became null.
1612 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1613 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1614 V.castAs<DefinedSVal>(), false));
1616 // Add visitor, which will suppress inline defensive checks.
1617 if (auto DV = V.getAs<DefinedSVal>()) {
1618 if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1619 EnableNullFPSuppression) {
1621 llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1626 if (auto KV = V.getAs<KnownSVal>())
1627 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1628 *KV, R, EnableNullFPSuppression));
1633 // If the expression is not an "lvalue expression", we can still
1634 // track the constraints on its contents.
1635 SVal V = state->getSValAsScalarOrLoc(S, N->getLocationContext());
1637 // If the value came from an inlined function call, we should at least make
1638 // sure that function isn't pruned in our output.
1639 if (const auto *E = dyn_cast<Expr>(S))
1640 S = E->IgnoreParenCasts();
1642 ReturnVisitor::addVisitorIfNecessary(N, S, report, EnableNullFPSuppression);
1644 // Uncomment this to find cases where we aren't properly getting the
1645 // base value that was dereferenced.
1646 // assert(!V.isUnknownOrUndef());
1647 // Is it a symbolic value?
1648 if (auto L = V.getAs<loc::MemRegionVal>()) {
1649 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1651 // At this point we are dealing with the region's LValue.
1652 // However, if the rvalue is a symbolic region, we should track it as well.
1653 // Try to use the correct type when looking up the value.
1655 if (const auto *E = dyn_cast<Expr>(S))
1656 RVal = state->getRawSVal(L.getValue(), E->getType());
1658 RVal = state->getSVal(L->getRegion());
1660 if (auto KV = RVal.getAs<KnownSVal>())
1661 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1662 *KV, L->getRegion(), EnableNullFPSuppression));
1664 const MemRegion *RegionRVal = RVal.getAsRegion();
1665 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1666 report.markInteresting(RegionRVal);
1667 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1668 loc::MemRegionVal(RegionRVal), false));
1674 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1675 const ExplodedNode *N) {
1676 const auto *ME = dyn_cast<ObjCMessageExpr>(S);
1679 if (const Expr *Receiver = ME->getInstanceReceiver()) {
1680 ProgramStateRef state = N->getState();
1681 SVal V = N->getSVal(Receiver);
1682 if (state->isNull(V).isConstrainedTrue())
1688 std::shared_ptr<PathDiagnosticPiece>
1689 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1690 const ExplodedNode *PrevN,
1691 BugReporterContext &BRC, BugReport &BR) {
1692 Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1696 const Stmt *S = P->getStmt();
1697 const Expr *Receiver = getNilReceiver(S, N);
1701 llvm::SmallString<256> Buf;
1702 llvm::raw_svector_ostream OS(Buf);
1704 if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1706 ME->getSelector().print(OS);
1707 OS << "' not called";
1710 OS << "No method is called";
1712 OS << " because the receiver is nil";
1714 // The receiver was nil, and hence the method was skipped.
1715 // Register a BugReporterVisitor to issue a message telling us how
1716 // the receiver was null.
1717 bugreporter::trackNullOrUndefValue(N, Receiver, BR, /*IsArg*/ false,
1718 /*EnableNullFPSuppression*/ false);
1719 // Issue a message saying that the method was skipped.
1720 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1721 N->getLocationContext());
1722 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1725 // Registers every VarDecl inside a Stmt with a last store visitor.
1726 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1728 bool EnableNullFPSuppression) {
1729 const ExplodedNode *N = BR.getErrorNode();
1730 std::deque<const Stmt *> WorkList;
1731 WorkList.push_back(S);
1733 while (!WorkList.empty()) {
1734 const Stmt *Head = WorkList.front();
1735 WorkList.pop_front();
1737 ProgramStateManager &StateMgr = N->getState()->getStateManager();
1739 if (const auto *DR = dyn_cast<DeclRefExpr>(Head)) {
1740 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1741 const VarRegion *R =
1742 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1744 // What did we load?
1745 SVal V = N->getSVal(S);
1747 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1748 // Register a new visitor with the BugReport.
1749 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1750 V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1755 for (const Stmt *SubStmt : Head->children())
1756 WorkList.push_back(SubStmt);
1760 //===----------------------------------------------------------------------===//
1761 // Visitor that tries to report interesting diagnostics from conditions.
1762 //===----------------------------------------------------------------------===//
1764 /// Return the tag associated with this visitor. This tag will be used
1765 /// to make all PathDiagnosticPieces created by this visitor.
1766 const char *ConditionBRVisitor::getTag() {
1767 return "ConditionBRVisitor";
1770 std::shared_ptr<PathDiagnosticPiece>
1771 ConditionBRVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *Prev,
1772 BugReporterContext &BRC, BugReport &BR) {
1773 auto piece = VisitNodeImpl(N, Prev, BRC, BR);
1775 piece->setTag(getTag());
1776 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1777 ev->setPrunable(true, /* override */ false);
1782 std::shared_ptr<PathDiagnosticPiece>
1783 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1784 const ExplodedNode *Prev,
1785 BugReporterContext &BRC, BugReport &BR) {
1786 ProgramPoint progPoint = N->getLocation();
1787 ProgramStateRef CurrentState = N->getState();
1788 ProgramStateRef PrevState = Prev->getState();
1790 // Compare the GDMs of the state, because that is where constraints
1791 // are managed. Note that ensure that we only look at nodes that
1792 // were generated by the analyzer engine proper, not checkers.
1793 if (CurrentState->getGDM().getRoot() ==
1794 PrevState->getGDM().getRoot())
1797 // If an assumption was made on a branch, it should be caught
1798 // here by looking at the state transition.
1799 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1800 const CFGBlock *srcBlk = BE->getSrc();
1801 if (const Stmt *term = srcBlk->getTerminator())
1802 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1806 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1807 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1808 ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
1810 const ProgramPointTag *tag = PS->getTag();
1811 if (tag == tags.first)
1812 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1814 if (tag == tags.second)
1815 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1824 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1825 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1826 const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1827 const Expr *Cond = nullptr;
1829 // In the code below, Term is a CFG terminator and Cond is a branch condition
1830 // expression upon which the decision is made on this terminator.
1832 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1833 // and "x == 0" is the respective condition.
1835 // Another example: in "if (x && y)", we've got two terminators and two
1836 // conditions due to short-circuit nature of operator "&&":
1837 // 1. The "if (x && y)" statement is a terminator,
1838 // and "y" is the respective condition.
1839 // 2. Also "x && ..." is another terminator,
1840 // and "x" is its condition.
1842 switch (Term->getStmtClass()) {
1843 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1844 // more tricky because there are more than two branches to account for.
1847 case Stmt::IfStmtClass:
1848 Cond = cast<IfStmt>(Term)->getCond();
1850 case Stmt::ConditionalOperatorClass:
1851 Cond = cast<ConditionalOperator>(Term)->getCond();
1853 case Stmt::BinaryOperatorClass:
1854 // When we encounter a logical operator (&& or ||) as a CFG terminator,
1855 // then the condition is actually its LHS; otherwise, we'd encounter
1856 // the parent, such as if-statement, as a terminator.
1857 const auto *BO = cast<BinaryOperator>(Term);
1858 assert(BO->isLogicalOp() &&
1859 "CFG terminator is not a short-circuit operator!");
1860 Cond = BO->getLHS();
1864 // However, when we encounter a logical operator as a branch condition,
1865 // then the condition is actually its RHS, because LHS would be
1866 // the condition for the logical operator terminator.
1867 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1868 if (!InnerBO->isLogicalOp())
1870 Cond = InnerBO->getRHS()->IgnoreParens();
1874 assert(srcBlk->succ_size() == 2);
1875 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1876 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1879 std::shared_ptr<PathDiagnosticPiece>
1880 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1881 BugReporterContext &BRC, BugReport &R,
1882 const ExplodedNode *N) {
1883 // These will be modified in code below, but we need to preserve the original
1884 // values in case we want to throw the generic message.
1885 const Expr *CondTmp = Cond;
1886 bool tookTrueTmp = tookTrue;
1889 CondTmp = CondTmp->IgnoreParenCasts();
1890 switch (CondTmp->getStmtClass()) {
1893 case Stmt::BinaryOperatorClass:
1894 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1895 tookTrueTmp, BRC, R, N))
1898 case Stmt::DeclRefExprClass:
1899 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1900 tookTrueTmp, BRC, R, N))
1903 case Stmt::UnaryOperatorClass: {
1904 const auto *UO = cast<UnaryOperator>(CondTmp);
1905 if (UO->getOpcode() == UO_LNot) {
1906 tookTrueTmp = !tookTrueTmp;
1907 CondTmp = UO->getSubExpr();
1916 // Condition too complex to explain? Just say something so that the user
1917 // knew we've made some path decision at this point.
1918 const LocationContext *LCtx = N->getLocationContext();
1919 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1920 if (!Loc.isValid() || !Loc.asLocation().isValid())
1923 return std::make_shared<PathDiagnosticEventPiece>(
1924 Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1927 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1928 const Expr *ParentEx,
1930 BugReporterContext &BRC,
1932 const ExplodedNode *N,
1933 Optional<bool> &prunable) {
1934 const Expr *OriginalExpr = Ex;
1935 Ex = Ex->IgnoreParenCasts();
1937 // Use heuristics to determine if Ex is a macro expending to a literal and
1938 // if so, use the macro's name.
1939 SourceLocation LocStart = Ex->getLocStart();
1940 SourceLocation LocEnd = Ex->getLocEnd();
1941 if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1942 (isa<GNUNullExpr>(Ex) ||
1943 isa<ObjCBoolLiteralExpr>(Ex) ||
1944 isa<CXXBoolLiteralExpr>(Ex) ||
1945 isa<IntegerLiteral>(Ex) ||
1946 isa<FloatingLiteral>(Ex))) {
1947 StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1948 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1949 StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1950 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1951 bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1953 bool partOfParentMacro = false;
1954 if (ParentEx->getLocStart().isMacroID()) {
1955 StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
1956 ParentEx->getLocStart(), BRC.getSourceManager(),
1957 BRC.getASTContext().getLangOpts());
1958 partOfParentMacro = PName.equals(StartName);
1961 if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
1962 // Get the location of the macro name as written by the caller.
1963 SourceLocation Loc = LocStart;
1964 while (LocStart.isMacroID()) {
1966 LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
1968 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
1969 Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1971 // Return the macro name.
1977 if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
1978 const bool quotes = isa<VarDecl>(DR->getDecl());
1981 const LocationContext *LCtx = N->getLocationContext();
1982 const ProgramState *state = N->getState().get();
1983 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1984 LCtx).getAsRegion()) {
1985 if (report.isInteresting(R))
1988 const ProgramState *state = N->getState().get();
1989 SVal V = state->getSVal(R);
1990 if (report.isInteresting(V))
1995 Out << DR->getDecl()->getDeclName().getAsString();
2001 if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
2002 QualType OriginalTy = OriginalExpr->getType();
2003 if (OriginalTy->isPointerType()) {
2004 if (IL->getValue() == 0) {
2009 else if (OriginalTy->isObjCObjectPointerType()) {
2010 if (IL->getValue() == 0) {
2016 Out << IL->getValue();
2023 std::shared_ptr<PathDiagnosticPiece>
2024 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
2025 const bool tookTrue, BugReporterContext &BRC,
2026 BugReport &R, const ExplodedNode *N) {
2027 bool shouldInvert = false;
2028 Optional<bool> shouldPrune;
2030 SmallString<128> LhsString, RhsString;
2032 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
2033 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
2034 BRC, R, N, shouldPrune);
2035 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
2036 BRC, R, N, shouldPrune);
2038 shouldInvert = !isVarLHS && isVarRHS;
2041 BinaryOperator::Opcode Op = BExpr->getOpcode();
2043 if (BinaryOperator::isAssignmentOp(Op)) {
2044 // For assignment operators, all that we care about is that the LHS
2045 // evaluates to "true" or "false".
2046 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
2050 // For non-assignment operations, we require that we can understand
2051 // both the LHS and RHS.
2052 if (LhsString.empty() || RhsString.empty() ||
2053 !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
2056 // Should we invert the strings if the LHS is not a variable name?
2057 SmallString<256> buf;
2058 llvm::raw_svector_ostream Out(buf);
2059 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
2061 // Do we need to invert the opcode?
2065 case BO_LT: Op = BO_GT; break;
2066 case BO_GT: Op = BO_LT; break;
2067 case BO_LE: Op = BO_GE; break;
2068 case BO_GE: Op = BO_LE; break;
2073 case BO_EQ: Op = BO_NE; break;
2074 case BO_NE: Op = BO_EQ; break;
2075 case BO_LT: Op = BO_GE; break;
2076 case BO_GT: Op = BO_LE; break;
2077 case BO_LE: Op = BO_GT; break;
2078 case BO_GE: Op = BO_LT; break;
2088 Out << "not equal to ";
2091 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
2095 Out << (shouldInvert ? LhsString : RhsString);
2096 const LocationContext *LCtx = N->getLocationContext();
2097 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2098 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2099 if (shouldPrune.hasValue())
2100 event->setPrunable(shouldPrune.getValue());
2104 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
2105 StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
2106 BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
2107 // FIXME: If there's already a constraint tracker for this variable,
2108 // we shouldn't emit anything here (c.f. the double note in
2109 // test/Analysis/inlining/path-notes.c)
2110 SmallString<256> buf;
2111 llvm::raw_svector_ostream Out(buf);
2112 Out << "Assuming " << LhsString << " is ";
2114 QualType Ty = CondVarExpr->getType();
2116 if (Ty->isPointerType())
2117 Out << (tookTrue ? "not null" : "null");
2118 else if (Ty->isObjCObjectPointerType())
2119 Out << (tookTrue ? "not nil" : "nil");
2120 else if (Ty->isBooleanType())
2121 Out << (tookTrue ? "true" : "false");
2122 else if (Ty->isIntegralOrEnumerationType())
2123 Out << (tookTrue ? "non-zero" : "zero");
2127 const LocationContext *LCtx = N->getLocationContext();
2128 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
2129 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2131 if (const auto *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
2132 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2133 const ProgramState *state = N->getState().get();
2134 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2135 if (report.isInteresting(R))
2136 event->setPrunable(false);
2144 std::shared_ptr<PathDiagnosticPiece>
2145 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
2146 const bool tookTrue, BugReporterContext &BRC,
2147 BugReport &report, const ExplodedNode *N) {
2148 const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
2152 SmallString<256> Buf;
2153 llvm::raw_svector_ostream Out(Buf);
2155 Out << "Assuming '" << VD->getDeclName() << "' is ";
2157 QualType VDTy = VD->getType();
2159 if (VDTy->isPointerType())
2160 Out << (tookTrue ? "non-null" : "null");
2161 else if (VDTy->isObjCObjectPointerType())
2162 Out << (tookTrue ? "non-nil" : "nil");
2163 else if (VDTy->isScalarType())
2164 Out << (tookTrue ? "not equal to 0" : "0");
2168 const LocationContext *LCtx = N->getLocationContext();
2169 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2170 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2172 const ProgramState *state = N->getState().get();
2173 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2174 if (report.isInteresting(R))
2175 event->setPrunable(false);
2177 SVal V = state->getSVal(R);
2178 if (report.isInteresting(V))
2179 event->setPrunable(false);
2182 return std::move(event);
2185 const char *const ConditionBRVisitor::GenericTrueMessage =
2186 "Assuming the condition is true";
2187 const char *const ConditionBRVisitor::GenericFalseMessage =
2188 "Assuming the condition is false";
2190 bool ConditionBRVisitor::isPieceMessageGeneric(
2191 const PathDiagnosticPiece *Piece) {
2192 return Piece->getString() == GenericTrueMessage ||
2193 Piece->getString() == GenericFalseMessage;
2196 void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
2197 BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR) {
2198 // Here we suppress false positives coming from system headers. This list is
2199 // based on known issues.
2200 AnalyzerOptions &Options = BRC.getAnalyzerOptions();
2201 const Decl *D = N->getLocationContext()->getDecl();
2203 if (AnalysisDeclContext::isInStdNamespace(D)) {
2204 // Skip reports within the 'std' namespace. Although these can sometimes be
2205 // the user's fault, we currently don't report them very well, and
2206 // Note that this will not help for any other data structure libraries, like
2207 // TR1, Boost, or llvm/ADT.
2208 if (Options.shouldSuppressFromCXXStandardLibrary()) {
2209 BR.markInvalid(getTag(), nullptr);
2212 // If the complete 'std' suppression is not enabled, suppress reports
2213 // from the 'std' namespace that are known to produce false positives.
2215 // The analyzer issues a false use-after-free when std::list::pop_front
2216 // or std::list::pop_back are called multiple times because we cannot
2217 // reason about the internal invariants of the data structure.
2218 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2219 const CXXRecordDecl *CD = MD->getParent();
2220 if (CD->getName() == "list") {
2221 BR.markInvalid(getTag(), nullptr);
2226 // The analyzer issues a false positive when the constructor of
2227 // std::__independent_bits_engine from algorithms is used.
2228 if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
2229 const CXXRecordDecl *CD = MD->getParent();
2230 if (CD->getName() == "__independent_bits_engine") {
2231 BR.markInvalid(getTag(), nullptr);
2236 for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
2237 LCtx = LCtx->getParent()) {
2238 const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
2242 const CXXRecordDecl *CD = MD->getParent();
2243 // The analyzer issues a false positive on
2244 // std::basic_string<uint8_t> v; v.push_back(1);
2246 // std::u16string s; s += u'a';
2247 // because we cannot reason about the internal invariants of the
2249 if (CD->getName() == "basic_string") {
2250 BR.markInvalid(getTag(), nullptr);
2254 // The analyzer issues a false positive on
2255 // std::shared_ptr<int> p(new int(1)); p = nullptr;
2256 // because it does not reason properly about temporary destructors.
2257 if (CD->getName() == "shared_ptr") {
2258 BR.markInvalid(getTag(), nullptr);
2265 // Skip reports within the sys/queue.h macros as we do not have the ability to
2266 // reason about data structure shapes.
2267 SourceManager &SM = BRC.getSourceManager();
2268 FullSourceLoc Loc = BR.getLocation(SM).asLocation();
2269 while (Loc.isMacroID()) {
2270 Loc = Loc.getSpellingLoc();
2271 if (SM.getFilename(Loc).endswith("sys/queue.h")) {
2272 BR.markInvalid(getTag(), nullptr);
2278 std::shared_ptr<PathDiagnosticPiece>
2279 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
2280 const ExplodedNode *PrevN,
2281 BugReporterContext &BRC, BugReport &BR) {
2282 ProgramStateRef State = N->getState();
2283 ProgramPoint ProgLoc = N->getLocation();
2285 // We are only interested in visiting CallEnter nodes.
2286 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
2290 // Check if one of the arguments is the region the visitor is tracking.
2291 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
2292 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
2294 ArrayRef<ParmVarDecl *> parms = Call->parameters();
2296 for (const auto ParamDecl : parms) {
2297 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
2300 // Are we tracking the argument or its subregion?
2301 if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
2304 // Check the function parameter type.
2305 assert(ParamDecl && "Formal parameter has no decl?");
2306 QualType T = ParamDecl->getType();
2308 if (!(T->isAnyPointerType() || T->isReferenceType())) {
2309 // Function can only change the value passed in by address.
2313 // If it is a const pointer value, the function does not intend to
2314 // change the value.
2315 if (T->getPointeeType().isConstQualified())
2318 // Mark the call site (LocationContext) as interesting if the value of the
2319 // argument is undefined or '0'/'NULL'.
2320 SVal BoundVal = State->getSVal(R);
2321 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
2322 BR.markInteresting(CEnter->getCalleeContext());
2329 std::shared_ptr<PathDiagnosticPiece>
2330 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
2331 const ExplodedNode *Pred,
2332 BugReporterContext &BRC, BugReport &BR) {
2336 const auto Edge = Succ->getLocation().getAs<BlockEdge>();
2337 if (!Edge.hasValue())
2340 auto Tag = Edge->getTag();
2344 if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
2350 dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
2351 assert(Met && "Not a C++ method.");
2352 assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
2353 "Not a copy/move assignment operator.");
2355 const auto *LCtx = Edge->getLocationContext();
2357 const auto &State = Succ->getState();
2358 auto &SVB = State->getStateManager().getSValBuilder();
2361 State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
2363 State->getSVal(SVB.getCXXThis(Met, LCtx->getStackFrame()));
2365 auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
2367 if (!L.isValid() || !L.asLocation().isValid())
2370 SmallString<256> Buf;
2371 llvm::raw_svector_ostream Out(Buf);
2373 Out << "Assuming " << Met->getParamDecl(0)->getName() <<
2374 ((Param == This) ? " == " : " != ") << "*this";
2376 auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
2377 Piece->addRange(Met->getSourceRange());
2379 return std::move(Piece);
2382 std::shared_ptr<PathDiagnosticPiece>
2383 TaintBugVisitor::VisitNode(const ExplodedNode *N, const ExplodedNode *PrevN,
2384 BugReporterContext &BRC, BugReport &BR) {
2386 // Find the ExplodedNode where the taint was first introduced
2387 if (!N->getState()->isTainted(V) || PrevN->getState()->isTainted(V))
2390 const Stmt *S = PathDiagnosticLocation::getStmt(N);
2394 const LocationContext *NCtx = N->getLocationContext();
2395 PathDiagnosticLocation L =
2396 PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);
2397 if (!L.isValid() || !L.asLocation().isValid())
2400 return std::make_shared<PathDiagnosticEventPiece>(L, "Taint originated here");
2403 FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
2404 : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
2406 void FalsePositiveRefutationBRVisitor::finalizeVisitor(
2407 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
2408 // Collect new constraints
2409 VisitNode(EndPathNode, nullptr, BRC, BR);
2411 // Create a refutation manager
2412 std::unique_ptr<SMTSolver> RefutationSolver = CreateZ3Solver();
2413 ASTContext &Ctx = BRC.getASTContext();
2415 // Add constraints to the solver
2416 for (const auto &I : Constraints) {
2417 SymbolRef Sym = I.first;
2419 SMTExprRef Constraints = RefutationSolver->fromBoolean(false);
2420 for (const auto &Range : I.second) {
2421 Constraints = RefutationSolver->mkOr(
2423 RefutationSolver->getRangeExpr(Ctx, Sym, Range.From(), Range.To(),
2426 RefutationSolver->addConstraint(Constraints);
2429 // And check for satisfiability
2430 if (RefutationSolver->check().isConstrainedFalse())
2431 BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
2434 std::shared_ptr<PathDiagnosticPiece>
2435 FalsePositiveRefutationBRVisitor::VisitNode(const ExplodedNode *N,
2436 const ExplodedNode *PrevN,
2437 BugReporterContext &BRC,
2439 // Collect new constraints
2440 const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
2441 ConstraintRangeTy::Factory &CF =
2442 N->getState()->get_context<ConstraintRange>();
2444 // Add constraints if we don't have them yet
2445 for (auto const &C : NewCs) {
2446 const SymbolRef &Sym = C.first;
2447 if (!Constraints.contains(Sym)) {
2448 Constraints = CF.add(Constraints, Sym, C.second);
2455 void FalsePositiveRefutationBRVisitor::Profile(
2456 llvm::FoldingSetNodeID &ID) const {
2458 ID.AddPointer(&Tag);