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/SMTConv.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
48 #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.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 static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
75 if (B->isAdditiveOp() && B->getType()->isPointerType()) {
76 if (B->getLHS()->getType()->isPointerType()) {
78 } else if (B->getRHS()->getType()->isPointerType()) {
85 /// Given that expression S represents a pointer that would be dereferenced,
86 /// try to find a sub-expression from which the pointer came from.
87 /// This is used for tracking down origins of a null or undefined value:
88 /// "this is null because that is null because that is null" etc.
89 /// We wipe away field and element offsets because they merely add offsets.
90 /// We also wipe away all casts except lvalue-to-rvalue casts, because the
91 /// latter represent an actual pointer dereference; however, we remove
92 /// the final lvalue-to-rvalue cast before returning from this function
93 /// because it demonstrates more clearly from where the pointer rvalue was
95 /// x->y.z ==> x (lvalue)
96 /// foo()->y.z ==> foo() (rvalue)
97 const Expr *bugreporter::getDerefExpr(const Stmt *S) {
98 const auto *E = dyn_cast<Expr>(S);
103 if (const auto *CE = dyn_cast<CastExpr>(E)) {
104 if (CE->getCastKind() == CK_LValueToRValue) {
105 // This cast represents the load we're looking for.
108 E = CE->getSubExpr();
109 } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
110 // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
111 if (const Expr *Inner = peelOffPointerArithmetic(B)) {
114 // Probably more arithmetic can be pattern-matched here,
115 // but for now give up.
118 } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
119 if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
120 (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
121 // Operators '*' and '&' don't actually mean anything.
122 // We look at casts instead.
125 // Probably more arithmetic can be pattern-matched here,
126 // but for now give up.
130 // Pattern match for a few useful cases: a[0], p->f, *p etc.
131 else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
133 } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
134 E = IvarRef->getBase();
135 } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
137 } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
138 E = PE->getSubExpr();
139 } else if (const auto *FE = dyn_cast<FullExpr>(E)) {
140 E = FE->getSubExpr();
142 // Other arbitrary stuff.
147 // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
148 // deeper into the sub-expression. This way we return the lvalue from which
149 // our pointer rvalue was loaded.
150 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
151 if (CE->getCastKind() == CK_LValueToRValue)
152 E = CE->getSubExpr();
157 /// Comparing internal representations of symbolic values (via
158 /// SVal::operator==()) is a valid way to check if the value was updated,
159 /// unless it's a LazyCompoundVal that may have a different internal
160 /// representation every time it is loaded from the state. In this function we
161 /// do an approximate comparison for lazy compound values, checking that they
162 /// are the immediate snapshots of the tracked region's bindings within the
163 /// node's respective states but not really checking that these snapshots
164 /// actually contain the same set of bindings.
165 bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
166 const ExplodedNode *RightNode, SVal RightVal) {
167 if (LeftVal == RightVal)
170 const auto LLCV = LeftVal.getAs<nonloc::LazyCompoundVal>();
174 const auto RLCV = RightVal.getAs<nonloc::LazyCompoundVal>();
178 return LLCV->getRegion() == RLCV->getRegion() &&
179 LLCV->getStore() == LeftNode->getState()->getStore() &&
180 RLCV->getStore() == RightNode->getState()->getStore();
183 //===----------------------------------------------------------------------===//
184 // Definitions for bug reporter visitors.
185 //===----------------------------------------------------------------------===//
187 std::shared_ptr<PathDiagnosticPiece>
188 BugReporterVisitor::getEndPath(BugReporterContext &,
189 const ExplodedNode *, BugReport &) {
194 BugReporterVisitor::finalizeVisitor(BugReporterContext &,
195 const ExplodedNode *, BugReport &) {}
197 std::shared_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
198 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
199 PathDiagnosticLocation L =
200 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
202 const auto &Ranges = BR.getRanges();
204 // Only add the statement itself as a range if we didn't specify any
205 // special ranges for this report.
206 auto P = std::make_shared<PathDiagnosticEventPiece>(
207 L, BR.getDescription(), Ranges.begin() == Ranges.end());
208 for (SourceRange Range : Ranges)
214 /// \return name of the macro inside the location \p Loc.
215 static StringRef getMacroName(SourceLocation Loc,
216 BugReporterContext &BRC) {
217 return Lexer::getImmediateMacroName(
219 BRC.getSourceManager(),
220 BRC.getASTContext().getLangOpts());
223 /// \return Whether given spelling location corresponds to an expansion
224 /// of a function-like macro.
225 static bool isFunctionMacroExpansion(SourceLocation Loc,
226 const SourceManager &SM) {
227 if (!Loc.isMacroID())
229 while (SM.isMacroArgExpansion(Loc))
230 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
231 std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
232 SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
233 const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
234 return EInfo.isFunctionMacroExpansion();
237 /// \return Whether \c RegionOfInterest was modified at \p N,
238 /// where \p ReturnState is a state associated with the return
239 /// from the current frame.
240 static bool wasRegionOfInterestModifiedAt(
241 const SubRegion *RegionOfInterest,
242 const ExplodedNode *N,
244 ProgramStateRef State = N->getState();
245 ProgramStateManager &Mgr = N->getState()->getStateManager();
247 if (!N->getLocationAs<PostStore>()
248 && !N->getLocationAs<PostInitializer>()
249 && !N->getLocationAs<PostStmt>())
252 // Writing into region of interest.
253 if (auto PS = N->getLocationAs<PostStmt>())
254 if (auto *BO = PS->getStmtAs<BinaryOperator>())
255 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
256 N->getSVal(BO->getLHS()).getAsRegion()))
259 // SVal after the state is possibly different.
260 SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
261 if (!Mgr.getSValBuilder().areEqual(State, ValueAtN, ValueAfter).isConstrainedTrue() &&
262 (!ValueAtN.isUndef() || !ValueAfter.isUndef()))
271 /// Put a diagnostic on return statement of all inlined functions
272 /// for which the region of interest \p RegionOfInterest was passed into,
273 /// but not written inside, and it has caused an undefined read or a null
274 /// pointer dereference outside.
275 class NoStoreFuncVisitor final : public BugReporterVisitor {
276 const SubRegion *RegionOfInterest;
277 MemRegionManager &MmrMgr;
278 const SourceManager &SM;
279 const PrintingPolicy &PP;
281 /// Recursion limit for dereferencing fields when looking for the
282 /// region of interest.
283 /// The limit of two indicates that we will dereference fields only once.
284 static const unsigned DEREFERENCE_LIMIT = 2;
286 /// Frames writing into \c RegionOfInterest.
287 /// This visitor generates a note only if a function does not write into
288 /// a region of interest. This information is not immediately available
289 /// by looking at the node associated with the exit from the function
290 /// (usually the return statement). To avoid recomputing the same information
291 /// many times (going up the path for each node and checking whether the
292 /// region was written into) we instead lazily compute the
293 /// stack frames along the path which write into the region of interest.
294 llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
295 llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
297 using RegionVector = SmallVector<const MemRegion *, 5>;
299 NoStoreFuncVisitor(const SubRegion *R)
300 : RegionOfInterest(R), MmrMgr(*R->getMemRegionManager()),
301 SM(MmrMgr.getContext().getSourceManager()),
302 PP(MmrMgr.getContext().getPrintingPolicy()) {}
304 void Profile(llvm::FoldingSetNodeID &ID) const override {
307 ID.AddPointer(RegionOfInterest);
310 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
311 BugReporterContext &BR,
312 BugReport &) override {
314 const LocationContext *Ctx = N->getLocationContext();
315 const StackFrameContext *SCtx = Ctx->getStackFrame();
316 ProgramStateRef State = N->getState();
317 auto CallExitLoc = N->getLocationAs<CallExitBegin>();
319 // No diagnostic if region was modified inside the frame.
320 if (!CallExitLoc || isRegionOfInterestModifiedInFrame(N))
323 CallEventRef<> Call =
324 BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
326 if (SM.isInSystemHeader(Call->getDecl()->getSourceRange().getBegin()))
329 // Region of interest corresponds to an IVar, exiting a method
330 // which could have written into that IVar, but did not.
331 if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
332 if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
333 const MemRegion *SelfRegion = MC->getReceiverSVal().getAsRegion();
334 if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
335 potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
337 return notModifiedDiagnostics(Ctx, *CallExitLoc, Call, {}, SelfRegion,
338 "self", /*FirstIsReferenceType=*/false,
343 if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
344 const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
345 if (RegionOfInterest->isSubRegionOf(ThisR)
346 && !CCall->getDecl()->isImplicit())
347 return notModifiedDiagnostics(Ctx, *CallExitLoc, Call, {}, ThisR,
349 /*FirstIsReferenceType=*/false, 1);
351 // Do not generate diagnostics for not modified parameters in
356 ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
357 for (unsigned I = 0; I < Call->getNumArgs() && I < parameters.size(); ++I) {
358 const ParmVarDecl *PVD = parameters[I];
359 SVal S = Call->getArgSVal(I);
360 bool ParamIsReferenceType = PVD->getType()->isReferenceType();
361 std::string ParamName = PVD->getNameAsString();
363 int IndirectionLevel = 1;
364 QualType T = PVD->getType();
365 while (const MemRegion *R = S.getAsRegion()) {
366 if (RegionOfInterest->isSubRegionOf(R) && !isPointerToConst(T))
367 return notModifiedDiagnostics(Ctx, *CallExitLoc, Call, {}, R,
368 ParamName, ParamIsReferenceType,
371 QualType PT = T->getPointeeType();
372 if (PT.isNull() || PT->isVoidType()) break;
374 if (const RecordDecl *RD = PT->getAsRecordDecl())
375 if (auto P = findRegionOfInterestInRecord(RD, State, R))
376 return notModifiedDiagnostics(
377 Ctx, *CallExitLoc, Call, *P, RegionOfInterest, ParamName,
378 ParamIsReferenceType, IndirectionLevel);
380 S = State->getSVal(R, PT);
390 /// Attempts to find the region of interest in a given CXX decl,
391 /// by either following the base classes or fields.
392 /// Dereferences fields up to a given recursion limit.
393 /// Note that \p Vec is passed by value, leading to quadratic copying cost,
394 /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
395 /// \return A chain fields leading to the region of interest or None.
396 const Optional<RegionVector>
397 findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State,
399 const RegionVector &Vec = {},
402 if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth.
405 if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
406 if (!RDX->hasDefinition())
409 // Recursively examine the base classes.
410 // Note that following base classes does not increase the recursion depth.
411 if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
412 for (const auto II : RDX->bases())
413 if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
414 if (auto Out = findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
417 for (const FieldDecl *I : RD->fields()) {
418 QualType FT = I->getType();
419 const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
420 const SVal V = State->getSVal(FR);
421 const MemRegion *VR = V.getAsRegion();
423 RegionVector VecF = Vec;
426 if (RegionOfInterest == VR)
429 if (const RecordDecl *RRD = FT->getAsRecordDecl())
431 findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
434 QualType PT = FT->getPointeeType();
435 if (PT.isNull() || PT->isVoidType() || !VR) continue;
437 if (const RecordDecl *RRD = PT->getAsRecordDecl())
439 findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
447 /// \return Whether the method declaration \p Parent
448 /// syntactically has a binary operation writing into the ivar \p Ivar.
449 bool potentiallyWritesIntoIvar(const Decl *Parent,
450 const ObjCIvarDecl *Ivar) {
451 using namespace ast_matchers;
452 const char * IvarBind = "Ivar";
453 if (!Parent || !Parent->hasBody())
455 StatementMatcher WriteIntoIvarM = binaryOperator(
456 hasOperatorName("="),
457 hasLHS(ignoringParenImpCasts(
458 objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
459 StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
460 auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
461 for (BoundNodes &Match : Matches) {
462 auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
463 if (IvarRef->isFreeIvar())
466 const Expr *Base = IvarRef->getBase();
467 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
468 Base = ICE->getSubExpr();
470 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
471 if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
472 if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf)
480 /// Check and lazily calculate whether the region of interest is
481 /// modified in the stack frame to which \p N belongs.
482 /// The calculation is cached in FramesModifyingRegion.
483 bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
484 const LocationContext *Ctx = N->getLocationContext();
485 const StackFrameContext *SCtx = Ctx->getStackFrame();
486 if (!FramesModifyingCalculated.count(SCtx))
487 findModifyingFrames(N);
488 return FramesModifyingRegion.count(SCtx);
492 /// Write to \c FramesModifyingRegion all stack frames along
493 /// the path in the current stack frame which modify \c RegionOfInterest.
494 void findModifyingFrames(const ExplodedNode *N) {
495 assert(N->getLocationAs<CallExitBegin>());
496 ProgramStateRef LastReturnState = N->getState();
497 SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
498 const LocationContext *Ctx = N->getLocationContext();
499 const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
502 ProgramStateRef State = N->getState();
503 auto CallExitLoc = N->getLocationAs<CallExitBegin>();
505 LastReturnState = State;
506 ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
509 FramesModifyingCalculated.insert(
510 N->getLocationContext()->getStackFrame());
512 if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) {
513 const StackFrameContext *SCtx = N->getStackFrame();
514 while (!SCtx->inTopFrame()) {
515 auto p = FramesModifyingRegion.insert(SCtx);
517 break; // Frame and all its parents already inserted.
518 SCtx = SCtx->getParent()->getStackFrame();
522 // Stop calculation at the call to the current function.
523 if (auto CE = N->getLocationAs<CallEnter>())
524 if (CE->getCalleeContext() == OriginalSCtx)
527 N = N->getFirstPred();
531 /// Get parameters associated with runtime definition in order
532 /// to get the correct parameter name.
533 ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
534 // Use runtime definition, if available.
535 RuntimeDefinition RD = Call->getRuntimeDefinition();
536 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
537 return FD->parameters();
538 if (const auto *MD = dyn_cast_or_null<ObjCMethodDecl>(RD.getDecl()))
539 return MD->parameters();
541 return Call->parameters();
544 /// \return whether \p Ty points to a const type, or is a const reference.
545 bool isPointerToConst(QualType Ty) {
546 return !Ty->getPointeeType().isNull() &&
547 Ty->getPointeeType().getCanonicalType().isConstQualified();
550 /// \return Diagnostics piece for region not modified in the current function.
551 std::shared_ptr<PathDiagnosticPiece>
552 notModifiedDiagnostics(const LocationContext *Ctx, CallExitBegin &CallExitLoc,
553 CallEventRef<> Call, const RegionVector &FieldChain,
554 const MemRegion *MatchedRegion, StringRef FirstElement,
555 bool FirstIsReferenceType, unsigned IndirectionLevel) {
557 PathDiagnosticLocation L;
558 if (const ReturnStmt *RS = CallExitLoc.getReturnStmt()) {
559 L = PathDiagnosticLocation::createBegin(RS, SM, Ctx);
561 L = PathDiagnosticLocation(
562 Call->getRuntimeDefinition().getDecl()->getSourceRange().getEnd(),
566 SmallString<256> sbuf;
567 llvm::raw_svector_ostream os(sbuf);
568 os << "Returning without writing to '";
570 // Do not generate the note if failed to pretty-print.
571 if (!prettyPrintRegionName(FirstElement, FirstIsReferenceType,
572 MatchedRegion, FieldChain, IndirectionLevel, os))
576 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
579 /// Pretty-print region \p MatchedRegion to \p os.
580 /// \return Whether printing succeeded.
581 bool prettyPrintRegionName(StringRef FirstElement, bool FirstIsReferenceType,
582 const MemRegion *MatchedRegion,
583 const RegionVector &FieldChain,
584 int IndirectionLevel,
585 llvm::raw_svector_ostream &os) {
587 if (FirstIsReferenceType)
590 RegionVector RegionSequence;
592 // Add the regions in the reverse order, then reverse the resulting array.
593 assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
594 const MemRegion *R = RegionOfInterest;
595 while (R != MatchedRegion) {
596 RegionSequence.push_back(R);
597 R = cast<SubRegion>(R)->getSuperRegion();
599 std::reverse(RegionSequence.begin(), RegionSequence.end());
600 RegionSequence.append(FieldChain.begin(), FieldChain.end());
603 for (const MemRegion *R : RegionSequence) {
605 // Just keep going up to the base region.
606 // Element regions may appear due to casts.
607 if (isa<CXXBaseObjectRegion>(R) || isa<CXXTempObjectRegion>(R))
611 Sep = prettyPrintFirstElement(FirstElement,
612 /*MoreItemsExpected=*/true,
613 IndirectionLevel, os);
617 // Can only reasonably pretty-print DeclRegions.
618 if (!isa<DeclRegion>(R))
621 const auto *DR = cast<DeclRegion>(R);
622 Sep = DR->getValueType()->isAnyPointerType() ? "->" : ".";
623 DR->getDecl()->getDeclName().print(os, PP);
627 prettyPrintFirstElement(FirstElement,
628 /*MoreItemsExpected=*/false, IndirectionLevel,
633 /// Print first item in the chain, return new separator.
634 StringRef prettyPrintFirstElement(StringRef FirstElement,
635 bool MoreItemsExpected,
636 int IndirectionLevel,
637 llvm::raw_svector_ostream &os) {
640 if (IndirectionLevel > 0 && MoreItemsExpected) {
645 if (IndirectionLevel > 0 && MoreItemsExpected)
648 for (int i=0; i<IndirectionLevel; i++)
652 if (IndirectionLevel > 0 && MoreItemsExpected)
659 /// Suppress null-pointer-dereference bugs where dereferenced null was returned
661 class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
662 const SubRegion *RegionOfInterest;
663 const SVal ValueAtDereference;
665 // Do not invalidate the reports where the value was modified
666 // after it got assigned to from the macro.
667 bool WasModified = false;
670 MacroNullReturnSuppressionVisitor(const SubRegion *R,
671 const SVal V) : RegionOfInterest(R),
672 ValueAtDereference(V) {}
674 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
675 BugReporterContext &BRC,
676 BugReport &BR) override {
680 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
684 const SourceManager &SMgr = BRC.getSourceManager();
685 if (auto Loc = matchAssignment(N)) {
686 if (isFunctionMacroExpansion(*Loc, SMgr)) {
687 std::string MacroName = getMacroName(*Loc, BRC);
688 SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
689 if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
690 BR.markInvalid(getTag(), MacroName.c_str());
694 if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
700 static void addMacroVisitorIfNecessary(
701 const ExplodedNode *N, const MemRegion *R,
702 bool EnableNullFPSuppression, BugReport &BR,
704 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
705 if (EnableNullFPSuppression &&
706 Options.ShouldSuppressNullReturnPaths && V.getAs<Loc>())
707 BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
708 R->getAs<SubRegion>(), V));
711 void* getTag() const {
713 return static_cast<void *>(&Tag);
716 void Profile(llvm::FoldingSetNodeID &ID) const override {
717 ID.AddPointer(getTag());
721 /// \return Source location of right hand side of an assignment
722 /// into \c RegionOfInterest, empty optional if none found.
723 Optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
724 const Stmt *S = PathDiagnosticLocation::getStmt(N);
725 ProgramStateRef State = N->getState();
726 auto *LCtx = N->getLocationContext();
730 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
731 if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
732 if (const Expr *RHS = VD->getInit())
733 if (RegionOfInterest->isSubRegionOf(
734 State->getLValue(VD, LCtx).getAsRegion()))
735 return RHS->getBeginLoc();
736 } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
737 const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
738 const Expr *RHS = BO->getRHS();
739 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
740 return RHS->getBeginLoc();
747 /// Emits an extra note at the return statement of an interesting stack frame.
749 /// The returned value is marked as an interesting value, and if it's null,
750 /// adds a visitor to track where it became null.
752 /// This visitor is intended to be used when another visitor discovers that an
753 /// interesting value comes from an inlined function call.
754 class ReturnVisitor : public BugReporterVisitor {
755 const StackFrameContext *StackFrame;
762 bool EnableNullFPSuppression;
763 bool ShouldInvalidate = true;
764 AnalyzerOptions& Options;
767 ReturnVisitor(const StackFrameContext *Frame,
769 AnalyzerOptions &Options)
770 : StackFrame(Frame), EnableNullFPSuppression(Suppressed),
773 static void *getTag() {
775 return static_cast<void *>(&Tag);
778 void Profile(llvm::FoldingSetNodeID &ID) const override {
779 ID.AddPointer(ReturnVisitor::getTag());
780 ID.AddPointer(StackFrame);
781 ID.AddBoolean(EnableNullFPSuppression);
784 /// Adds a ReturnVisitor if the given statement represents a call that was
787 /// This will search back through the ExplodedGraph, starting from the given
788 /// node, looking for when the given statement was processed. If it turns out
789 /// the statement is a call that was inlined, we add the visitor to the
790 /// bug report, so it can print a note later.
791 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
793 bool InEnableNullFPSuppression) {
794 if (!CallEvent::isCallStmt(S))
797 // First, find when we processed the statement.
799 if (auto CEE = Node->getLocationAs<CallExitEnd>())
800 if (CEE->getCalleeContext()->getCallSite() == S)
802 if (auto SP = Node->getLocationAs<StmtPoint>())
803 if (SP->getStmt() == S)
806 Node = Node->getFirstPred();
809 // Next, step over any post-statement checks.
810 while (Node && Node->getLocation().getAs<PostStmt>())
811 Node = Node->getFirstPred();
815 // Finally, see if we inlined the call.
816 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
820 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
821 if (CalleeContext->getCallSite() != S)
824 // Check the return value.
825 ProgramStateRef State = Node->getState();
826 SVal RetVal = Node->getSVal(S);
828 // Handle cases where a reference is returned and then immediately used.
829 if (cast<Expr>(S)->isGLValue())
830 if (Optional<Loc> LValue = RetVal.getAs<Loc>())
831 RetVal = State->getSVal(*LValue);
833 // See if the return value is NULL. If so, suppress the report.
834 AnalyzerOptions &Options = State->getAnalysisManager().options;
836 bool EnableNullFPSuppression = false;
837 if (InEnableNullFPSuppression &&
838 Options.ShouldSuppressNullReturnPaths)
839 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
840 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
842 BR.markInteresting(CalleeContext);
843 BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
844 EnableNullFPSuppression,
848 std::shared_ptr<PathDiagnosticPiece>
849 visitNodeInitial(const ExplodedNode *N,
850 BugReporterContext &BRC, BugReport &BR) {
851 // Only print a message at the interesting return statement.
852 if (N->getLocationContext() != StackFrame)
855 Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
859 const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
863 // Okay, we're at the right return statement, but do we have the return
865 ProgramStateRef State = N->getState();
866 SVal V = State->getSVal(Ret, StackFrame);
867 if (V.isUnknownOrUndef())
870 // Don't print any more notes after this one.
873 const Expr *RetE = Ret->getRetValue();
874 assert(RetE && "Tracking a return value for a void function");
876 // Handle cases where a reference is returned and then immediately used.
877 Optional<Loc> LValue;
878 if (RetE->isGLValue()) {
879 if ((LValue = V.getAs<Loc>())) {
880 SVal RValue = State->getRawSVal(*LValue, RetE->getType());
881 if (RValue.getAs<DefinedSVal>())
886 // Ignore aggregate rvalues.
887 if (V.getAs<nonloc::LazyCompoundVal>() ||
888 V.getAs<nonloc::CompoundVal>())
891 RetE = RetE->IgnoreParenCasts();
893 // If we're returning 0, we should track where that 0 came from.
894 bugreporter::trackExpressionValue(N, RetE, BR, EnableNullFPSuppression);
896 // Build an appropriate message based on the return value.
898 llvm::raw_svector_ostream Out(Msg);
900 if (State->isNull(V).isConstrainedTrue()) {
901 if (V.getAs<Loc>()) {
903 // If we have counter-suppression enabled, make sure we keep visiting
904 // future nodes. We want to emit a path note as well, in case
905 // the report is resurrected as valid later on.
906 if (EnableNullFPSuppression &&
907 Options.ShouldAvoidSuppressingNullArgumentPaths)
908 Mode = MaybeUnsuppress;
910 if (RetE->getType()->isObjCObjectPointerType()) {
911 Out << "Returning nil";
913 Out << "Returning null pointer";
916 Out << "Returning zero";
920 if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
921 Out << "Returning the value " << CI->getValue();
922 } else if (V.getAs<Loc>()) {
923 Out << "Returning pointer";
925 Out << "Returning value";
930 if (const MemRegion *MR = LValue->getAsRegion()) {
931 if (MR->canPrintPretty()) {
932 Out << " (reference to ";
933 MR->printPretty(Out);
938 // FIXME: We should have a more generalized location printing mechanism.
939 if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
940 if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
941 Out << " (loaded from '" << *DD << "')";
944 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
945 if (!L.isValid() || !L.asLocation().isValid())
948 return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
951 std::shared_ptr<PathDiagnosticPiece>
952 visitNodeMaybeUnsuppress(const ExplodedNode *N,
953 BugReporterContext &BRC, BugReport &BR) {
955 assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
958 // Are we at the entry node for this call?
959 Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
963 if (CE->getCalleeContext() != StackFrame)
968 // Don't automatically suppress a report if one of the arguments is
969 // known to be a null pointer. Instead, start tracking /that/ null
970 // value back to its origin.
971 ProgramStateManager &StateMgr = BRC.getStateManager();
972 CallEventManager &CallMgr = StateMgr.getCallEventManager();
974 ProgramStateRef State = N->getState();
975 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
976 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
977 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
981 const Expr *ArgE = Call->getArgExpr(I);
985 // Is it possible for this argument to be non-null?
986 if (!State->isNull(*ArgV).isConstrainedTrue())
989 if (bugreporter::trackExpressionValue(N, ArgE, BR, EnableNullFPSuppression))
990 ShouldInvalidate = false;
992 // If we /can't/ track the null pointer, we should err on the side of
993 // false negatives, and continue towards marking this report invalid.
994 // (We will still look at the other arguments, though.)
1000 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
1001 BugReporterContext &BRC,
1002 BugReport &BR) override {
1005 return visitNodeInitial(N, BRC, BR);
1006 case MaybeUnsuppress:
1007 return visitNodeMaybeUnsuppress(N, BRC, BR);
1012 llvm_unreachable("Invalid visit mode!");
1015 void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
1016 BugReport &BR) override {
1017 if (EnableNullFPSuppression && ShouldInvalidate)
1018 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
1024 void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1026 ID.AddPointer(&tag);
1029 ID.AddBoolean(EnableNullFPSuppression);
1032 /// Returns true if \p N represents the DeclStmt declaring and initializing
1034 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
1035 Optional<PostStmt> P = N->getLocationAs<PostStmt>();
1039 const DeclStmt *DS = P->getStmtAs<DeclStmt>();
1043 if (DS->getSingleDecl() != VR->getDecl())
1046 const MemSpaceRegion *VarSpace = VR->getMemorySpace();
1047 const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
1049 // If we ever directly evaluate global DeclStmts, this assertion will be
1050 // invalid, but this still seems preferable to silently accepting an
1051 // initialization that may be for a path-sensitive variable.
1052 assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
1056 assert(VR->getDecl()->hasLocalStorage());
1057 const LocationContext *LCtx = N->getLocationContext();
1058 return FrameSpace->getStackFrame() == LCtx->getStackFrame();
1061 /// Show diagnostics for initializing or declaring a region \p R with a bad value.
1062 static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
1063 const MemRegion *R, SVal V, const DeclStmt *DS) {
1064 if (R->canPrintPretty()) {
1069 if (V.getAs<loc::ConcreteInt>()) {
1071 if (R->isBoundable()) {
1072 if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1073 if (TR->getValueType()->isObjCObjectPointerType()) {
1074 os << action << "nil";
1080 os << action << "a null pointer value";
1082 } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
1083 os << action << CVal->getValue();
1086 if (isa<VarRegion>(R)) {
1087 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
1088 if (VD->getInit()) {
1089 os << (R->canPrintPretty() ? "initialized" : "Initializing")
1090 << " to a garbage value";
1092 os << (R->canPrintPretty() ? "declared" : "Declaring")
1093 << " without an initial value";
1097 os << (R->canPrintPretty() ? "initialized" : "Initialized")
1103 /// Display diagnostics for passing bad region as a parameter.
1104 static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
1105 const VarRegion *VR,
1107 const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1111 if (V.getAs<loc::ConcreteInt>()) {
1112 if (Param->getType()->isObjCObjectPointerType())
1113 os << "nil object reference";
1115 os << "null pointer value";
1116 } else if (V.isUndef()) {
1117 os << "uninitialized value";
1118 } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1119 os << "the value " << CI->getValue();
1124 // Printed parameter indexes are 1-based, not 0-based.
1125 unsigned Idx = Param->getFunctionScopeIndex() + 1;
1126 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
1127 if (VR->canPrintPretty()) {
1129 VR->printPretty(os);
1133 /// Show default diagnostics for storing bad region.
1134 static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
1137 if (V.getAs<loc::ConcreteInt>()) {
1139 if (R->isBoundable()) {
1140 if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1141 if (TR->getValueType()->isObjCObjectPointerType()) {
1142 os << "nil object reference stored";
1148 if (R->canPrintPretty())
1149 os << "Null pointer value stored";
1151 os << "Storing null pointer value";
1154 } else if (V.isUndef()) {
1155 if (R->canPrintPretty())
1156 os << "Uninitialized value stored";
1158 os << "Storing uninitialized value";
1160 } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
1161 if (R->canPrintPretty())
1162 os << "The value " << CV->getValue() << " is assigned";
1164 os << "Assigning " << CV->getValue();
1167 if (R->canPrintPretty())
1168 os << "Value assigned";
1170 os << "Assigning value";
1173 if (R->canPrintPretty()) {
1179 std::shared_ptr<PathDiagnosticPiece>
1180 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
1181 BugReporterContext &BRC, BugReport &BR) {
1185 const ExplodedNode *StoreSite = nullptr;
1186 const ExplodedNode *Pred = Succ->getFirstPred();
1187 const Expr *InitE = nullptr;
1188 bool IsParam = false;
1190 // First see if we reached the declaration of the region.
1191 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1192 if (isInitializationOfVar(Pred, VR)) {
1194 InitE = VR->getDecl()->getInit();
1198 // If this is a post initializer expression, initializing the region, we
1199 // should track the initializer expression.
1200 if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
1201 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1202 if (FieldReg && FieldReg == R) {
1204 InitE = PIP->getInitializer()->getInit();
1208 // Otherwise, see if this is the store site:
1209 // (1) Succ has this binding and Pred does not, i.e. this is
1210 // where the binding first occurred.
1211 // (2) Succ has this binding and is a PostStore node for this region, i.e.
1212 // the same binding was re-assigned here.
1214 if (Succ->getState()->getSVal(R) != V)
1217 if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
1218 Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1219 if (!PS || PS->getLocationValue() != R)
1225 // If this is an assignment expression, we can track the value
1227 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
1228 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
1229 if (BO->isAssignmentOp())
1230 InitE = BO->getRHS();
1232 // If this is a call entry, the variable should be a parameter.
1233 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1234 // 'this' should never be NULL, but this visitor isn't just for NULL and
1236 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1237 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1239 const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1241 ProgramStateManager &StateMgr = BRC.getStateManager();
1242 CallEventManager &CallMgr = StateMgr.getCallEventManager();
1244 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
1246 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1251 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1252 // is wrapped inside of it.
1253 if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1254 InitE = TmpR->getExpr();
1261 // If we have an expression that provided the value, try to track where it
1265 V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1267 InitE = InitE->IgnoreParenCasts();
1268 bugreporter::trackExpressionValue(StoreSite, InitE, BR,
1269 EnableNullFPSuppression);
1271 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
1272 BR, EnableNullFPSuppression);
1275 // Okay, we've found the binding. Emit an appropriate message.
1276 SmallString<256> sbuf;
1277 llvm::raw_svector_ostream os(sbuf);
1279 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1280 const Stmt *S = PS->getStmt();
1281 const char *action = nullptr;
1282 const auto *DS = dyn_cast<DeclStmt>(S);
1283 const auto *VR = dyn_cast<VarRegion>(R);
1286 action = R->canPrintPretty() ? "initialized to " :
1288 } else if (isa<BlockExpr>(S)) {
1289 action = R->canPrintPretty() ? "captured by block as " :
1290 "Captured by block as ";
1292 // See if we can get the BlockVarRegion.
1293 ProgramStateRef State = StoreSite->getState();
1294 SVal V = StoreSite->getSVal(S);
1295 if (const auto *BDR =
1296 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1297 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1298 if (auto KV = State->getSVal(OriginalR).getAs<KnownSVal>())
1299 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1300 *KV, OriginalR, EnableNullFPSuppression));
1306 showBRDiagnostics(action, os, R, V, DS);
1308 } else if (StoreSite->getLocation().getAs<CallEnter>()) {
1309 if (const auto *VR = dyn_cast<VarRegion>(R))
1310 showBRParamDiagnostics(os, VR, V);
1313 if (os.str().empty())
1314 showBRDefaultDiagnostics(os, R, V);
1316 // Construct a new PathDiagnosticPiece.
1317 ProgramPoint P = StoreSite->getLocation();
1318 PathDiagnosticLocation L;
1319 if (P.getAs<CallEnter>() && InitE)
1320 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
1321 P.getLocationContext());
1323 if (!L.isValid() || !L.asLocation().isValid())
1324 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
1326 if (!L.isValid() || !L.asLocation().isValid())
1329 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1332 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1334 ID.AddPointer(&tag);
1335 ID.AddBoolean(Assumption);
1339 /// Return the tag associated with this visitor. This tag will be used
1340 /// to make all PathDiagnosticPieces created by this visitor.
1341 const char *TrackConstraintBRVisitor::getTag() {
1342 return "TrackConstraintBRVisitor";
1345 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1347 return N->getState()->isNull(Constraint).isUnderconstrained();
1348 return (bool)N->getState()->assume(Constraint, !Assumption);
1351 std::shared_ptr<PathDiagnosticPiece>
1352 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
1353 BugReporterContext &BRC, BugReport &) {
1354 const ExplodedNode *PrevN = N->getFirstPred();
1358 // Start tracking after we see the first state in which the value is
1360 if (!IsTrackingTurnedOn)
1361 if (!isUnderconstrained(N))
1362 IsTrackingTurnedOn = true;
1363 if (!IsTrackingTurnedOn)
1366 // Check if in the previous state it was feasible for this constraint
1367 // to *not* be true.
1368 if (isUnderconstrained(PrevN)) {
1371 // As a sanity check, make sure that the negation of the constraint
1372 // was infeasible in the current state. If it is feasible, we somehow
1373 // missed the transition point.
1374 assert(!isUnderconstrained(N));
1376 // We found the transition point for the constraint. We now need to
1377 // pretty-print the constraint. (work-in-progress)
1378 SmallString<64> sbuf;
1379 llvm::raw_svector_ostream os(sbuf);
1381 if (Constraint.getAs<Loc>()) {
1382 os << "Assuming pointer value is ";
1383 os << (Assumption ? "non-null" : "null");
1386 if (os.str().empty())
1389 // Construct a new PathDiagnosticPiece.
1390 ProgramPoint P = N->getLocation();
1391 PathDiagnosticLocation L =
1392 PathDiagnosticLocation::create(P, BRC.getSourceManager());
1396 auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1397 X->setTag(getTag());
1398 return std::move(X);
1404 SuppressInlineDefensiveChecksVisitor::
1405 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
1407 // Check if the visitor is disabled.
1408 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
1409 if (!Options.ShouldSuppressInlinedDefensiveChecks)
1412 assert(N->getState()->isNull(V).isConstrainedTrue() &&
1413 "The visitor only tracks the cases where V is constrained to 0");
1416 void SuppressInlineDefensiveChecksVisitor::Profile(
1417 llvm::FoldingSetNodeID &ID) const {
1423 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
1424 return "IDCVisitor";
1427 std::shared_ptr<PathDiagnosticPiece>
1428 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
1429 BugReporterContext &BRC,
1431 const ExplodedNode *Pred = Succ->getFirstPred();
1435 // Start tracking after we see the first state in which the value is null.
1436 if (!IsTrackingTurnedOn)
1437 if (Succ->getState()->isNull(V).isConstrainedTrue())
1438 IsTrackingTurnedOn = true;
1439 if (!IsTrackingTurnedOn)
1442 // Check if in the previous state it was feasible for this value
1443 // to *not* be null.
1444 if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
1447 assert(Succ->getState()->isNull(V).isConstrainedTrue());
1449 // Check if this is inlined defensive checks.
1450 const LocationContext *CurLC =Succ->getLocationContext();
1451 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
1452 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
1453 BR.markInvalid("Suppress IDC", CurLC);
1457 // Treat defensive checks in function-like macros as if they were an inlined
1458 // defensive check. If the bug location is not in a macro and the
1459 // terminator for the current location is in a macro then suppress the
1461 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1466 ProgramPoint CurPoint = Succ->getLocation();
1467 const Stmt *CurTerminatorStmt = nullptr;
1468 if (auto BE = CurPoint.getAs<BlockEdge>()) {
1469 CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1470 } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1471 const Stmt *CurStmt = SP->getStmt();
1472 if (!CurStmt->getBeginLoc().isMacroID())
1475 CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1476 CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
1481 if (!CurTerminatorStmt)
1484 SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
1485 if (TerminatorLoc.isMacroID()) {
1486 SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
1488 // Suppress reports unless we are in that same macro.
1489 if (!BugLoc.isMacroID() ||
1490 getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1491 BR.markInvalid("Suppress Macro IDC", CurLC);
1499 static const MemRegion *getLocationRegionIfReference(const Expr *E,
1500 const ExplodedNode *N) {
1501 if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
1502 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1503 if (!VD->getType()->isReferenceType())
1505 ProgramStateManager &StateMgr = N->getState()->getStateManager();
1506 MemRegionManager &MRMgr = StateMgr.getRegionManager();
1507 return MRMgr.getVarRegion(VD, N->getLocationContext());
1511 // FIXME: This does not handle other kinds of null references,
1512 // for example, references from FieldRegions:
1513 // struct Wrapper { int &ref; };
1514 // Wrapper w = { *(int *)0 };
1520 /// \return A subexpression of {@code Ex} which represents the
1521 /// expression-of-interest.
1522 static const Expr *peelOffOuterExpr(const Expr *Ex,
1523 const ExplodedNode *N) {
1524 Ex = Ex->IgnoreParenCasts();
1525 if (const auto *FE = dyn_cast<FullExpr>(Ex))
1526 return peelOffOuterExpr(FE->getSubExpr(), N);
1527 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1528 return peelOffOuterExpr(OVE->getSourceExpr(), N);
1529 if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1530 const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1531 if (PropRef && PropRef->isMessagingGetter()) {
1532 const Expr *GetterMessageSend =
1533 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1534 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1535 return peelOffOuterExpr(GetterMessageSend, N);
1539 // Peel off the ternary operator.
1540 if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
1541 // Find a node where the branching occurred and find out which branch
1542 // we took (true/false) by looking at the ExplodedGraph.
1543 const ExplodedNode *NI = N;
1545 ProgramPoint ProgPoint = NI->getLocation();
1546 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1547 const CFGBlock *srcBlk = BE->getSrc();
1548 if (const Stmt *term = srcBlk->getTerminator()) {
1550 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1552 return peelOffOuterExpr(CO->getTrueExpr(), N);
1554 return peelOffOuterExpr(CO->getFalseExpr(), N);
1558 NI = NI->getFirstPred();
1562 if (auto *BO = dyn_cast<BinaryOperator>(Ex))
1563 if (const Expr *SubEx = peelOffPointerArithmetic(BO))
1564 return peelOffOuterExpr(SubEx, N);
1566 if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
1567 if (UO->getOpcode() == UO_LNot)
1568 return peelOffOuterExpr(UO->getSubExpr(), N);
1570 // FIXME: There's a hack in our Store implementation that always computes
1571 // field offsets around null pointers as if they are always equal to 0.
1572 // The idea here is to report accesses to fields as null dereferences
1573 // even though the pointer value that's being dereferenced is actually
1574 // the offset of the field rather than exactly 0.
1575 // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1576 // This code interacts heavily with this hack; otherwise the value
1577 // would not be null at all for most fields, so we'd be unable to track it.
1578 if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue())
1579 if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
1580 return peelOffOuterExpr(DerefEx, N);
1586 /// Find the ExplodedNode where the lvalue (the value of 'Ex')
1588 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1589 const Expr *Inner) {
1591 if (PathDiagnosticLocation::getStmt(N) == Inner)
1593 N = N->getFirstPred();
1598 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
1599 const Expr *E, BugReport &report,
1600 bool EnableNullFPSuppression) {
1601 if (!E || !InputNode)
1604 const Expr *Inner = peelOffOuterExpr(E, InputNode);
1605 const ExplodedNode *LVNode = findNodeForExpression(InputNode, Inner);
1609 ProgramStateRef LVState = LVNode->getState();
1611 // The message send could be nil due to the receiver being nil.
1612 // At this point in the path, the receiver should be live since we are at the
1613 // message send expr. If it is nil, start tracking it.
1614 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
1615 trackExpressionValue(LVNode, Receiver, report, EnableNullFPSuppression);
1617 // See if the expression we're interested refers to a variable.
1618 // If so, we can track both its contents and constraints on its value.
1619 if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
1620 SVal LVal = LVNode->getSVal(Inner);
1622 const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
1623 bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1625 // If this is a C++ reference to a null pointer, we are tracking the
1626 // pointer. In addition, we should find the store at which the reference
1628 if (RR && !LVIsNull)
1629 if (auto KV = LVal.getAs<KnownSVal>())
1630 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1631 *KV, RR, EnableNullFPSuppression));
1633 // In case of C++ references, we want to differentiate between a null
1634 // reference and reference to null pointer.
1635 // If the LVal is null, check if we are dealing with null reference.
1636 // For those, we want to track the location of the reference.
1637 const MemRegion *R = (RR && LVIsNull) ? RR :
1638 LVNode->getSVal(Inner).getAsRegion();
1642 // Mark both the variable region and its contents as interesting.
1643 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1645 llvm::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R)));
1647 MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1648 LVNode, R, EnableNullFPSuppression, report, V);
1650 report.markInteresting(V);
1651 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1653 // If the contents are symbolic, find out when they became null.
1654 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1655 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1656 V.castAs<DefinedSVal>(), false));
1658 // Add visitor, which will suppress inline defensive checks.
1659 if (auto DV = V.getAs<DefinedSVal>())
1660 if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1661 EnableNullFPSuppression)
1663 llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1666 if (auto KV = V.getAs<KnownSVal>())
1667 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1668 *KV, R, EnableNullFPSuppression));
1673 // If the expression is not an "lvalue expression", we can still
1674 // track the constraints on its contents.
1675 SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext());
1677 ReturnVisitor::addVisitorIfNecessary(
1678 LVNode, Inner, report, EnableNullFPSuppression);
1680 // Is it a symbolic value?
1681 if (auto L = V.getAs<loc::MemRegionVal>()) {
1682 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1684 // FIXME: this is a hack for fixing a later crash when attempting to
1685 // dereference a void* pointer.
1686 // We should not try to dereference pointers at all when we don't care
1687 // what is written inside the pointer.
1688 bool CanDereference = true;
1689 if (const auto *SR = dyn_cast<SymbolicRegion>(L->getRegion()))
1690 if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
1691 CanDereference = false;
1693 // At this point we are dealing with the region's LValue.
1694 // However, if the rvalue is a symbolic region, we should track it as well.
1695 // Try to use the correct type when looking up the value.
1697 if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
1698 RVal = LVState->getRawSVal(L.getValue(), Inner->getType());
1699 } else if (CanDereference) {
1700 RVal = LVState->getSVal(L->getRegion());
1704 if (auto KV = RVal.getAs<KnownSVal>())
1705 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1706 *KV, L->getRegion(), EnableNullFPSuppression));
1708 const MemRegion *RegionRVal = RVal.getAsRegion();
1709 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1710 report.markInteresting(RegionRVal);
1711 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1712 loc::MemRegionVal(RegionRVal), /*assumption=*/false));
1718 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1719 const ExplodedNode *N) {
1720 const auto *ME = dyn_cast<ObjCMessageExpr>(S);
1723 if (const Expr *Receiver = ME->getInstanceReceiver()) {
1724 ProgramStateRef state = N->getState();
1725 SVal V = N->getSVal(Receiver);
1726 if (state->isNull(V).isConstrainedTrue())
1732 std::shared_ptr<PathDiagnosticPiece>
1733 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1734 BugReporterContext &BRC, BugReport &BR) {
1735 Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1739 const Stmt *S = P->getStmt();
1740 const Expr *Receiver = getNilReceiver(S, N);
1744 llvm::SmallString<256> Buf;
1745 llvm::raw_svector_ostream OS(Buf);
1747 if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1749 ME->getSelector().print(OS);
1750 OS << "' not called";
1753 OS << "No method is called";
1755 OS << " because the receiver is nil";
1757 // The receiver was nil, and hence the method was skipped.
1758 // Register a BugReporterVisitor to issue a message telling us how
1759 // the receiver was null.
1760 bugreporter::trackExpressionValue(N, Receiver, BR,
1761 /*EnableNullFPSuppression*/ false);
1762 // Issue a message saying that the method was skipped.
1763 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1764 N->getLocationContext());
1765 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1768 // Registers every VarDecl inside a Stmt with a last store visitor.
1769 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1771 bool EnableNullFPSuppression) {
1772 const ExplodedNode *N = BR.getErrorNode();
1773 std::deque<const Stmt *> WorkList;
1774 WorkList.push_back(S);
1776 while (!WorkList.empty()) {
1777 const Stmt *Head = WorkList.front();
1778 WorkList.pop_front();
1780 ProgramStateManager &StateMgr = N->getState()->getStateManager();
1782 if (const auto *DR = dyn_cast<DeclRefExpr>(Head)) {
1783 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1784 const VarRegion *R =
1785 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1787 // What did we load?
1788 SVal V = N->getSVal(S);
1790 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1791 // Register a new visitor with the BugReport.
1792 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1793 V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1798 for (const Stmt *SubStmt : Head->children())
1799 WorkList.push_back(SubStmt);
1803 //===----------------------------------------------------------------------===//
1804 // Visitor that tries to report interesting diagnostics from conditions.
1805 //===----------------------------------------------------------------------===//
1807 /// Return the tag associated with this visitor. This tag will be used
1808 /// to make all PathDiagnosticPieces created by this visitor.
1809 const char *ConditionBRVisitor::getTag() {
1810 return "ConditionBRVisitor";
1813 std::shared_ptr<PathDiagnosticPiece>
1814 ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1815 BugReporterContext &BRC, BugReport &BR) {
1816 auto piece = VisitNodeImpl(N, BRC, BR);
1818 piece->setTag(getTag());
1819 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1820 ev->setPrunable(true, /* override */ false);
1825 std::shared_ptr<PathDiagnosticPiece>
1826 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1827 BugReporterContext &BRC, BugReport &BR) {
1828 ProgramPoint progPoint = N->getLocation();
1829 ProgramStateRef CurrentState = N->getState();
1830 ProgramStateRef PrevState = N->getFirstPred()->getState();
1832 // Compare the GDMs of the state, because that is where constraints
1833 // are managed. Note that ensure that we only look at nodes that
1834 // were generated by the analyzer engine proper, not checkers.
1835 if (CurrentState->getGDM().getRoot() ==
1836 PrevState->getGDM().getRoot())
1839 // If an assumption was made on a branch, it should be caught
1840 // here by looking at the state transition.
1841 if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1842 const CFGBlock *srcBlk = BE->getSrc();
1843 if (const Stmt *term = srcBlk->getTerminator())
1844 return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1848 if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1849 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1850 ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
1852 const ProgramPointTag *tag = PS->getTag();
1853 if (tag == tags.first)
1854 return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1856 if (tag == tags.second)
1857 return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1866 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1867 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1868 const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1869 const Expr *Cond = nullptr;
1871 // In the code below, Term is a CFG terminator and Cond is a branch condition
1872 // expression upon which the decision is made on this terminator.
1874 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1875 // and "x == 0" is the respective condition.
1877 // Another example: in "if (x && y)", we've got two terminators and two
1878 // conditions due to short-circuit nature of operator "&&":
1879 // 1. The "if (x && y)" statement is a terminator,
1880 // and "y" is the respective condition.
1881 // 2. Also "x && ..." is another terminator,
1882 // and "x" is its condition.
1884 switch (Term->getStmtClass()) {
1885 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1886 // more tricky because there are more than two branches to account for.
1889 case Stmt::IfStmtClass:
1890 Cond = cast<IfStmt>(Term)->getCond();
1892 case Stmt::ConditionalOperatorClass:
1893 Cond = cast<ConditionalOperator>(Term)->getCond();
1895 case Stmt::BinaryOperatorClass:
1896 // When we encounter a logical operator (&& or ||) as a CFG terminator,
1897 // then the condition is actually its LHS; otherwise, we'd encounter
1898 // the parent, such as if-statement, as a terminator.
1899 const auto *BO = cast<BinaryOperator>(Term);
1900 assert(BO->isLogicalOp() &&
1901 "CFG terminator is not a short-circuit operator!");
1902 Cond = BO->getLHS();
1906 // However, when we encounter a logical operator as a branch condition,
1907 // then the condition is actually its RHS, because LHS would be
1908 // the condition for the logical operator terminator.
1909 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1910 if (!InnerBO->isLogicalOp())
1912 Cond = InnerBO->getRHS()->IgnoreParens();
1916 assert(srcBlk->succ_size() == 2);
1917 const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1918 return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1921 std::shared_ptr<PathDiagnosticPiece>
1922 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1923 BugReporterContext &BRC, BugReport &R,
1924 const ExplodedNode *N) {
1925 // These will be modified in code below, but we need to preserve the original
1926 // values in case we want to throw the generic message.
1927 const Expr *CondTmp = Cond;
1928 bool tookTrueTmp = tookTrue;
1931 CondTmp = CondTmp->IgnoreParenCasts();
1932 switch (CondTmp->getStmtClass()) {
1935 case Stmt::BinaryOperatorClass:
1936 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1937 tookTrueTmp, BRC, R, N))
1940 case Stmt::DeclRefExprClass:
1941 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1942 tookTrueTmp, BRC, R, N))
1945 case Stmt::UnaryOperatorClass: {
1946 const auto *UO = cast<UnaryOperator>(CondTmp);
1947 if (UO->getOpcode() == UO_LNot) {
1948 tookTrueTmp = !tookTrueTmp;
1949 CondTmp = UO->getSubExpr();
1958 // Condition too complex to explain? Just say something so that the user
1959 // knew we've made some path decision at this point.
1960 const LocationContext *LCtx = N->getLocationContext();
1961 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1962 if (!Loc.isValid() || !Loc.asLocation().isValid())
1965 return std::make_shared<PathDiagnosticEventPiece>(
1966 Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1969 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1970 const Expr *ParentEx,
1972 BugReporterContext &BRC,
1974 const ExplodedNode *N,
1975 Optional<bool> &prunable) {
1976 const Expr *OriginalExpr = Ex;
1977 Ex = Ex->IgnoreParenCasts();
1979 // Use heuristics to determine if Ex is a macro expending to a literal and
1980 // if so, use the macro's name.
1981 SourceLocation LocStart = Ex->getBeginLoc();
1982 SourceLocation LocEnd = Ex->getEndLoc();
1983 if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1984 (isa<GNUNullExpr>(Ex) ||
1985 isa<ObjCBoolLiteralExpr>(Ex) ||
1986 isa<CXXBoolLiteralExpr>(Ex) ||
1987 isa<IntegerLiteral>(Ex) ||
1988 isa<FloatingLiteral>(Ex))) {
1989 StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1990 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1991 StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1992 BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1993 bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1995 bool partOfParentMacro = false;
1996 if (ParentEx->getBeginLoc().isMacroID()) {
1997 StringRef PName = Lexer::getImmediateMacroNameForDiagnostics(
1998 ParentEx->getBeginLoc(), BRC.getSourceManager(),
1999 BRC.getASTContext().getLangOpts());
2000 partOfParentMacro = PName.equals(StartName);
2003 if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
2004 // Get the location of the macro name as written by the caller.
2005 SourceLocation Loc = LocStart;
2006 while (LocStart.isMacroID()) {
2008 LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
2010 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
2011 Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
2013 // Return the macro name.
2019 if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
2020 const bool quotes = isa<VarDecl>(DR->getDecl());
2023 const LocationContext *LCtx = N->getLocationContext();
2024 const ProgramState *state = N->getState().get();
2025 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
2026 LCtx).getAsRegion()) {
2027 if (report.isInteresting(R))
2030 const ProgramState *state = N->getState().get();
2031 SVal V = state->getSVal(R);
2032 if (report.isInteresting(V))
2037 Out << DR->getDecl()->getDeclName().getAsString();
2043 if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
2044 QualType OriginalTy = OriginalExpr->getType();
2045 if (OriginalTy->isPointerType()) {
2046 if (IL->getValue() == 0) {
2051 else if (OriginalTy->isObjCObjectPointerType()) {
2052 if (IL->getValue() == 0) {
2058 Out << IL->getValue();
2065 std::shared_ptr<PathDiagnosticPiece>
2066 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
2067 const bool tookTrue, BugReporterContext &BRC,
2068 BugReport &R, const ExplodedNode *N) {
2069 bool shouldInvert = false;
2070 Optional<bool> shouldPrune;
2072 SmallString<128> LhsString, RhsString;
2074 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
2075 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
2076 BRC, R, N, shouldPrune);
2077 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
2078 BRC, R, N, shouldPrune);
2080 shouldInvert = !isVarLHS && isVarRHS;
2083 BinaryOperator::Opcode Op = BExpr->getOpcode();
2085 if (BinaryOperator::isAssignmentOp(Op)) {
2086 // For assignment operators, all that we care about is that the LHS
2087 // evaluates to "true" or "false".
2088 return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
2092 // For non-assignment operations, we require that we can understand
2093 // both the LHS and RHS.
2094 if (LhsString.empty() || RhsString.empty() ||
2095 !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
2098 // Should we invert the strings if the LHS is not a variable name?
2099 SmallString<256> buf;
2100 llvm::raw_svector_ostream Out(buf);
2101 Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
2103 // Do we need to invert the opcode?
2107 case BO_LT: Op = BO_GT; break;
2108 case BO_GT: Op = BO_LT; break;
2109 case BO_LE: Op = BO_GE; break;
2110 case BO_GE: Op = BO_LE; break;
2115 case BO_EQ: Op = BO_NE; break;
2116 case BO_NE: Op = BO_EQ; break;
2117 case BO_LT: Op = BO_GE; break;
2118 case BO_GT: Op = BO_LE; break;
2119 case BO_LE: Op = BO_GT; break;
2120 case BO_GE: Op = BO_LT; break;
2130 Out << "not equal to ";
2133 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
2137 Out << (shouldInvert ? LhsString : RhsString);
2138 const LocationContext *LCtx = N->getLocationContext();
2139 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2140 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2141 if (shouldPrune.hasValue())
2142 event->setPrunable(shouldPrune.getValue());
2146 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
2147 StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
2148 BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
2149 // FIXME: If there's already a constraint tracker for this variable,
2150 // we shouldn't emit anything here (c.f. the double note in
2151 // test/Analysis/inlining/path-notes.c)
2152 SmallString<256> buf;
2153 llvm::raw_svector_ostream Out(buf);
2154 Out << "Assuming " << LhsString << " is ";
2156 QualType Ty = CondVarExpr->getType();
2158 if (Ty->isPointerType())
2159 Out << (tookTrue ? "not null" : "null");
2160 else if (Ty->isObjCObjectPointerType())
2161 Out << (tookTrue ? "not nil" : "nil");
2162 else if (Ty->isBooleanType())
2163 Out << (tookTrue ? "true" : "false");
2164 else if (Ty->isIntegralOrEnumerationType())
2165 Out << (tookTrue ? "non-zero" : "zero");
2169 const LocationContext *LCtx = N->getLocationContext();
2170 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
2171 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2173 if (const auto *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
2174 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2175 const ProgramState *state = N->getState().get();
2176 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2177 if (report.isInteresting(R))
2178 event->setPrunable(false);
2186 std::shared_ptr<PathDiagnosticPiece>
2187 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
2188 const bool tookTrue, BugReporterContext &BRC,
2189 BugReport &report, const ExplodedNode *N) {
2190 const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
2194 SmallString<256> Buf;
2195 llvm::raw_svector_ostream Out(Buf);
2197 Out << "Assuming '" << VD->getDeclName() << "' is ";
2199 QualType VDTy = VD->getType();
2201 if (VDTy->isPointerType())
2202 Out << (tookTrue ? "non-null" : "null");
2203 else if (VDTy->isObjCObjectPointerType())
2204 Out << (tookTrue ? "non-nil" : "nil");
2205 else if (VDTy->isScalarType())
2206 Out << (tookTrue ? "not equal to 0" : "0");
2210 const LocationContext *LCtx = N->getLocationContext();
2211 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2212 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2214 const ProgramState *state = N->getState().get();
2215 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2216 if (report.isInteresting(R))
2217 event->setPrunable(false);
2219 SVal V = state->getSVal(R);
2220 if (report.isInteresting(V))
2221 event->setPrunable(false);
2224 return std::move(event);
2227 const char *const ConditionBRVisitor::GenericTrueMessage =
2228 "Assuming the condition is true";
2229 const char *const ConditionBRVisitor::GenericFalseMessage =
2230 "Assuming the condition is false";
2232 bool ConditionBRVisitor::isPieceMessageGeneric(
2233 const PathDiagnosticPiece *Piece) {
2234 return Piece->getString() == GenericTrueMessage ||
2235 Piece->getString() == GenericFalseMessage;
2238 void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
2239 BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR) {
2240 // Here we suppress false positives coming from system headers. This list is
2241 // based on known issues.
2242 AnalyzerOptions &Options = BRC.getAnalyzerOptions();
2243 const Decl *D = N->getLocationContext()->getDecl();
2245 if (AnalysisDeclContext::isInStdNamespace(D)) {
2246 // Skip reports within the 'std' namespace. Although these can sometimes be
2247 // the user's fault, we currently don't report them very well, and
2248 // Note that this will not help for any other data structure libraries, like
2249 // TR1, Boost, or llvm/ADT.
2250 if (Options.ShouldSuppressFromCXXStandardLibrary) {
2251 BR.markInvalid(getTag(), nullptr);
2254 // If the complete 'std' suppression is not enabled, suppress reports
2255 // from the 'std' namespace that are known to produce false positives.
2257 // The analyzer issues a false use-after-free when std::list::pop_front
2258 // or std::list::pop_back are called multiple times because we cannot
2259 // reason about the internal invariants of the data structure.
2260 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2261 const CXXRecordDecl *CD = MD->getParent();
2262 if (CD->getName() == "list") {
2263 BR.markInvalid(getTag(), nullptr);
2268 // The analyzer issues a false positive when the constructor of
2269 // std::__independent_bits_engine from algorithms is used.
2270 if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
2271 const CXXRecordDecl *CD = MD->getParent();
2272 if (CD->getName() == "__independent_bits_engine") {
2273 BR.markInvalid(getTag(), nullptr);
2278 for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
2279 LCtx = LCtx->getParent()) {
2280 const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
2284 const CXXRecordDecl *CD = MD->getParent();
2285 // The analyzer issues a false positive on
2286 // std::basic_string<uint8_t> v; v.push_back(1);
2288 // std::u16string s; s += u'a';
2289 // because we cannot reason about the internal invariants of the
2291 if (CD->getName() == "basic_string") {
2292 BR.markInvalid(getTag(), nullptr);
2296 // The analyzer issues a false positive on
2297 // std::shared_ptr<int> p(new int(1)); p = nullptr;
2298 // because it does not reason properly about temporary destructors.
2299 if (CD->getName() == "shared_ptr") {
2300 BR.markInvalid(getTag(), nullptr);
2307 // Skip reports within the sys/queue.h macros as we do not have the ability to
2308 // reason about data structure shapes.
2309 SourceManager &SM = BRC.getSourceManager();
2310 FullSourceLoc Loc = BR.getLocation(SM).asLocation();
2311 while (Loc.isMacroID()) {
2312 Loc = Loc.getSpellingLoc();
2313 if (SM.getFilename(Loc).endswith("sys/queue.h")) {
2314 BR.markInvalid(getTag(), nullptr);
2320 std::shared_ptr<PathDiagnosticPiece>
2321 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
2322 BugReporterContext &BRC, BugReport &BR) {
2323 ProgramStateRef State = N->getState();
2324 ProgramPoint ProgLoc = N->getLocation();
2326 // We are only interested in visiting CallEnter nodes.
2327 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
2331 // Check if one of the arguments is the region the visitor is tracking.
2332 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
2333 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
2335 ArrayRef<ParmVarDecl *> parms = Call->parameters();
2337 for (const auto ParamDecl : parms) {
2338 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
2341 // Are we tracking the argument or its subregion?
2342 if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
2345 // Check the function parameter type.
2346 assert(ParamDecl && "Formal parameter has no decl?");
2347 QualType T = ParamDecl->getType();
2349 if (!(T->isAnyPointerType() || T->isReferenceType())) {
2350 // Function can only change the value passed in by address.
2354 // If it is a const pointer value, the function does not intend to
2355 // change the value.
2356 if (T->getPointeeType().isConstQualified())
2359 // Mark the call site (LocationContext) as interesting if the value of the
2360 // argument is undefined or '0'/'NULL'.
2361 SVal BoundVal = State->getSVal(R);
2362 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
2363 BR.markInteresting(CEnter->getCalleeContext());
2370 std::shared_ptr<PathDiagnosticPiece>
2371 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
2372 BugReporterContext &BRC, BugReport &) {
2376 const auto Edge = Succ->getLocation().getAs<BlockEdge>();
2377 if (!Edge.hasValue())
2380 auto Tag = Edge->getTag();
2384 if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
2390 dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
2391 assert(Met && "Not a C++ method.");
2392 assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
2393 "Not a copy/move assignment operator.");
2395 const auto *LCtx = Edge->getLocationContext();
2397 const auto &State = Succ->getState();
2398 auto &SVB = State->getStateManager().getSValBuilder();
2401 State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
2403 State->getSVal(SVB.getCXXThis(Met, LCtx->getStackFrame()));
2405 auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
2407 if (!L.isValid() || !L.asLocation().isValid())
2410 SmallString<256> Buf;
2411 llvm::raw_svector_ostream Out(Buf);
2413 Out << "Assuming " << Met->getParamDecl(0)->getName() <<
2414 ((Param == This) ? " == " : " != ") << "*this";
2416 auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
2417 Piece->addRange(Met->getSourceRange());
2419 return std::move(Piece);
2422 std::shared_ptr<PathDiagnosticPiece>
2423 TaintBugVisitor::VisitNode(const ExplodedNode *N,
2424 BugReporterContext &BRC, BugReport &) {
2426 // Find the ExplodedNode where the taint was first introduced
2427 if (!N->getState()->isTainted(V) || N->getFirstPred()->getState()->isTainted(V))
2430 const Stmt *S = PathDiagnosticLocation::getStmt(N);
2434 const LocationContext *NCtx = N->getLocationContext();
2435 PathDiagnosticLocation L =
2436 PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);
2437 if (!L.isValid() || !L.asLocation().isValid())
2440 return std::make_shared<PathDiagnosticEventPiece>(L, "Taint originated here");
2443 FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
2444 : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
2446 void FalsePositiveRefutationBRVisitor::finalizeVisitor(
2447 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
2448 // Collect new constraints
2449 VisitNode(EndPathNode, BRC, BR);
2451 // Create a refutation manager
2452 SMTSolverRef RefutationSolver = CreateZ3Solver();
2453 ASTContext &Ctx = BRC.getASTContext();
2455 // Add constraints to the solver
2456 for (const auto &I : Constraints) {
2457 const SymbolRef Sym = I.first;
2458 auto RangeIt = I.second.begin();
2460 SMTExprRef Constraints = SMTConv::getRangeExpr(
2461 RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
2463 while ((++RangeIt) != I.second.end()) {
2464 Constraints = RefutationSolver->mkOr(
2465 Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
2466 RangeIt->From(), RangeIt->To(),
2470 RefutationSolver->addConstraint(Constraints);
2473 // And check for satisfiability
2474 Optional<bool> isSat = RefutationSolver->check();
2475 if (!isSat.hasValue())
2478 if (!isSat.getValue())
2479 BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
2482 std::shared_ptr<PathDiagnosticPiece>
2483 FalsePositiveRefutationBRVisitor::VisitNode(const ExplodedNode *N,
2484 BugReporterContext &,
2486 // Collect new constraints
2487 const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
2488 ConstraintRangeTy::Factory &CF =
2489 N->getState()->get_context<ConstraintRange>();
2491 // Add constraints if we don't have them yet
2492 for (auto const &C : NewCs) {
2493 const SymbolRef &Sym = C.first;
2494 if (!Constraints.contains(Sym)) {
2495 Constraints = CF.add(Constraints, Sym, C.second);
2502 void FalsePositiveRefutationBRVisitor::Profile(
2503 llvm::FoldingSetNodeID &ID) const {
2505 ID.AddPointer(&Tag);