1 //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines a set of BugReporter "visitors" which can be used to
10 // enhance the diagnostics reported for a bug.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclBase.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/Type.h"
24 #include "clang/ASTMatchers/ASTMatchFinder.h"
25 #include "clang/Analysis/Analyses/Dominators.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 static 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 static Optional<const llvm::APSInt *>
184 getConcreteIntegerValue(const Expr *CondVarExpr, const ExplodedNode *N) {
185 ProgramStateRef State = N->getState();
186 const LocationContext *LCtx = N->getLocationContext();
188 // The declaration of the value may rely on a pointer so take its l-value.
189 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(CondVarExpr)) {
190 if (const auto *VD = dyn_cast_or_null<VarDecl>(DRE->getDecl())) {
191 SVal DeclSVal = State->getSVal(State->getLValue(VD, LCtx));
192 if (auto DeclCI = DeclSVal.getAs<nonloc::ConcreteInt>())
193 return &DeclCI->getValue();
200 /// \return name of the macro inside the location \p Loc.
201 static StringRef getMacroName(SourceLocation Loc,
202 BugReporterContext &BRC) {
203 return Lexer::getImmediateMacroName(
205 BRC.getSourceManager(),
206 BRC.getASTContext().getLangOpts());
209 /// \return Whether given spelling location corresponds to an expansion
210 /// of a function-like macro.
211 static bool isFunctionMacroExpansion(SourceLocation Loc,
212 const SourceManager &SM) {
213 if (!Loc.isMacroID())
215 while (SM.isMacroArgExpansion(Loc))
216 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
217 std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
218 SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
219 const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
220 return EInfo.isFunctionMacroExpansion();
223 /// \return Whether \c RegionOfInterest was modified at \p N,
224 /// where \p ValueAfter is \c RegionOfInterest's value at the end of the
226 static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest,
227 const ExplodedNode *N,
229 ProgramStateRef State = N->getState();
230 ProgramStateManager &Mgr = N->getState()->getStateManager();
232 if (!N->getLocationAs<PostStore>() && !N->getLocationAs<PostInitializer>() &&
233 !N->getLocationAs<PostStmt>())
236 // Writing into region of interest.
237 if (auto PS = N->getLocationAs<PostStmt>())
238 if (auto *BO = PS->getStmtAs<BinaryOperator>())
239 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
240 N->getSVal(BO->getLHS()).getAsRegion()))
243 // SVal after the state is possibly different.
244 SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
245 if (!Mgr.getSValBuilder()
246 .areEqual(State, ValueAtN, ValueAfter)
247 .isConstrainedTrue() &&
248 (!ValueAtN.isUndef() || !ValueAfter.isUndef()))
254 //===----------------------------------------------------------------------===//
255 // Implementation of BugReporterVisitor.
256 //===----------------------------------------------------------------------===//
258 std::shared_ptr<PathDiagnosticPiece>
259 BugReporterVisitor::getEndPath(BugReporterContext &,
260 const ExplodedNode *, BugReport &) {
265 BugReporterVisitor::finalizeVisitor(BugReporterContext &,
266 const ExplodedNode *, BugReport &) {}
268 std::shared_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
269 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
270 PathDiagnosticLocation L =
271 PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
273 const auto &Ranges = BR.getRanges();
275 // Only add the statement itself as a range if we didn't specify any
276 // special ranges for this report.
277 auto P = std::make_shared<PathDiagnosticEventPiece>(
278 L, BR.getDescription(), Ranges.begin() == Ranges.end());
279 for (SourceRange Range : Ranges)
285 //===----------------------------------------------------------------------===//
286 // Implementation of NoStoreFuncVisitor.
287 //===----------------------------------------------------------------------===//
291 /// Put a diagnostic on return statement of all inlined functions
292 /// for which the region of interest \p RegionOfInterest was passed into,
293 /// but not written inside, and it has caused an undefined read or a null
294 /// pointer dereference outside.
295 class NoStoreFuncVisitor final : public BugReporterVisitor {
296 const SubRegion *RegionOfInterest;
297 MemRegionManager &MmrMgr;
298 const SourceManager &SM;
299 const PrintingPolicy &PP;
301 /// Recursion limit for dereferencing fields when looking for the
302 /// region of interest.
303 /// The limit of two indicates that we will dereference fields only once.
304 static const unsigned DEREFERENCE_LIMIT = 2;
306 /// Frames writing into \c RegionOfInterest.
307 /// This visitor generates a note only if a function does not write into
308 /// a region of interest. This information is not immediately available
309 /// by looking at the node associated with the exit from the function
310 /// (usually the return statement). To avoid recomputing the same information
311 /// many times (going up the path for each node and checking whether the
312 /// region was written into) we instead lazily compute the
313 /// stack frames along the path which write into the region of interest.
314 llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
315 llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
317 using RegionVector = SmallVector<const MemRegion *, 5>;
320 NoStoreFuncVisitor(const SubRegion *R)
321 : RegionOfInterest(R), MmrMgr(*R->getMemRegionManager()),
322 SM(MmrMgr.getContext().getSourceManager()),
323 PP(MmrMgr.getContext().getPrintingPolicy()) {}
325 void Profile(llvm::FoldingSetNodeID &ID) const override {
328 ID.AddPointer(RegionOfInterest);
331 void *getTag() const {
333 return static_cast<void *>(&Tag);
336 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
337 BugReporterContext &BR,
338 BugReport &R) override;
341 /// Attempts to find the region of interest in a given record decl,
342 /// by either following the base classes or fields.
343 /// Dereferences fields up to a given recursion limit.
344 /// Note that \p Vec is passed by value, leading to quadratic copying cost,
345 /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
346 /// \return A chain fields leading to the region of interest or None.
347 const Optional<RegionVector>
348 findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State,
349 const MemRegion *R, const RegionVector &Vec = {},
352 /// Check and lazily calculate whether the region of interest is
353 /// modified in the stack frame to which \p N belongs.
354 /// The calculation is cached in FramesModifyingRegion.
355 bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
356 const LocationContext *Ctx = N->getLocationContext();
357 const StackFrameContext *SCtx = Ctx->getStackFrame();
358 if (!FramesModifyingCalculated.count(SCtx))
359 findModifyingFrames(N);
360 return FramesModifyingRegion.count(SCtx);
363 /// Write to \c FramesModifyingRegion all stack frames along
364 /// the path in the current stack frame which modify \c RegionOfInterest.
365 void findModifyingFrames(const ExplodedNode *N);
367 /// Consume the information on the no-store stack frame in order to
368 /// either emit a note or suppress the report enirely.
369 /// \return Diagnostics piece for region not modified in the current function,
370 /// if it decides to emit one.
371 std::shared_ptr<PathDiagnosticPiece>
372 maybeEmitNote(BugReport &R, const CallEvent &Call, const ExplodedNode *N,
373 const RegionVector &FieldChain, const MemRegion *MatchedRegion,
374 StringRef FirstElement, bool FirstIsReferenceType,
375 unsigned IndirectionLevel);
377 /// Pretty-print region \p MatchedRegion to \p os.
378 /// \return Whether printing succeeded.
379 bool prettyPrintRegionName(StringRef FirstElement, bool FirstIsReferenceType,
380 const MemRegion *MatchedRegion,
381 const RegionVector &FieldChain,
382 int IndirectionLevel,
383 llvm::raw_svector_ostream &os);
385 /// Print first item in the chain, return new separator.
386 static StringRef prettyPrintFirstElement(StringRef FirstElement,
387 bool MoreItemsExpected,
388 int IndirectionLevel,
389 llvm::raw_svector_ostream &os);
392 } // end of anonymous namespace
394 /// \return Whether the method declaration \p Parent
395 /// syntactically has a binary operation writing into the ivar \p Ivar.
396 static bool potentiallyWritesIntoIvar(const Decl *Parent,
397 const ObjCIvarDecl *Ivar) {
398 using namespace ast_matchers;
399 const char *IvarBind = "Ivar";
400 if (!Parent || !Parent->hasBody())
402 StatementMatcher WriteIntoIvarM = binaryOperator(
403 hasOperatorName("="),
404 hasLHS(ignoringParenImpCasts(
405 objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
406 StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
407 auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
408 for (BoundNodes &Match : Matches) {
409 auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
410 if (IvarRef->isFreeIvar())
413 const Expr *Base = IvarRef->getBase();
414 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
415 Base = ICE->getSubExpr();
417 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
418 if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
419 if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf)
427 /// Get parameters associated with runtime definition in order
428 /// to get the correct parameter name.
429 static ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
430 // Use runtime definition, if available.
431 RuntimeDefinition RD = Call->getRuntimeDefinition();
432 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
433 return FD->parameters();
434 if (const auto *MD = dyn_cast_or_null<ObjCMethodDecl>(RD.getDecl()))
435 return MD->parameters();
437 return Call->parameters();
440 /// \return whether \p Ty points to a const type, or is a const reference.
441 static bool isPointerToConst(QualType Ty) {
442 return !Ty->getPointeeType().isNull() &&
443 Ty->getPointeeType().getCanonicalType().isConstQualified();
446 /// Attempts to find the region of interest in a given CXX decl,
447 /// by either following the base classes or fields.
448 /// Dereferences fields up to a given recursion limit.
449 /// Note that \p Vec is passed by value, leading to quadratic copying cost,
450 /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
451 /// \return A chain fields leading to the region of interest or None.
452 const Optional<NoStoreFuncVisitor::RegionVector>
453 NoStoreFuncVisitor::findRegionOfInterestInRecord(
454 const RecordDecl *RD, ProgramStateRef State, const MemRegion *R,
455 const NoStoreFuncVisitor::RegionVector &Vec /* = {} */,
456 int depth /* = 0 */) {
458 if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth.
461 if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
462 if (!RDX->hasDefinition())
465 // Recursively examine the base classes.
466 // Note that following base classes does not increase the recursion depth.
467 if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
468 for (const auto II : RDX->bases())
469 if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
470 if (Optional<RegionVector> Out =
471 findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
474 for (const FieldDecl *I : RD->fields()) {
475 QualType FT = I->getType();
476 const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
477 const SVal V = State->getSVal(FR);
478 const MemRegion *VR = V.getAsRegion();
480 RegionVector VecF = Vec;
483 if (RegionOfInterest == VR)
486 if (const RecordDecl *RRD = FT->getAsRecordDecl())
488 findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
491 QualType PT = FT->getPointeeType();
492 if (PT.isNull() || PT->isVoidType() || !VR)
495 if (const RecordDecl *RRD = PT->getAsRecordDecl())
496 if (Optional<RegionVector> Out =
497 findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
504 std::shared_ptr<PathDiagnosticPiece>
505 NoStoreFuncVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BR,
508 const LocationContext *Ctx = N->getLocationContext();
509 const StackFrameContext *SCtx = Ctx->getStackFrame();
510 ProgramStateRef State = N->getState();
511 auto CallExitLoc = N->getLocationAs<CallExitBegin>();
513 // No diagnostic if region was modified inside the frame.
514 if (!CallExitLoc || isRegionOfInterestModifiedInFrame(N))
517 CallEventRef<> Call =
518 BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
520 // Region of interest corresponds to an IVar, exiting a method
521 // which could have written into that IVar, but did not.
522 if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
523 if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
524 const MemRegion *SelfRegion = MC->getReceiverSVal().getAsRegion();
525 if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
526 potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
528 return maybeEmitNote(R, *Call, N, {}, SelfRegion, "self",
529 /*FirstIsReferenceType=*/false, 1);
533 if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
534 const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
535 if (RegionOfInterest->isSubRegionOf(ThisR) &&
536 !CCall->getDecl()->isImplicit())
537 return maybeEmitNote(R, *Call, N, {}, ThisR, "this",
538 /*FirstIsReferenceType=*/false, 1);
540 // Do not generate diagnostics for not modified parameters in
545 ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
546 for (unsigned I = 0; I < Call->getNumArgs() && I < parameters.size(); ++I) {
547 const ParmVarDecl *PVD = parameters[I];
548 SVal V = Call->getArgSVal(I);
549 bool ParamIsReferenceType = PVD->getType()->isReferenceType();
550 std::string ParamName = PVD->getNameAsString();
552 int IndirectionLevel = 1;
553 QualType T = PVD->getType();
554 while (const MemRegion *MR = V.getAsRegion()) {
555 if (RegionOfInterest->isSubRegionOf(MR) && !isPointerToConst(T))
556 return maybeEmitNote(R, *Call, N, {}, MR, ParamName,
557 ParamIsReferenceType, IndirectionLevel);
559 QualType PT = T->getPointeeType();
560 if (PT.isNull() || PT->isVoidType())
563 if (const RecordDecl *RD = PT->getAsRecordDecl())
564 if (Optional<RegionVector> P =
565 findRegionOfInterestInRecord(RD, State, MR))
566 return maybeEmitNote(R, *Call, N, *P, RegionOfInterest, ParamName,
567 ParamIsReferenceType, IndirectionLevel);
569 V = State->getSVal(MR, PT);
578 void NoStoreFuncVisitor::findModifyingFrames(const ExplodedNode *N) {
579 assert(N->getLocationAs<CallExitBegin>());
580 ProgramStateRef LastReturnState = N->getState();
581 SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
582 const LocationContext *Ctx = N->getLocationContext();
583 const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
586 ProgramStateRef State = N->getState();
587 auto CallExitLoc = N->getLocationAs<CallExitBegin>();
589 LastReturnState = State;
590 ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
593 FramesModifyingCalculated.insert(N->getLocationContext()->getStackFrame());
595 if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) {
596 const StackFrameContext *SCtx = N->getStackFrame();
597 while (!SCtx->inTopFrame()) {
598 auto p = FramesModifyingRegion.insert(SCtx);
600 break; // Frame and all its parents already inserted.
601 SCtx = SCtx->getParent()->getStackFrame();
605 // Stop calculation at the call to the current function.
606 if (auto CE = N->getLocationAs<CallEnter>())
607 if (CE->getCalleeContext() == OriginalSCtx)
610 N = N->getFirstPred();
614 std::shared_ptr<PathDiagnosticPiece> NoStoreFuncVisitor::maybeEmitNote(
615 BugReport &R, const CallEvent &Call, const ExplodedNode *N,
616 const RegionVector &FieldChain, const MemRegion *MatchedRegion,
617 StringRef FirstElement, bool FirstIsReferenceType,
618 unsigned IndirectionLevel) {
619 // Optimistically suppress uninitialized value bugs that result
620 // from system headers having a chance to initialize the value
621 // but failing to do so. It's too unlikely a system header's fault.
622 // It's much more likely a situation in which the function has a failure
623 // mode that the user decided not to check. If we want to hunt such
624 // omitted checks, we should provide an explicit function-specific note
625 // describing the precondition under which the function isn't supposed to
626 // initialize its out-parameter, and additionally check that such
627 // precondition can actually be fulfilled on the current path.
628 if (Call.isInSystemHeader()) {
629 // We make an exception for system header functions that have no branches.
630 // Such functions unconditionally fail to initialize the variable.
631 // If they call other functions that have more paths within them,
632 // this suppression would still apply when we visit these inner functions.
633 // One common example of a standard function that doesn't ever initialize
634 // its out parameter is operator placement new; it's up to the follow-up
635 // constructor (if any) to initialize the memory.
636 if (!N->getStackFrame()->getCFG()->isLinear())
637 R.markInvalid(getTag(), nullptr);
641 PathDiagnosticLocation L =
642 PathDiagnosticLocation::create(N->getLocation(), SM);
644 // For now this shouldn't trigger, but once it does (as we add more
645 // functions to the body farm), we'll need to decide if these reports
646 // are worth suppressing as well.
647 if (!L.hasValidLocation())
650 SmallString<256> sbuf;
651 llvm::raw_svector_ostream os(sbuf);
652 os << "Returning without writing to '";
654 // Do not generate the note if failed to pretty-print.
655 if (!prettyPrintRegionName(FirstElement, FirstIsReferenceType, MatchedRegion,
656 FieldChain, IndirectionLevel, os))
660 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
663 bool NoStoreFuncVisitor::prettyPrintRegionName(StringRef FirstElement,
664 bool FirstIsReferenceType,
665 const MemRegion *MatchedRegion,
666 const RegionVector &FieldChain,
667 int IndirectionLevel,
668 llvm::raw_svector_ostream &os) {
670 if (FirstIsReferenceType)
673 RegionVector RegionSequence;
675 // Add the regions in the reverse order, then reverse the resulting array.
676 assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
677 const MemRegion *R = RegionOfInterest;
678 while (R != MatchedRegion) {
679 RegionSequence.push_back(R);
680 R = cast<SubRegion>(R)->getSuperRegion();
682 std::reverse(RegionSequence.begin(), RegionSequence.end());
683 RegionSequence.append(FieldChain.begin(), FieldChain.end());
686 for (const MemRegion *R : RegionSequence) {
688 // Just keep going up to the base region.
689 // Element regions may appear due to casts.
690 if (isa<CXXBaseObjectRegion>(R) || isa<CXXTempObjectRegion>(R))
694 Sep = prettyPrintFirstElement(FirstElement,
695 /*MoreItemsExpected=*/true,
696 IndirectionLevel, os);
700 // Can only reasonably pretty-print DeclRegions.
701 if (!isa<DeclRegion>(R))
704 const auto *DR = cast<DeclRegion>(R);
705 Sep = DR->getValueType()->isAnyPointerType() ? "->" : ".";
706 DR->getDecl()->getDeclName().print(os, PP);
710 prettyPrintFirstElement(FirstElement,
711 /*MoreItemsExpected=*/false, IndirectionLevel, os);
715 StringRef NoStoreFuncVisitor::prettyPrintFirstElement(
716 StringRef FirstElement, bool MoreItemsExpected, int IndirectionLevel,
717 llvm::raw_svector_ostream &os) {
720 if (IndirectionLevel > 0 && MoreItemsExpected) {
725 if (IndirectionLevel > 0 && MoreItemsExpected)
728 for (int i = 0; i < IndirectionLevel; i++)
732 if (IndirectionLevel > 0 && MoreItemsExpected)
738 //===----------------------------------------------------------------------===//
739 // Implementation of MacroNullReturnSuppressionVisitor.
740 //===----------------------------------------------------------------------===//
744 /// Suppress null-pointer-dereference bugs where dereferenced null was returned
746 class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
747 const SubRegion *RegionOfInterest;
748 const SVal ValueAtDereference;
750 // Do not invalidate the reports where the value was modified
751 // after it got assigned to from the macro.
752 bool WasModified = false;
755 MacroNullReturnSuppressionVisitor(const SubRegion *R,
756 const SVal V) : RegionOfInterest(R),
757 ValueAtDereference(V) {}
759 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
760 BugReporterContext &BRC,
761 BugReport &BR) override {
765 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
769 const SourceManager &SMgr = BRC.getSourceManager();
770 if (auto Loc = matchAssignment(N)) {
771 if (isFunctionMacroExpansion(*Loc, SMgr)) {
772 std::string MacroName = getMacroName(*Loc, BRC);
773 SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
774 if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
775 BR.markInvalid(getTag(), MacroName.c_str());
779 if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
785 static void addMacroVisitorIfNecessary(
786 const ExplodedNode *N, const MemRegion *R,
787 bool EnableNullFPSuppression, BugReport &BR,
789 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
790 if (EnableNullFPSuppression &&
791 Options.ShouldSuppressNullReturnPaths && V.getAs<Loc>())
792 BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
793 R->getAs<SubRegion>(), V));
796 void* getTag() const {
798 return static_cast<void *>(&Tag);
801 void Profile(llvm::FoldingSetNodeID &ID) const override {
802 ID.AddPointer(getTag());
806 /// \return Source location of right hand side of an assignment
807 /// into \c RegionOfInterest, empty optional if none found.
808 Optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
809 const Stmt *S = PathDiagnosticLocation::getStmt(N);
810 ProgramStateRef State = N->getState();
811 auto *LCtx = N->getLocationContext();
815 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
816 if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
817 if (const Expr *RHS = VD->getInit())
818 if (RegionOfInterest->isSubRegionOf(
819 State->getLValue(VD, LCtx).getAsRegion()))
820 return RHS->getBeginLoc();
821 } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
822 const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
823 const Expr *RHS = BO->getRHS();
824 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
825 return RHS->getBeginLoc();
832 } // end of anonymous namespace
836 /// Emits an extra note at the return statement of an interesting stack frame.
838 /// The returned value is marked as an interesting value, and if it's null,
839 /// adds a visitor to track where it became null.
841 /// This visitor is intended to be used when another visitor discovers that an
842 /// interesting value comes from an inlined function call.
843 class ReturnVisitor : public BugReporterVisitor {
844 const StackFrameContext *StackFrame;
851 bool EnableNullFPSuppression;
852 bool ShouldInvalidate = true;
853 AnalyzerOptions& Options;
856 ReturnVisitor(const StackFrameContext *Frame,
858 AnalyzerOptions &Options)
859 : StackFrame(Frame), EnableNullFPSuppression(Suppressed),
862 static void *getTag() {
864 return static_cast<void *>(&Tag);
867 void Profile(llvm::FoldingSetNodeID &ID) const override {
868 ID.AddPointer(ReturnVisitor::getTag());
869 ID.AddPointer(StackFrame);
870 ID.AddBoolean(EnableNullFPSuppression);
873 /// Adds a ReturnVisitor if the given statement represents a call that was
876 /// This will search back through the ExplodedGraph, starting from the given
877 /// node, looking for when the given statement was processed. If it turns out
878 /// the statement is a call that was inlined, we add the visitor to the
879 /// bug report, so it can print a note later.
880 static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
882 bool InEnableNullFPSuppression) {
883 if (!CallEvent::isCallStmt(S))
886 // First, find when we processed the statement.
887 // If we work with a 'CXXNewExpr' that is going to be purged away before
888 // its call take place. We would catch that purge in the last condition
889 // as a 'StmtPoint' so we have to bypass it.
890 const bool BypassCXXNewExprEval = isa<CXXNewExpr>(S);
892 // This is moving forward when we enter into another context.
893 const StackFrameContext *CurrentSFC = Node->getStackFrame();
896 // If that is satisfied we found our statement as an inlined call.
897 if (Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>())
898 if (CEE->getCalleeContext()->getCallSite() == S)
901 // Try to move forward to the end of the call-chain.
902 Node = Node->getFirstPred();
906 const StackFrameContext *PredSFC = Node->getStackFrame();
908 // If that is satisfied we found our statement.
909 // FIXME: This code currently bypasses the call site for the
910 // conservatively evaluated allocator.
911 if (!BypassCXXNewExprEval)
912 if (Optional<StmtPoint> SP = Node->getLocationAs<StmtPoint>())
913 // See if we do not enter into another context.
914 if (SP->getStmt() == S && CurrentSFC == PredSFC)
917 CurrentSFC = PredSFC;
918 } while (Node->getStackFrame() == CurrentSFC);
920 // Next, step over any post-statement checks.
921 while (Node && Node->getLocation().getAs<PostStmt>())
922 Node = Node->getFirstPred();
926 // Finally, see if we inlined the call.
927 Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
931 const StackFrameContext *CalleeContext = CEE->getCalleeContext();
932 if (CalleeContext->getCallSite() != S)
935 // Check the return value.
936 ProgramStateRef State = Node->getState();
937 SVal RetVal = Node->getSVal(S);
939 // Handle cases where a reference is returned and then immediately used.
940 if (cast<Expr>(S)->isGLValue())
941 if (Optional<Loc> LValue = RetVal.getAs<Loc>())
942 RetVal = State->getSVal(*LValue);
944 // See if the return value is NULL. If so, suppress the report.
945 AnalyzerOptions &Options = State->getAnalysisManager().options;
947 bool EnableNullFPSuppression = false;
948 if (InEnableNullFPSuppression &&
949 Options.ShouldSuppressNullReturnPaths)
950 if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
951 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
953 BR.markInteresting(CalleeContext);
954 BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
955 EnableNullFPSuppression,
959 std::shared_ptr<PathDiagnosticPiece>
960 visitNodeInitial(const ExplodedNode *N,
961 BugReporterContext &BRC, BugReport &BR) {
962 // Only print a message at the interesting return statement.
963 if (N->getLocationContext() != StackFrame)
966 Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
970 const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
974 // Okay, we're at the right return statement, but do we have the return
976 ProgramStateRef State = N->getState();
977 SVal V = State->getSVal(Ret, StackFrame);
978 if (V.isUnknownOrUndef())
981 // Don't print any more notes after this one.
984 const Expr *RetE = Ret->getRetValue();
985 assert(RetE && "Tracking a return value for a void function");
987 // Handle cases where a reference is returned and then immediately used.
988 Optional<Loc> LValue;
989 if (RetE->isGLValue()) {
990 if ((LValue = V.getAs<Loc>())) {
991 SVal RValue = State->getRawSVal(*LValue, RetE->getType());
992 if (RValue.getAs<DefinedSVal>())
997 // Ignore aggregate rvalues.
998 if (V.getAs<nonloc::LazyCompoundVal>() ||
999 V.getAs<nonloc::CompoundVal>())
1002 RetE = RetE->IgnoreParenCasts();
1004 // If we're returning 0, we should track where that 0 came from.
1005 bugreporter::trackExpressionValue(N, RetE, BR, EnableNullFPSuppression);
1007 // Build an appropriate message based on the return value.
1008 SmallString<64> Msg;
1009 llvm::raw_svector_ostream Out(Msg);
1011 if (State->isNull(V).isConstrainedTrue()) {
1012 if (V.getAs<Loc>()) {
1014 // If we have counter-suppression enabled, make sure we keep visiting
1015 // future nodes. We want to emit a path note as well, in case
1016 // the report is resurrected as valid later on.
1017 if (EnableNullFPSuppression &&
1018 Options.ShouldAvoidSuppressingNullArgumentPaths)
1019 Mode = MaybeUnsuppress;
1021 if (RetE->getType()->isObjCObjectPointerType()) {
1022 Out << "Returning nil";
1024 Out << "Returning null pointer";
1027 Out << "Returning zero";
1031 if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1032 Out << "Returning the value " << CI->getValue();
1033 } else if (V.getAs<Loc>()) {
1034 Out << "Returning pointer";
1036 Out << "Returning value";
1041 if (const MemRegion *MR = LValue->getAsRegion()) {
1042 if (MR->canPrintPretty()) {
1043 Out << " (reference to ";
1044 MR->printPretty(Out);
1049 // FIXME: We should have a more generalized location printing mechanism.
1050 if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
1051 if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
1052 Out << " (loaded from '" << *DD << "')";
1055 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
1056 if (!L.isValid() || !L.asLocation().isValid())
1059 return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
1062 std::shared_ptr<PathDiagnosticPiece>
1063 visitNodeMaybeUnsuppress(const ExplodedNode *N,
1064 BugReporterContext &BRC, BugReport &BR) {
1066 assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
1069 // Are we at the entry node for this call?
1070 Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
1074 if (CE->getCalleeContext() != StackFrame)
1079 // Don't automatically suppress a report if one of the arguments is
1080 // known to be a null pointer. Instead, start tracking /that/ null
1081 // value back to its origin.
1082 ProgramStateManager &StateMgr = BRC.getStateManager();
1083 CallEventManager &CallMgr = StateMgr.getCallEventManager();
1085 ProgramStateRef State = N->getState();
1086 CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
1087 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
1088 Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
1092 const Expr *ArgE = Call->getArgExpr(I);
1096 // Is it possible for this argument to be non-null?
1097 if (!State->isNull(*ArgV).isConstrainedTrue())
1100 if (bugreporter::trackExpressionValue(N, ArgE, BR, EnableNullFPSuppression))
1101 ShouldInvalidate = false;
1103 // If we /can't/ track the null pointer, we should err on the side of
1104 // false negatives, and continue towards marking this report invalid.
1105 // (We will still look at the other arguments, though.)
1111 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
1112 BugReporterContext &BRC,
1113 BugReport &BR) override {
1116 return visitNodeInitial(N, BRC, BR);
1117 case MaybeUnsuppress:
1118 return visitNodeMaybeUnsuppress(N, BRC, BR);
1123 llvm_unreachable("Invalid visit mode!");
1126 void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
1127 BugReport &BR) override {
1128 if (EnableNullFPSuppression && ShouldInvalidate)
1129 BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
1133 } // end of anonymous namespace
1135 //===----------------------------------------------------------------------===//
1136 // Implementation of FindLastStoreBRVisitor.
1137 //===----------------------------------------------------------------------===//
1139 void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1141 ID.AddPointer(&tag);
1144 ID.AddBoolean(EnableNullFPSuppression);
1147 /// Returns true if \p N represents the DeclStmt declaring and initializing
1149 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
1150 Optional<PostStmt> P = N->getLocationAs<PostStmt>();
1154 const DeclStmt *DS = P->getStmtAs<DeclStmt>();
1158 if (DS->getSingleDecl() != VR->getDecl())
1161 const MemSpaceRegion *VarSpace = VR->getMemorySpace();
1162 const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
1164 // If we ever directly evaluate global DeclStmts, this assertion will be
1165 // invalid, but this still seems preferable to silently accepting an
1166 // initialization that may be for a path-sensitive variable.
1167 assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
1171 assert(VR->getDecl()->hasLocalStorage());
1172 const LocationContext *LCtx = N->getLocationContext();
1173 return FrameSpace->getStackFrame() == LCtx->getStackFrame();
1176 /// Show diagnostics for initializing or declaring a region \p R with a bad value.
1177 static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
1178 const MemRegion *R, SVal V, const DeclStmt *DS) {
1179 if (R->canPrintPretty()) {
1184 if (V.getAs<loc::ConcreteInt>()) {
1186 if (R->isBoundable()) {
1187 if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1188 if (TR->getValueType()->isObjCObjectPointerType()) {
1189 os << action << "nil";
1195 os << action << "a null pointer value";
1197 } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
1198 os << action << CVal->getValue();
1201 if (isa<VarRegion>(R)) {
1202 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
1203 if (VD->getInit()) {
1204 os << (R->canPrintPretty() ? "initialized" : "Initializing")
1205 << " to a garbage value";
1207 os << (R->canPrintPretty() ? "declared" : "Declaring")
1208 << " without an initial value";
1212 os << (R->canPrintPretty() ? "initialized" : "Initialized")
1218 /// Display diagnostics for passing bad region as a parameter.
1219 static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
1220 const VarRegion *VR,
1222 const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1226 if (V.getAs<loc::ConcreteInt>()) {
1227 if (Param->getType()->isObjCObjectPointerType())
1228 os << "nil object reference";
1230 os << "null pointer value";
1231 } else if (V.isUndef()) {
1232 os << "uninitialized value";
1233 } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1234 os << "the value " << CI->getValue();
1239 // Printed parameter indexes are 1-based, not 0-based.
1240 unsigned Idx = Param->getFunctionScopeIndex() + 1;
1241 os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
1242 if (VR->canPrintPretty()) {
1244 VR->printPretty(os);
1248 /// Show default diagnostics for storing bad region.
1249 static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
1252 if (V.getAs<loc::ConcreteInt>()) {
1254 if (R->isBoundable()) {
1255 if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1256 if (TR->getValueType()->isObjCObjectPointerType()) {
1257 os << "nil object reference stored";
1263 if (R->canPrintPretty())
1264 os << "Null pointer value stored";
1266 os << "Storing null pointer value";
1269 } else if (V.isUndef()) {
1270 if (R->canPrintPretty())
1271 os << "Uninitialized value stored";
1273 os << "Storing uninitialized value";
1275 } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
1276 if (R->canPrintPretty())
1277 os << "The value " << CV->getValue() << " is assigned";
1279 os << "Assigning " << CV->getValue();
1282 if (R->canPrintPretty())
1283 os << "Value assigned";
1285 os << "Assigning value";
1288 if (R->canPrintPretty()) {
1294 std::shared_ptr<PathDiagnosticPiece>
1295 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
1296 BugReporterContext &BRC, BugReport &BR) {
1300 const ExplodedNode *StoreSite = nullptr;
1301 const ExplodedNode *Pred = Succ->getFirstPred();
1302 const Expr *InitE = nullptr;
1303 bool IsParam = false;
1305 // First see if we reached the declaration of the region.
1306 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1307 if (isInitializationOfVar(Pred, VR)) {
1309 InitE = VR->getDecl()->getInit();
1313 // If this is a post initializer expression, initializing the region, we
1314 // should track the initializer expression.
1315 if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
1316 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1317 if (FieldReg && FieldReg == R) {
1319 InitE = PIP->getInitializer()->getInit();
1323 // Otherwise, see if this is the store site:
1324 // (1) Succ has this binding and Pred does not, i.e. this is
1325 // where the binding first occurred.
1326 // (2) Succ has this binding and is a PostStore node for this region, i.e.
1327 // the same binding was re-assigned here.
1329 if (Succ->getState()->getSVal(R) != V)
1332 if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
1333 Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1334 if (!PS || PS->getLocationValue() != R)
1340 // If this is an assignment expression, we can track the value
1342 if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
1343 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
1344 if (BO->isAssignmentOp())
1345 InitE = BO->getRHS();
1347 // If this is a call entry, the variable should be a parameter.
1348 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1349 // 'this' should never be NULL, but this visitor isn't just for NULL and
1351 if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1352 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1354 const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1356 ProgramStateManager &StateMgr = BRC.getStateManager();
1357 CallEventManager &CallMgr = StateMgr.getCallEventManager();
1359 CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
1361 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1366 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1367 // is wrapped inside of it.
1368 if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1369 InitE = TmpR->getExpr();
1376 // If we have an expression that provided the value, try to track where it
1380 V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1382 InitE = InitE->IgnoreParenCasts();
1383 bugreporter::trackExpressionValue(StoreSite, InitE, BR,
1384 EnableNullFPSuppression);
1386 ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
1387 BR, EnableNullFPSuppression);
1390 // Okay, we've found the binding. Emit an appropriate message.
1391 SmallString<256> sbuf;
1392 llvm::raw_svector_ostream os(sbuf);
1394 if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1395 const Stmt *S = PS->getStmt();
1396 const char *action = nullptr;
1397 const auto *DS = dyn_cast<DeclStmt>(S);
1398 const auto *VR = dyn_cast<VarRegion>(R);
1401 action = R->canPrintPretty() ? "initialized to " :
1403 } else if (isa<BlockExpr>(S)) {
1404 action = R->canPrintPretty() ? "captured by block as " :
1405 "Captured by block as ";
1407 // See if we can get the BlockVarRegion.
1408 ProgramStateRef State = StoreSite->getState();
1409 SVal V = StoreSite->getSVal(S);
1410 if (const auto *BDR =
1411 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1412 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1413 if (auto KV = State->getSVal(OriginalR).getAs<KnownSVal>())
1414 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1415 *KV, OriginalR, EnableNullFPSuppression));
1421 showBRDiagnostics(action, os, R, V, DS);
1423 } else if (StoreSite->getLocation().getAs<CallEnter>()) {
1424 if (const auto *VR = dyn_cast<VarRegion>(R))
1425 showBRParamDiagnostics(os, VR, V);
1428 if (os.str().empty())
1429 showBRDefaultDiagnostics(os, R, V);
1431 // Construct a new PathDiagnosticPiece.
1432 ProgramPoint P = StoreSite->getLocation();
1433 PathDiagnosticLocation L;
1434 if (P.getAs<CallEnter>() && InitE)
1435 L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
1436 P.getLocationContext());
1438 if (!L.isValid() || !L.asLocation().isValid())
1439 L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
1441 if (!L.isValid() || !L.asLocation().isValid())
1444 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1447 //===----------------------------------------------------------------------===//
1448 // Implementation of TrackConstraintBRVisitor.
1449 //===----------------------------------------------------------------------===//
1451 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1453 ID.AddPointer(&tag);
1454 ID.AddBoolean(Assumption);
1458 /// Return the tag associated with this visitor. This tag will be used
1459 /// to make all PathDiagnosticPieces created by this visitor.
1460 const char *TrackConstraintBRVisitor::getTag() {
1461 return "TrackConstraintBRVisitor";
1464 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1466 return N->getState()->isNull(Constraint).isUnderconstrained();
1467 return (bool)N->getState()->assume(Constraint, !Assumption);
1470 std::shared_ptr<PathDiagnosticPiece>
1471 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
1472 BugReporterContext &BRC, BugReport &) {
1473 const ExplodedNode *PrevN = N->getFirstPred();
1477 // Start tracking after we see the first state in which the value is
1479 if (!IsTrackingTurnedOn)
1480 if (!isUnderconstrained(N))
1481 IsTrackingTurnedOn = true;
1482 if (!IsTrackingTurnedOn)
1485 // Check if in the previous state it was feasible for this constraint
1486 // to *not* be true.
1487 if (isUnderconstrained(PrevN)) {
1490 // As a sanity check, make sure that the negation of the constraint
1491 // was infeasible in the current state. If it is feasible, we somehow
1492 // missed the transition point.
1493 assert(!isUnderconstrained(N));
1495 // We found the transition point for the constraint. We now need to
1496 // pretty-print the constraint. (work-in-progress)
1497 SmallString<64> sbuf;
1498 llvm::raw_svector_ostream os(sbuf);
1500 if (Constraint.getAs<Loc>()) {
1501 os << "Assuming pointer value is ";
1502 os << (Assumption ? "non-null" : "null");
1505 if (os.str().empty())
1508 // Construct a new PathDiagnosticPiece.
1509 ProgramPoint P = N->getLocation();
1510 PathDiagnosticLocation L =
1511 PathDiagnosticLocation::create(P, BRC.getSourceManager());
1515 auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1516 X->setTag(getTag());
1517 return std::move(X);
1523 //===----------------------------------------------------------------------===//
1524 // Implementation of SuppressInlineDefensiveChecksVisitor.
1525 //===----------------------------------------------------------------------===//
1527 SuppressInlineDefensiveChecksVisitor::
1528 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
1530 // Check if the visitor is disabled.
1531 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
1532 if (!Options.ShouldSuppressInlinedDefensiveChecks)
1535 assert(N->getState()->isNull(V).isConstrainedTrue() &&
1536 "The visitor only tracks the cases where V is constrained to 0");
1539 void SuppressInlineDefensiveChecksVisitor::Profile(
1540 llvm::FoldingSetNodeID &ID) const {
1546 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
1547 return "IDCVisitor";
1550 std::shared_ptr<PathDiagnosticPiece>
1551 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
1552 BugReporterContext &BRC,
1554 const ExplodedNode *Pred = Succ->getFirstPred();
1558 // Start tracking after we see the first state in which the value is null.
1559 if (!IsTrackingTurnedOn)
1560 if (Succ->getState()->isNull(V).isConstrainedTrue())
1561 IsTrackingTurnedOn = true;
1562 if (!IsTrackingTurnedOn)
1565 // Check if in the previous state it was feasible for this value
1566 // to *not* be null.
1567 if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
1570 assert(Succ->getState()->isNull(V).isConstrainedTrue());
1572 // Check if this is inlined defensive checks.
1573 const LocationContext *CurLC =Succ->getLocationContext();
1574 const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
1575 if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
1576 BR.markInvalid("Suppress IDC", CurLC);
1580 // Treat defensive checks in function-like macros as if they were an inlined
1581 // defensive check. If the bug location is not in a macro and the
1582 // terminator for the current location is in a macro then suppress the
1584 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1589 ProgramPoint CurPoint = Succ->getLocation();
1590 const Stmt *CurTerminatorStmt = nullptr;
1591 if (auto BE = CurPoint.getAs<BlockEdge>()) {
1592 CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1593 } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1594 const Stmt *CurStmt = SP->getStmt();
1595 if (!CurStmt->getBeginLoc().isMacroID())
1598 CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1599 CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminatorStmt();
1604 if (!CurTerminatorStmt)
1607 SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
1608 if (TerminatorLoc.isMacroID()) {
1609 SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
1611 // Suppress reports unless we are in that same macro.
1612 if (!BugLoc.isMacroID() ||
1613 getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1614 BR.markInvalid("Suppress Macro IDC", CurLC);
1622 //===----------------------------------------------------------------------===//
1623 // TrackControlDependencyCondBRVisitor.
1624 //===----------------------------------------------------------------------===//
1627 /// Tracks the expressions that are a control dependency of the node that was
1628 /// supplied to the constructor.
1635 /// An error is emitted at line 3. This visitor realizes that the branch
1636 /// on line 2 is a control dependency of line 3, and tracks it's condition via
1637 /// trackExpressionValue().
1638 class TrackControlDependencyCondBRVisitor final : public BugReporterVisitor {
1639 const ExplodedNode *Origin;
1640 ControlDependencyCalculator ControlDeps;
1641 llvm::SmallSet<const CFGBlock *, 32> VisitedBlocks;
1644 TrackControlDependencyCondBRVisitor(const ExplodedNode *O)
1645 : Origin(O), ControlDeps(&O->getCFG()) {}
1647 void Profile(llvm::FoldingSetNodeID &ID) const override {
1652 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
1653 BugReporterContext &BRC,
1654 BugReport &BR) override;
1656 } // end of anonymous namespace
1658 static CFGBlock *GetRelevantBlock(const ExplodedNode *Node) {
1659 if (auto SP = Node->getLocationAs<StmtPoint>()) {
1660 const Stmt *S = SP->getStmt();
1663 return const_cast<CFGBlock *>(Node->getLocationContext()
1664 ->getAnalysisDeclContext()->getCFGStmtMap()->getBlock(S));
1670 static std::shared_ptr<PathDiagnosticEventPiece>
1671 constructDebugPieceForTrackedCondition(const Expr *Cond,
1672 const ExplodedNode *N,
1673 BugReporterContext &BRC) {
1675 if (BRC.getAnalyzerOptions().AnalysisDiagOpt == PD_NONE ||
1676 !BRC.getAnalyzerOptions().ShouldTrackConditionsDebug)
1679 std::string ConditionText = Lexer::getSourceText(
1680 CharSourceRange::getTokenRange(Cond->getSourceRange()),
1681 BRC.getSourceManager(),
1682 BRC.getASTContext().getLangOpts());
1684 return std::make_shared<PathDiagnosticEventPiece>(
1685 PathDiagnosticLocation::createBegin(
1686 Cond, BRC.getSourceManager(), N->getLocationContext()),
1687 (Twine() + "Tracking condition '" + ConditionText + "'").str());
1690 std::shared_ptr<PathDiagnosticPiece>
1691 TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
1692 BugReporterContext &BRC,
1694 // We can only reason about control dependencies within the same stack frame.
1695 if (Origin->getStackFrame() != N->getStackFrame())
1698 CFGBlock *NB = GetRelevantBlock(N);
1700 // Skip if we already inspected this block.
1701 if (!VisitedBlocks.insert(NB).second)
1704 CFGBlock *OriginB = GetRelevantBlock(Origin);
1706 // TODO: Cache CFGBlocks for each ExplodedNode.
1707 if (!OriginB || !NB)
1710 if (ControlDeps.isControlDependent(OriginB, NB)) {
1711 if (const Expr *Condition = NB->getLastCondition()) {
1712 // Keeping track of the already tracked conditions on a visitor level
1713 // isn't sufficient, because a new visitor is created for each tracked
1714 // expression, hence the BugReport level set.
1715 if (BR.addTrackedCondition(N)) {
1716 bugreporter::trackExpressionValue(
1717 N, Condition, BR, /*EnableNullFPSuppression=*/false);
1718 return constructDebugPieceForTrackedCondition(Condition, N, BRC);
1726 //===----------------------------------------------------------------------===//
1727 // Implementation of trackExpressionValue.
1728 //===----------------------------------------------------------------------===//
1730 static const MemRegion *getLocationRegionIfReference(const Expr *E,
1731 const ExplodedNode *N) {
1732 if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
1733 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1734 if (!VD->getType()->isReferenceType())
1736 ProgramStateManager &StateMgr = N->getState()->getStateManager();
1737 MemRegionManager &MRMgr = StateMgr.getRegionManager();
1738 return MRMgr.getVarRegion(VD, N->getLocationContext());
1742 // FIXME: This does not handle other kinds of null references,
1743 // for example, references from FieldRegions:
1744 // struct Wrapper { int &ref; };
1745 // Wrapper w = { *(int *)0 };
1751 /// \return A subexpression of {@code Ex} which represents the
1752 /// expression-of-interest.
1753 static const Expr *peelOffOuterExpr(const Expr *Ex,
1754 const ExplodedNode *N) {
1755 Ex = Ex->IgnoreParenCasts();
1756 if (const auto *FE = dyn_cast<FullExpr>(Ex))
1757 return peelOffOuterExpr(FE->getSubExpr(), N);
1758 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1759 return peelOffOuterExpr(OVE->getSourceExpr(), N);
1760 if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1761 const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1762 if (PropRef && PropRef->isMessagingGetter()) {
1763 const Expr *GetterMessageSend =
1764 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1765 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1766 return peelOffOuterExpr(GetterMessageSend, N);
1770 // Peel off the ternary operator.
1771 if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
1772 // Find a node where the branching occurred and find out which branch
1773 // we took (true/false) by looking at the ExplodedGraph.
1774 const ExplodedNode *NI = N;
1776 ProgramPoint ProgPoint = NI->getLocation();
1777 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1778 const CFGBlock *srcBlk = BE->getSrc();
1779 if (const Stmt *term = srcBlk->getTerminatorStmt()) {
1781 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1783 return peelOffOuterExpr(CO->getTrueExpr(), N);
1785 return peelOffOuterExpr(CO->getFalseExpr(), N);
1789 NI = NI->getFirstPred();
1793 if (auto *BO = dyn_cast<BinaryOperator>(Ex))
1794 if (const Expr *SubEx = peelOffPointerArithmetic(BO))
1795 return peelOffOuterExpr(SubEx, N);
1797 if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
1798 if (UO->getOpcode() == UO_LNot)
1799 return peelOffOuterExpr(UO->getSubExpr(), N);
1801 // FIXME: There's a hack in our Store implementation that always computes
1802 // field offsets around null pointers as if they are always equal to 0.
1803 // The idea here is to report accesses to fields as null dereferences
1804 // even though the pointer value that's being dereferenced is actually
1805 // the offset of the field rather than exactly 0.
1806 // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1807 // This code interacts heavily with this hack; otherwise the value
1808 // would not be null at all for most fields, so we'd be unable to track it.
1809 if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue())
1810 if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
1811 return peelOffOuterExpr(DerefEx, N);
1817 /// Find the ExplodedNode where the lvalue (the value of 'Ex')
1819 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1820 const Expr *Inner) {
1822 if (PathDiagnosticLocation::getStmt(N) == Inner)
1824 N = N->getFirstPred();
1829 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
1830 const Expr *E, BugReport &report,
1831 bool EnableNullFPSuppression) {
1832 if (!E || !InputNode)
1835 const Expr *Inner = peelOffOuterExpr(E, InputNode);
1836 const ExplodedNode *LVNode = findNodeForExpression(InputNode, Inner);
1840 ProgramStateRef LVState = LVNode->getState();
1842 // We only track expressions if we believe that they are important. Chances
1843 // are good that control dependencies to the tracking point are also improtant
1844 // because of this, let's explain why we believe control reached this point.
1845 // TODO: Shouldn't we track control dependencies of every bug location, rather
1846 // than only tracked expressions?
1847 if (LVState->getAnalysisManager().getAnalyzerOptions().ShouldTrackConditions)
1848 report.addVisitor(llvm::make_unique<TrackControlDependencyCondBRVisitor>(
1851 // The message send could be nil due to the receiver being nil.
1852 // At this point in the path, the receiver should be live since we are at the
1853 // message send expr. If it is nil, start tracking it.
1854 if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
1855 trackExpressionValue(LVNode, Receiver, report, EnableNullFPSuppression);
1857 // Track the index if this is an array subscript.
1858 if (const auto *Arr = dyn_cast<ArraySubscriptExpr>(Inner))
1859 trackExpressionValue(
1860 LVNode, Arr->getIdx(), report, /*EnableNullFPSuppression*/ false);
1862 // See if the expression we're interested refers to a variable.
1863 // If so, we can track both its contents and constraints on its value.
1864 if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
1865 SVal LVal = LVNode->getSVal(Inner);
1867 const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
1868 bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1870 // If this is a C++ reference to a null pointer, we are tracking the
1871 // pointer. In addition, we should find the store at which the reference
1873 if (RR && !LVIsNull)
1874 if (auto KV = LVal.getAs<KnownSVal>())
1875 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1876 *KV, RR, EnableNullFPSuppression));
1878 // In case of C++ references, we want to differentiate between a null
1879 // reference and reference to null pointer.
1880 // If the LVal is null, check if we are dealing with null reference.
1881 // For those, we want to track the location of the reference.
1882 const MemRegion *R = (RR && LVIsNull) ? RR :
1883 LVNode->getSVal(Inner).getAsRegion();
1887 // Mark both the variable region and its contents as interesting.
1888 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1890 llvm::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R)));
1892 MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1893 LVNode, R, EnableNullFPSuppression, report, V);
1895 report.markInteresting(V);
1896 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1898 // If the contents are symbolic, find out when they became null.
1899 if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1900 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1901 V.castAs<DefinedSVal>(), false));
1903 // Add visitor, which will suppress inline defensive checks.
1904 if (auto DV = V.getAs<DefinedSVal>())
1905 if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1906 EnableNullFPSuppression)
1908 llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1911 if (auto KV = V.getAs<KnownSVal>())
1912 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1913 *KV, R, EnableNullFPSuppression));
1918 // If the expression is not an "lvalue expression", we can still
1919 // track the constraints on its contents.
1920 SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext());
1922 ReturnVisitor::addVisitorIfNecessary(
1923 LVNode, Inner, report, EnableNullFPSuppression);
1925 // Is it a symbolic value?
1926 if (auto L = V.getAs<loc::MemRegionVal>()) {
1927 report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1929 // FIXME: this is a hack for fixing a later crash when attempting to
1930 // dereference a void* pointer.
1931 // We should not try to dereference pointers at all when we don't care
1932 // what is written inside the pointer.
1933 bool CanDereference = true;
1934 if (const auto *SR = dyn_cast<SymbolicRegion>(L->getRegion()))
1935 if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
1936 CanDereference = false;
1938 // At this point we are dealing with the region's LValue.
1939 // However, if the rvalue is a symbolic region, we should track it as well.
1940 // Try to use the correct type when looking up the value.
1942 if (ExplodedGraph::isInterestingLValueExpr(Inner)) {
1943 RVal = LVState->getRawSVal(L.getValue(), Inner->getType());
1944 } else if (CanDereference) {
1945 RVal = LVState->getSVal(L->getRegion());
1949 if (auto KV = RVal.getAs<KnownSVal>())
1950 report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1951 *KV, L->getRegion(), EnableNullFPSuppression));
1953 const MemRegion *RegionRVal = RVal.getAsRegion();
1954 if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1955 report.markInteresting(RegionRVal);
1956 report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1957 loc::MemRegionVal(RegionRVal), /*assumption=*/false));
1963 //===----------------------------------------------------------------------===//
1964 // Implementation of NulReceiverBRVisitor.
1965 //===----------------------------------------------------------------------===//
1967 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1968 const ExplodedNode *N) {
1969 const auto *ME = dyn_cast<ObjCMessageExpr>(S);
1972 if (const Expr *Receiver = ME->getInstanceReceiver()) {
1973 ProgramStateRef state = N->getState();
1974 SVal V = N->getSVal(Receiver);
1975 if (state->isNull(V).isConstrainedTrue())
1981 std::shared_ptr<PathDiagnosticPiece>
1982 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1983 BugReporterContext &BRC, BugReport &BR) {
1984 Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1988 const Stmt *S = P->getStmt();
1989 const Expr *Receiver = getNilReceiver(S, N);
1993 llvm::SmallString<256> Buf;
1994 llvm::raw_svector_ostream OS(Buf);
1996 if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1998 ME->getSelector().print(OS);
1999 OS << "' not called";
2002 OS << "No method is called";
2004 OS << " because the receiver is nil";
2006 // The receiver was nil, and hence the method was skipped.
2007 // Register a BugReporterVisitor to issue a message telling us how
2008 // the receiver was null.
2009 bugreporter::trackExpressionValue(N, Receiver, BR,
2010 /*EnableNullFPSuppression*/ false);
2011 // Issue a message saying that the method was skipped.
2012 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
2013 N->getLocationContext());
2014 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
2017 //===----------------------------------------------------------------------===//
2018 // Implementation of FindLastStoreBRVisitor.
2019 //===----------------------------------------------------------------------===//
2021 // Registers every VarDecl inside a Stmt with a last store visitor.
2022 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
2024 bool EnableNullFPSuppression) {
2025 const ExplodedNode *N = BR.getErrorNode();
2026 std::deque<const Stmt *> WorkList;
2027 WorkList.push_back(S);
2029 while (!WorkList.empty()) {
2030 const Stmt *Head = WorkList.front();
2031 WorkList.pop_front();
2033 ProgramStateManager &StateMgr = N->getState()->getStateManager();
2035 if (const auto *DR = dyn_cast<DeclRefExpr>(Head)) {
2036 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2037 const VarRegion *R =
2038 StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
2040 // What did we load?
2041 SVal V = N->getSVal(S);
2043 if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
2044 // Register a new visitor with the BugReport.
2045 BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
2046 V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
2051 for (const Stmt *SubStmt : Head->children())
2052 WorkList.push_back(SubStmt);
2056 //===----------------------------------------------------------------------===//
2057 // Visitor that tries to report interesting diagnostics from conditions.
2058 //===----------------------------------------------------------------------===//
2060 /// Return the tag associated with this visitor. This tag will be used
2061 /// to make all PathDiagnosticPieces created by this visitor.
2062 const char *ConditionBRVisitor::getTag() {
2063 return "ConditionBRVisitor";
2066 std::shared_ptr<PathDiagnosticPiece>
2067 ConditionBRVisitor::VisitNode(const ExplodedNode *N,
2068 BugReporterContext &BRC, BugReport &BR) {
2069 auto piece = VisitNodeImpl(N, BRC, BR);
2071 piece->setTag(getTag());
2072 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
2073 ev->setPrunable(true, /* override */ false);
2078 std::shared_ptr<PathDiagnosticPiece>
2079 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
2080 BugReporterContext &BRC, BugReport &BR) {
2081 ProgramPoint ProgPoint = N->getLocation();
2082 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags =
2083 ExprEngine::geteagerlyAssumeBinOpBifurcationTags();
2085 // If an assumption was made on a branch, it should be caught
2086 // here by looking at the state transition.
2087 if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
2088 const CFGBlock *SrcBlock = BE->getSrc();
2089 if (const Stmt *Term = SrcBlock->getTerminatorStmt()) {
2090 // If the tag of the previous node is 'Eagerly Assume...' the current
2091 // 'BlockEdge' has the same constraint information. We do not want to
2092 // report the value as it is just an assumption on the predecessor node
2093 // which will be caught in the next VisitNode() iteration as a 'PostStmt'.
2094 const ProgramPointTag *PreviousNodeTag =
2095 N->getFirstPred()->getLocation().getTag();
2096 if (PreviousNodeTag == Tags.first || PreviousNodeTag == Tags.second)
2099 return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC);
2104 if (Optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) {
2105 const ProgramPointTag *CurrentNodeTag = PS->getTag();
2106 if (CurrentNodeTag != Tags.first && CurrentNodeTag != Tags.second)
2109 bool TookTrue = CurrentNodeTag == Tags.first;
2110 return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue);
2116 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
2117 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
2118 const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
2119 const Expr *Cond = nullptr;
2121 // In the code below, Term is a CFG terminator and Cond is a branch condition
2122 // expression upon which the decision is made on this terminator.
2124 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
2125 // and "x == 0" is the respective condition.
2127 // Another example: in "if (x && y)", we've got two terminators and two
2128 // conditions due to short-circuit nature of operator "&&":
2129 // 1. The "if (x && y)" statement is a terminator,
2130 // and "y" is the respective condition.
2131 // 2. Also "x && ..." is another terminator,
2132 // and "x" is its condition.
2134 switch (Term->getStmtClass()) {
2135 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
2136 // more tricky because there are more than two branches to account for.
2139 case Stmt::IfStmtClass:
2140 Cond = cast<IfStmt>(Term)->getCond();
2142 case Stmt::ConditionalOperatorClass:
2143 Cond = cast<ConditionalOperator>(Term)->getCond();
2145 case Stmt::BinaryOperatorClass:
2146 // When we encounter a logical operator (&& or ||) as a CFG terminator,
2147 // then the condition is actually its LHS; otherwise, we'd encounter
2148 // the parent, such as if-statement, as a terminator.
2149 const auto *BO = cast<BinaryOperator>(Term);
2150 assert(BO->isLogicalOp() &&
2151 "CFG terminator is not a short-circuit operator!");
2152 Cond = BO->getLHS();
2156 Cond = Cond->IgnoreParens();
2158 // However, when we encounter a logical operator as a branch condition,
2159 // then the condition is actually its RHS, because LHS would be
2160 // the condition for the logical operator terminator.
2161 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
2162 if (!InnerBO->isLogicalOp())
2164 Cond = InnerBO->getRHS()->IgnoreParens();
2168 assert(srcBlk->succ_size() == 2);
2169 const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk;
2170 return VisitTrueTest(Cond, BRC, R, N, TookTrue);
2173 std::shared_ptr<PathDiagnosticPiece>
2174 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, BugReporterContext &BRC,
2175 BugReport &R, const ExplodedNode *N,
2177 ProgramStateRef CurrentState = N->getState();
2178 ProgramStateRef PrevState = N->getFirstPred()->getState();
2179 const LocationContext *LCtx = N->getLocationContext();
2181 // If the constraint information is changed between the current and the
2182 // previous program state we assuming the newly seen constraint information.
2183 // If we cannot evaluate the condition (and the constraints are the same)
2184 // the analyzer has no information about the value and just assuming it.
2186 !BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) ||
2187 CurrentState->getSVal(Cond, LCtx).isUnknownOrUndef();
2189 // These will be modified in code below, but we need to preserve the original
2190 // values in case we want to throw the generic message.
2191 const Expr *CondTmp = Cond;
2192 bool TookTrueTmp = TookTrue;
2195 CondTmp = CondTmp->IgnoreParenCasts();
2196 switch (CondTmp->getStmtClass()) {
2199 case Stmt::BinaryOperatorClass:
2200 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
2201 BRC, R, N, TookTrueTmp, IsAssuming))
2204 case Stmt::DeclRefExprClass:
2205 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
2206 BRC, R, N, TookTrueTmp, IsAssuming))
2209 case Stmt::MemberExprClass:
2210 if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp),
2211 BRC, R, N, TookTrueTmp, IsAssuming))
2214 case Stmt::UnaryOperatorClass: {
2215 const auto *UO = cast<UnaryOperator>(CondTmp);
2216 if (UO->getOpcode() == UO_LNot) {
2217 TookTrueTmp = !TookTrueTmp;
2218 CondTmp = UO->getSubExpr();
2227 // Condition too complex to explain? Just say something so that the user
2228 // knew we've made some path decision at this point.
2229 // If it is too complex and we know the evaluation of the condition do not
2230 // repeat the note from 'BugReporter.cpp'
2234 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2235 if (!Loc.isValid() || !Loc.asLocation().isValid())
2238 return std::make_shared<PathDiagnosticEventPiece>(
2239 Loc, TookTrue ? GenericTrueMessage : GenericFalseMessage);
2242 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
2243 const Expr *ParentEx,
2245 BugReporterContext &BRC,
2247 const ExplodedNode *N,
2248 Optional<bool> &prunable,
2249 bool IsSameFieldName) {
2250 const Expr *OriginalExpr = Ex;
2251 Ex = Ex->IgnoreParenCasts();
2253 if (isa<GNUNullExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
2254 isa<CXXBoolLiteralExpr>(Ex) || isa<IntegerLiteral>(Ex) ||
2255 isa<FloatingLiteral>(Ex)) {
2256 // Use heuristics to determine if the expression is a macro
2257 // expanding to a literal and if so, use the macro's name.
2258 SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
2259 SourceLocation EndLoc = OriginalExpr->getEndLoc();
2260 if (BeginLoc.isMacroID() && EndLoc.isMacroID()) {
2261 SourceManager &SM = BRC.getSourceManager();
2262 const LangOptions &LO = BRC.getASTContext().getLangOpts();
2263 if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
2264 Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)) {
2265 CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
2266 Out << Lexer::getSourceText(R, SM, LO);
2272 if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
2273 const bool quotes = isa<VarDecl>(DR->getDecl());
2276 const LocationContext *LCtx = N->getLocationContext();
2277 const ProgramState *state = N->getState().get();
2278 if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
2279 LCtx).getAsRegion()) {
2280 if (report.isInteresting(R))
2283 const ProgramState *state = N->getState().get();
2284 SVal V = state->getSVal(R);
2285 if (report.isInteresting(V))
2290 Out << DR->getDecl()->getDeclName().getAsString();
2296 if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
2297 QualType OriginalTy = OriginalExpr->getType();
2298 if (OriginalTy->isPointerType()) {
2299 if (IL->getValue() == 0) {
2304 else if (OriginalTy->isObjCObjectPointerType()) {
2305 if (IL->getValue() == 0) {
2311 Out << IL->getValue();
2315 if (const auto *ME = dyn_cast<MemberExpr>(Ex)) {
2316 if (!IsSameFieldName)
2317 Out << "field '" << ME->getMemberDecl()->getName() << '\'';
2320 << Lexer::getSourceText(
2321 CharSourceRange::getTokenRange(Ex->getSourceRange()),
2322 BRC.getSourceManager(), BRC.getASTContext().getLangOpts(), 0)
2329 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTrueTest(
2330 const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC,
2331 BugReport &R, const ExplodedNode *N, bool TookTrue, bool IsAssuming) {
2332 bool shouldInvert = false;
2333 Optional<bool> shouldPrune;
2335 // Check if the field name of the MemberExprs is ambiguous. Example:
2336 // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'.
2337 bool IsSameFieldName = false;
2338 if (const auto *LhsME =
2339 dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts()))
2340 if (const auto *RhsME =
2341 dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts()))
2342 IsSameFieldName = LhsME->getMemberDecl()->getName() ==
2343 RhsME->getMemberDecl()->getName();
2345 SmallString<128> LhsString, RhsString;
2347 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
2348 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R,
2349 N, shouldPrune, IsSameFieldName);
2350 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R,
2351 N, shouldPrune, IsSameFieldName);
2353 shouldInvert = !isVarLHS && isVarRHS;
2356 BinaryOperator::Opcode Op = BExpr->getOpcode();
2358 if (BinaryOperator::isAssignmentOp(Op)) {
2359 // For assignment operators, all that we care about is that the LHS
2360 // evaluates to "true" or "false".
2361 return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N,
2365 // For non-assignment operations, we require that we can understand
2366 // both the LHS and RHS.
2367 if (LhsString.empty() || RhsString.empty() ||
2368 !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
2371 // Should we invert the strings if the LHS is not a variable name?
2372 SmallString<256> buf;
2373 llvm::raw_svector_ostream Out(buf);
2374 Out << (IsAssuming ? "Assuming " : "")
2375 << (shouldInvert ? RhsString : LhsString) << " is ";
2377 // Do we need to invert the opcode?
2381 case BO_LT: Op = BO_GT; break;
2382 case BO_GT: Op = BO_LT; break;
2383 case BO_LE: Op = BO_GE; break;
2384 case BO_GE: Op = BO_LE; break;
2389 case BO_EQ: Op = BO_NE; break;
2390 case BO_NE: Op = BO_EQ; break;
2391 case BO_LT: Op = BO_GE; break;
2392 case BO_GT: Op = BO_LE; break;
2393 case BO_LE: Op = BO_GT; break;
2394 case BO_GE: Op = BO_LT; break;
2404 Out << "not equal to ";
2407 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
2411 Out << (shouldInvert ? LhsString : RhsString);
2412 const LocationContext *LCtx = N->getLocationContext();
2413 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2415 // Convert 'field ...' to 'Field ...' if it is a MemberExpr.
2416 std::string Message = Out.str();
2417 Message[0] = toupper(Message[0]);
2419 // If we know the value create a pop-up note.
2421 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message);
2423 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
2424 if (shouldPrune.hasValue())
2425 event->setPrunable(shouldPrune.getValue());
2429 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
2430 StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC,
2431 BugReport &report, const ExplodedNode *N, bool TookTrue) {
2432 // FIXME: If there's already a constraint tracker for this variable,
2433 // we shouldn't emit anything here (c.f. the double note in
2434 // test/Analysis/inlining/path-notes.c)
2435 SmallString<256> buf;
2436 llvm::raw_svector_ostream Out(buf);
2437 Out << "Assuming " << LhsString << " is ";
2439 if (!printValue(CondVarExpr, Out, N, TookTrue, /*IsAssuming=*/true))
2442 const LocationContext *LCtx = N->getLocationContext();
2443 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
2444 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2446 if (const auto *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
2447 if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2448 const ProgramState *state = N->getState().get();
2449 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2450 if (report.isInteresting(R))
2451 event->setPrunable(false);
2459 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTrueTest(
2460 const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC,
2461 BugReport &report, const ExplodedNode *N, bool TookTrue, bool IsAssuming) {
2462 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
2466 SmallString<256> Buf;
2467 llvm::raw_svector_ostream Out(Buf);
2469 Out << (IsAssuming ? "Assuming '" : "'") << VD->getDeclName() << "' is ";
2471 if (!printValue(DRE, Out, N, TookTrue, IsAssuming))
2474 const LocationContext *LCtx = N->getLocationContext();
2475 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2477 // If we know the value create a pop-up note.
2479 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
2481 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2482 const ProgramState *state = N->getState().get();
2483 if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2484 if (report.isInteresting(R))
2485 event->setPrunable(false);
2487 SVal V = state->getSVal(R);
2488 if (report.isInteresting(V))
2489 event->setPrunable(false);
2492 return std::move(event);
2495 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTrueTest(
2496 const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC,
2497 BugReport &report, const ExplodedNode *N, bool TookTrue, bool IsAssuming) {
2498 SmallString<256> Buf;
2499 llvm::raw_svector_ostream Out(Buf);
2501 Out << (IsAssuming ? "Assuming field '" : "Field '")
2502 << ME->getMemberDecl()->getName() << "' is ";
2504 if (!printValue(ME, Out, N, TookTrue, IsAssuming))
2507 const LocationContext *LCtx = N->getLocationContext();
2508 PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2509 if (!Loc.isValid() || !Loc.asLocation().isValid())
2512 // If we know the value create a pop-up note.
2514 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
2516 return std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2519 bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
2520 const ExplodedNode *N, bool TookTrue,
2522 QualType Ty = CondVarExpr->getType();
2524 if (Ty->isPointerType()) {
2525 Out << (TookTrue ? "non-null" : "null");
2529 if (Ty->isObjCObjectPointerType()) {
2530 Out << (TookTrue ? "non-nil" : "nil");
2534 if (!Ty->isIntegralOrEnumerationType())
2537 Optional<const llvm::APSInt *> IntValue;
2539 IntValue = getConcreteIntegerValue(CondVarExpr, N);
2541 if (IsAssuming || !IntValue.hasValue()) {
2542 if (Ty->isBooleanType())
2543 Out << (TookTrue ? "true" : "false");
2545 Out << (TookTrue ? "not equal to 0" : "0");
2547 if (Ty->isBooleanType())
2548 Out << (IntValue.getValue()->getBoolValue() ? "true" : "false");
2550 Out << *IntValue.getValue();
2556 const char *const ConditionBRVisitor::GenericTrueMessage =
2557 "Assuming the condition is true";
2558 const char *const ConditionBRVisitor::GenericFalseMessage =
2559 "Assuming the condition is false";
2561 bool ConditionBRVisitor::isPieceMessageGeneric(
2562 const PathDiagnosticPiece *Piece) {
2563 return Piece->getString() == GenericTrueMessage ||
2564 Piece->getString() == GenericFalseMessage;
2567 //===----------------------------------------------------------------------===//
2568 // Implementation of LikelyFalsePositiveSuppressionBRVisitor.
2569 //===----------------------------------------------------------------------===//
2571 void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
2572 BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR) {
2573 // Here we suppress false positives coming from system headers. This list is
2574 // based on known issues.
2575 AnalyzerOptions &Options = BRC.getAnalyzerOptions();
2576 const Decl *D = N->getLocationContext()->getDecl();
2578 if (AnalysisDeclContext::isInStdNamespace(D)) {
2579 // Skip reports within the 'std' namespace. Although these can sometimes be
2580 // the user's fault, we currently don't report them very well, and
2581 // Note that this will not help for any other data structure libraries, like
2582 // TR1, Boost, or llvm/ADT.
2583 if (Options.ShouldSuppressFromCXXStandardLibrary) {
2584 BR.markInvalid(getTag(), nullptr);
2587 // If the complete 'std' suppression is not enabled, suppress reports
2588 // from the 'std' namespace that are known to produce false positives.
2590 // The analyzer issues a false use-after-free when std::list::pop_front
2591 // or std::list::pop_back are called multiple times because we cannot
2592 // reason about the internal invariants of the data structure.
2593 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2594 const CXXRecordDecl *CD = MD->getParent();
2595 if (CD->getName() == "list") {
2596 BR.markInvalid(getTag(), nullptr);
2601 // The analyzer issues a false positive when the constructor of
2602 // std::__independent_bits_engine from algorithms is used.
2603 if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
2604 const CXXRecordDecl *CD = MD->getParent();
2605 if (CD->getName() == "__independent_bits_engine") {
2606 BR.markInvalid(getTag(), nullptr);
2611 for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
2612 LCtx = LCtx->getParent()) {
2613 const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
2617 const CXXRecordDecl *CD = MD->getParent();
2618 // The analyzer issues a false positive on
2619 // std::basic_string<uint8_t> v; v.push_back(1);
2621 // std::u16string s; s += u'a';
2622 // because we cannot reason about the internal invariants of the
2624 if (CD->getName() == "basic_string") {
2625 BR.markInvalid(getTag(), nullptr);
2629 // The analyzer issues a false positive on
2630 // std::shared_ptr<int> p(new int(1)); p = nullptr;
2631 // because it does not reason properly about temporary destructors.
2632 if (CD->getName() == "shared_ptr") {
2633 BR.markInvalid(getTag(), nullptr);
2640 // Skip reports within the sys/queue.h macros as we do not have the ability to
2641 // reason about data structure shapes.
2642 SourceManager &SM = BRC.getSourceManager();
2643 FullSourceLoc Loc = BR.getLocation(SM).asLocation();
2644 while (Loc.isMacroID()) {
2645 Loc = Loc.getSpellingLoc();
2646 if (SM.getFilename(Loc).endswith("sys/queue.h")) {
2647 BR.markInvalid(getTag(), nullptr);
2653 //===----------------------------------------------------------------------===//
2654 // Implementation of UndefOrNullArgVisitor.
2655 //===----------------------------------------------------------------------===//
2657 std::shared_ptr<PathDiagnosticPiece>
2658 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
2659 BugReporterContext &BRC, BugReport &BR) {
2660 ProgramStateRef State = N->getState();
2661 ProgramPoint ProgLoc = N->getLocation();
2663 // We are only interested in visiting CallEnter nodes.
2664 Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
2668 // Check if one of the arguments is the region the visitor is tracking.
2669 CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
2670 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
2672 ArrayRef<ParmVarDecl *> parms = Call->parameters();
2674 for (const auto ParamDecl : parms) {
2675 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
2678 // Are we tracking the argument or its subregion?
2679 if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
2682 // Check the function parameter type.
2683 assert(ParamDecl && "Formal parameter has no decl?");
2684 QualType T = ParamDecl->getType();
2686 if (!(T->isAnyPointerType() || T->isReferenceType())) {
2687 // Function can only change the value passed in by address.
2691 // If it is a const pointer value, the function does not intend to
2692 // change the value.
2693 if (T->getPointeeType().isConstQualified())
2696 // Mark the call site (LocationContext) as interesting if the value of the
2697 // argument is undefined or '0'/'NULL'.
2698 SVal BoundVal = State->getSVal(R);
2699 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
2700 BR.markInteresting(CEnter->getCalleeContext());
2707 //===----------------------------------------------------------------------===//
2708 // Implementation of FalsePositiveRefutationBRVisitor.
2709 //===----------------------------------------------------------------------===//
2711 FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
2712 : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
2714 void FalsePositiveRefutationBRVisitor::finalizeVisitor(
2715 BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
2716 // Collect new constraints
2717 VisitNode(EndPathNode, BRC, BR);
2719 // Create a refutation manager
2720 llvm::SMTSolverRef RefutationSolver = llvm::CreateZ3Solver();
2721 ASTContext &Ctx = BRC.getASTContext();
2723 // Add constraints to the solver
2724 for (const auto &I : Constraints) {
2725 const SymbolRef Sym = I.first;
2726 auto RangeIt = I.second.begin();
2728 llvm::SMTExprRef Constraints = SMTConv::getRangeExpr(
2729 RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
2731 while ((++RangeIt) != I.second.end()) {
2732 Constraints = RefutationSolver->mkOr(
2733 Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
2734 RangeIt->From(), RangeIt->To(),
2738 RefutationSolver->addConstraint(Constraints);
2741 // And check for satisfiability
2742 Optional<bool> isSat = RefutationSolver->check();
2743 if (!isSat.hasValue())
2746 if (!isSat.getValue())
2747 BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
2750 std::shared_ptr<PathDiagnosticPiece>
2751 FalsePositiveRefutationBRVisitor::VisitNode(const ExplodedNode *N,
2752 BugReporterContext &,
2754 // Collect new constraints
2755 const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
2756 ConstraintRangeTy::Factory &CF =
2757 N->getState()->get_context<ConstraintRange>();
2759 // Add constraints if we don't have them yet
2760 for (auto const &C : NewCs) {
2761 const SymbolRef &Sym = C.first;
2762 if (!Constraints.contains(Sym)) {
2763 Constraints = CF.add(Constraints, Sym, C.second);
2770 void FalsePositiveRefutationBRVisitor::Profile(
2771 llvm::FoldingSetNodeID &ID) const {
2773 ID.AddPointer(&Tag);
2776 //===----------------------------------------------------------------------===//
2777 // Implementation of TagVisitor.
2778 //===----------------------------------------------------------------------===//
2780 int NoteTag::Kind = 0;
2782 void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
2784 ID.AddPointer(&Tag);
2787 std::shared_ptr<PathDiagnosticPiece>
2788 TagVisitor::VisitNode(const ExplodedNode *N, BugReporterContext &BRC,
2790 ProgramPoint PP = N->getLocation();
2791 const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
2795 if (Optional<std::string> Msg = T->generateMessage(BRC, R)) {
2796 PathDiagnosticLocation Loc =
2797 PathDiagnosticLocation::create(PP, BRC.getSourceManager());
2798 auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
2799 Piece->setPrunable(T->isPrunable());