clang  9.0.0svn
BugReporterVisitors.cpp
Go to the documentation of this file.
1 //===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a set of BugReporter "visitors" which can be used to
11 // enhance the diagnostics reported for a bug.
12 //
13 //===----------------------------------------------------------------------===//
14 
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"
27 #include "clang/Analysis/CFG.h"
31 #include "clang/Basic/LLVM.h"
34 #include "clang/Lex/Lexer.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"
61 #include <cassert>
62 #include <deque>
63 #include <memory>
64 #include <string>
65 #include <utility>
66 
67 using namespace clang;
68 using namespace ento;
69 
70 //===----------------------------------------------------------------------===//
71 // Utility functions.
72 //===----------------------------------------------------------------------===//
73 
74 static const Expr *peelOffPointerArithmetic(const BinaryOperator *B) {
75  if (B->isAdditiveOp() && B->getType()->isPointerType()) {
76  if (B->getLHS()->getType()->isPointerType()) {
77  return B->getLHS();
78  } else if (B->getRHS()->getType()->isPointerType()) {
79  return B->getRHS();
80  }
81  }
82  return nullptr;
83 }
84 
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
94 /// loaded. Examples:
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);
99  if (!E)
100  return nullptr;
101 
102  while (true) {
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.
106  break;
107  }
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)) {
112  E = Inner;
113  } else {
114  // Probably more arithmetic can be pattern-matched here,
115  // but for now give up.
116  break;
117  }
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.
123  E = U->getSubExpr();
124  } else {
125  // Probably more arithmetic can be pattern-matched here,
126  // but for now give up.
127  break;
128  }
129  }
130  // Pattern match for a few useful cases: a[0], p->f, *p etc.
131  else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
132  E = ME->getBase();
133  } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
134  E = IvarRef->getBase();
135  } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
136  E = AE->getBase();
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();
141  } else {
142  // Other arbitrary stuff.
143  break;
144  }
145  }
146 
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();
153 
154  return E;
155 }
156 
157 //===----------------------------------------------------------------------===//
158 // Definitions for bug reporter visitors.
159 //===----------------------------------------------------------------------===//
160 
161 std::shared_ptr<PathDiagnosticPiece>
162 BugReporterVisitor::getEndPath(BugReporterContext &,
163  const ExplodedNode *, BugReport &) {
164  return nullptr;
165 }
166 
167 void
168 BugReporterVisitor::finalizeVisitor(BugReporterContext &,
169  const ExplodedNode *, BugReport &) {}
170 
171 std::shared_ptr<PathDiagnosticPiece> BugReporterVisitor::getDefaultEndPath(
172  BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
173  PathDiagnosticLocation L =
174  PathDiagnosticLocation::createEndOfPath(EndPathNode,BRC.getSourceManager());
175 
176  const auto &Ranges = BR.getRanges();
177 
178  // Only add the statement itself as a range if we didn't specify any
179  // special ranges for this report.
180  auto P = std::make_shared<PathDiagnosticEventPiece>(
181  L, BR.getDescription(), Ranges.begin() == Ranges.end());
182  for (SourceRange Range : Ranges)
183  P->addRange(Range);
184 
185  return P;
186 }
187 
188 /// \return name of the macro inside the location \p Loc.
189 static StringRef getMacroName(SourceLocation Loc,
190  BugReporterContext &BRC) {
192  Loc,
193  BRC.getSourceManager(),
194  BRC.getASTContext().getLangOpts());
195 }
196 
197 /// \return Whether given spelling location corresponds to an expansion
198 /// of a function-like macro.
200  const SourceManager &SM) {
201  if (!Loc.isMacroID())
202  return false;
203  while (SM.isMacroArgExpansion(Loc))
204  Loc = SM.getImmediateExpansionRange(Loc).getBegin();
205  std::pair<FileID, unsigned> TLInfo = SM.getDecomposedLoc(Loc);
206  SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
207  const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
208  return EInfo.isFunctionMacroExpansion();
209 }
210 
211 /// \return Whether \c RegionOfInterest was modified at \p N,
212 /// where \p ReturnState is a state associated with the return
213 /// from the current frame.
215  const SubRegion *RegionOfInterest,
216  const ExplodedNode *N,
217  SVal ValueAfter) {
218  ProgramStateRef State = N->getState();
219  ProgramStateManager &Mgr = N->getState()->getStateManager();
220 
221  if (!N->getLocationAs<PostStore>()
222  && !N->getLocationAs<PostInitializer>()
223  && !N->getLocationAs<PostStmt>())
224  return false;
225 
226  // Writing into region of interest.
227  if (auto PS = N->getLocationAs<PostStmt>())
228  if (auto *BO = PS->getStmtAs<BinaryOperator>())
229  if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
230  N->getSVal(BO->getLHS()).getAsRegion()))
231  return true;
232 
233  // SVal after the state is possibly different.
234  SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
235  if (!Mgr.getSValBuilder().areEqual(State, ValueAtN, ValueAfter).isConstrainedTrue() &&
236  (!ValueAtN.isUndef() || !ValueAfter.isUndef()))
237  return true;
238 
239  return false;
240 }
241 
242 
243 namespace {
244 
245 /// Put a diagnostic on return statement of all inlined functions
246 /// for which the region of interest \p RegionOfInterest was passed into,
247 /// but not written inside, and it has caused an undefined read or a null
248 /// pointer dereference outside.
249 class NoStoreFuncVisitor final : public BugReporterVisitor {
250  const SubRegion *RegionOfInterest;
251  MemRegionManager &MmrMgr;
252  const SourceManager &SM;
253  const PrintingPolicy &PP;
254 
255  /// Recursion limit for dereferencing fields when looking for the
256  /// region of interest.
257  /// The limit of two indicates that we will dereference fields only once.
258  static const unsigned DEREFERENCE_LIMIT = 2;
259 
260  /// Frames writing into \c RegionOfInterest.
261  /// This visitor generates a note only if a function does not write into
262  /// a region of interest. This information is not immediately available
263  /// by looking at the node associated with the exit from the function
264  /// (usually the return statement). To avoid recomputing the same information
265  /// many times (going up the path for each node and checking whether the
266  /// region was written into) we instead lazily compute the
267  /// stack frames along the path which write into the region of interest.
268  llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingRegion;
269  llvm::SmallPtrSet<const StackFrameContext *, 32> FramesModifyingCalculated;
270 
271  using RegionVector = SmallVector<const MemRegion *, 5>;
272 public:
273  NoStoreFuncVisitor(const SubRegion *R)
274  : RegionOfInterest(R), MmrMgr(*R->getMemRegionManager()),
275  SM(MmrMgr.getContext().getSourceManager()),
276  PP(MmrMgr.getContext().getPrintingPolicy()) {}
277 
278  void Profile(llvm::FoldingSetNodeID &ID) const override {
279  static int Tag = 0;
280  ID.AddPointer(&Tag);
281  ID.AddPointer(RegionOfInterest);
282  }
283 
284  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
285  BugReporterContext &BR,
286  BugReport &) override {
287 
288  const LocationContext *Ctx = N->getLocationContext();
289  const StackFrameContext *SCtx = Ctx->getStackFrame();
290  ProgramStateRef State = N->getState();
291  auto CallExitLoc = N->getLocationAs<CallExitBegin>();
292 
293  // No diagnostic if region was modified inside the frame.
294  if (!CallExitLoc || isRegionOfInterestModifiedInFrame(N))
295  return nullptr;
296 
297  CallEventRef<> Call =
298  BR.getStateManager().getCallEventManager().getCaller(SCtx, State);
299 
300  if (SM.isInSystemHeader(Call->getDecl()->getSourceRange().getBegin()))
301  return nullptr;
302 
303  // Region of interest corresponds to an IVar, exiting a method
304  // which could have written into that IVar, but did not.
305  if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
306  if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
307  const MemRegion *SelfRegion = MC->getReceiverSVal().getAsRegion();
308  if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
309  potentiallyWritesIntoIvar(Call->getRuntimeDefinition().getDecl(),
310  IvarR->getDecl()))
311  return notModifiedDiagnostics(N, {}, SelfRegion, "self",
312  /*FirstIsReferenceType=*/false, 1);
313  }
314  }
315 
316  if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
317  const MemRegion *ThisR = CCall->getCXXThisVal().getAsRegion();
318  if (RegionOfInterest->isSubRegionOf(ThisR)
319  && !CCall->getDecl()->isImplicit())
320  return notModifiedDiagnostics(N, {}, ThisR, "this",
321  /*FirstIsReferenceType=*/false, 1);
322 
323  // Do not generate diagnostics for not modified parameters in
324  // constructors.
325  return nullptr;
326  }
327 
328  ArrayRef<ParmVarDecl *> parameters = getCallParameters(Call);
329  for (unsigned I = 0; I < Call->getNumArgs() && I < parameters.size(); ++I) {
330  const ParmVarDecl *PVD = parameters[I];
331  SVal S = Call->getArgSVal(I);
332  bool ParamIsReferenceType = PVD->getType()->isReferenceType();
333  std::string ParamName = PVD->getNameAsString();
334 
335  int IndirectionLevel = 1;
336  QualType T = PVD->getType();
337  while (const MemRegion *R = S.getAsRegion()) {
338  if (RegionOfInterest->isSubRegionOf(R) && !isPointerToConst(T))
339  return notModifiedDiagnostics(N, {}, R, ParamName,
340  ParamIsReferenceType, IndirectionLevel);
341 
342  QualType PT = T->getPointeeType();
343  if (PT.isNull() || PT->isVoidType()) break;
344 
345  if (const RecordDecl *RD = PT->getAsRecordDecl())
346  if (auto P = findRegionOfInterestInRecord(RD, State, R))
347  return notModifiedDiagnostics(N, *P, RegionOfInterest, ParamName,
348  ParamIsReferenceType,
349  IndirectionLevel);
350 
351  S = State->getSVal(R, PT);
352  T = PT;
353  IndirectionLevel++;
354  }
355  }
356 
357  return nullptr;
358  }
359 
360 private:
361  /// Attempts to find the region of interest in a given CXX decl,
362  /// by either following the base classes or fields.
363  /// Dereferences fields up to a given recursion limit.
364  /// Note that \p Vec is passed by value, leading to quadratic copying cost,
365  /// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
366  /// \return A chain fields leading to the region of interest or None.
368  findRegionOfInterestInRecord(const RecordDecl *RD, ProgramStateRef State,
369  const MemRegion *R,
370  const RegionVector &Vec = {},
371  int depth = 0) {
372 
373  if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth.
374  return None;
375 
376  if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
377  if (!RDX->hasDefinition())
378  return None;
379 
380  // Recursively examine the base classes.
381  // Note that following base classes does not increase the recursion depth.
382  if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
383  for (const auto II : RDX->bases())
384  if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
385  if (auto Out = findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
386  return Out;
387 
388  for (const FieldDecl *I : RD->fields()) {
389  QualType FT = I->getType();
390  const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
391  const SVal V = State->getSVal(FR);
392  const MemRegion *VR = V.getAsRegion();
393 
394  RegionVector VecF = Vec;
395  VecF.push_back(FR);
396 
397  if (RegionOfInterest == VR)
398  return VecF;
399 
400  if (const RecordDecl *RRD = FT->getAsRecordDecl())
401  if (auto Out =
402  findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
403  return Out;
404 
405  QualType PT = FT->getPointeeType();
406  if (PT.isNull() || PT->isVoidType() || !VR) continue;
407 
408  if (const RecordDecl *RRD = PT->getAsRecordDecl())
409  if (auto Out =
410  findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
411  return Out;
412 
413  }
414 
415  return None;
416  }
417 
418  /// \return Whether the method declaration \p Parent
419  /// syntactically has a binary operation writing into the ivar \p Ivar.
420  bool potentiallyWritesIntoIvar(const Decl *Parent,
421  const ObjCIvarDecl *Ivar) {
422  using namespace ast_matchers;
423  const char * IvarBind = "Ivar";
424  if (!Parent || !Parent->hasBody())
425  return false;
426  StatementMatcher WriteIntoIvarM = binaryOperator(
427  hasOperatorName("="),
428  hasLHS(ignoringParenImpCasts(
429  objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
430  StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
431  auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
432  for (BoundNodes &Match : Matches) {
433  auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
434  if (IvarRef->isFreeIvar())
435  return true;
436 
437  const Expr *Base = IvarRef->getBase();
438  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
439  Base = ICE->getSubExpr();
440 
441  if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
442  if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
443  if (ID->getParameterKind() == ImplicitParamDecl::ObjCSelf)
444  return true;
445 
446  return false;
447  }
448  return false;
449  }
450 
451  /// Check and lazily calculate whether the region of interest is
452  /// modified in the stack frame to which \p N belongs.
453  /// The calculation is cached in FramesModifyingRegion.
454  bool isRegionOfInterestModifiedInFrame(const ExplodedNode *N) {
455  const LocationContext *Ctx = N->getLocationContext();
456  const StackFrameContext *SCtx = Ctx->getStackFrame();
457  if (!FramesModifyingCalculated.count(SCtx))
458  findModifyingFrames(N);
459  return FramesModifyingRegion.count(SCtx);
460  }
461 
462 
463  /// Write to \c FramesModifyingRegion all stack frames along
464  /// the path in the current stack frame which modify \c RegionOfInterest.
465  void findModifyingFrames(const ExplodedNode *N) {
466  assert(N->getLocationAs<CallExitBegin>());
467  ProgramStateRef LastReturnState = N->getState();
468  SVal ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
469  const LocationContext *Ctx = N->getLocationContext();
470  const StackFrameContext *OriginalSCtx = Ctx->getStackFrame();
471 
472  do {
473  ProgramStateRef State = N->getState();
474  auto CallExitLoc = N->getLocationAs<CallExitBegin>();
475  if (CallExitLoc) {
476  LastReturnState = State;
477  ValueAtReturn = LastReturnState->getSVal(RegionOfInterest);
478  }
479 
480  FramesModifyingCalculated.insert(
481  N->getLocationContext()->getStackFrame());
482 
483  if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtReturn)) {
484  const StackFrameContext *SCtx = N->getStackFrame();
485  while (!SCtx->inTopFrame()) {
486  auto p = FramesModifyingRegion.insert(SCtx);
487  if (!p.second)
488  break; // Frame and all its parents already inserted.
489  SCtx = SCtx->getParent()->getStackFrame();
490  }
491  }
492 
493  // Stop calculation at the call to the current function.
494  if (auto CE = N->getLocationAs<CallEnter>())
495  if (CE->getCalleeContext() == OriginalSCtx)
496  break;
497 
498  N = N->getFirstPred();
499  } while (N);
500  }
501 
502  /// Get parameters associated with runtime definition in order
503  /// to get the correct parameter name.
504  ArrayRef<ParmVarDecl *> getCallParameters(CallEventRef<> Call) {
505  // Use runtime definition, if available.
506  RuntimeDefinition RD = Call->getRuntimeDefinition();
507  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(RD.getDecl()))
508  return FD->parameters();
509  if (const auto *MD = dyn_cast_or_null<ObjCMethodDecl>(RD.getDecl()))
510  return MD->parameters();
511 
512  return Call->parameters();
513  }
514 
515  /// \return whether \p Ty points to a const type, or is a const reference.
516  bool isPointerToConst(QualType Ty) {
517  return !Ty->getPointeeType().isNull() &&
519  }
520 
521  /// \return Diagnostics piece for region not modified in the current function.
522  std::shared_ptr<PathDiagnosticPiece>
523  notModifiedDiagnostics(const ExplodedNode *N, const RegionVector &FieldChain,
524  const MemRegion *MatchedRegion, StringRef FirstElement,
525  bool FirstIsReferenceType, unsigned IndirectionLevel) {
526 
527  PathDiagnosticLocation L =
528  PathDiagnosticLocation::create(N->getLocation(), SM);
529 
530  SmallString<256> sbuf;
531  llvm::raw_svector_ostream os(sbuf);
532  os << "Returning without writing to '";
533 
534  // Do not generate the note if failed to pretty-print.
535  if (!prettyPrintRegionName(FirstElement, FirstIsReferenceType,
536  MatchedRegion, FieldChain, IndirectionLevel, os))
537  return nullptr;
538 
539  os << "'";
540  return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
541  }
542 
543  /// Pretty-print region \p MatchedRegion to \p os.
544  /// \return Whether printing succeeded.
545  bool prettyPrintRegionName(StringRef FirstElement, bool FirstIsReferenceType,
546  const MemRegion *MatchedRegion,
547  const RegionVector &FieldChain,
548  int IndirectionLevel,
549  llvm::raw_svector_ostream &os) {
550 
551  if (FirstIsReferenceType)
552  IndirectionLevel--;
553 
554  RegionVector RegionSequence;
555 
556  // Add the regions in the reverse order, then reverse the resulting array.
557  assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
558  const MemRegion *R = RegionOfInterest;
559  while (R != MatchedRegion) {
560  RegionSequence.push_back(R);
561  R = cast<SubRegion>(R)->getSuperRegion();
562  }
563  std::reverse(RegionSequence.begin(), RegionSequence.end());
564  RegionSequence.append(FieldChain.begin(), FieldChain.end());
565 
566  StringRef Sep;
567  for (const MemRegion *R : RegionSequence) {
568 
569  // Just keep going up to the base region.
570  // Element regions may appear due to casts.
571  if (isa<CXXBaseObjectRegion>(R) || isa<CXXTempObjectRegion>(R))
572  continue;
573 
574  if (Sep.empty())
575  Sep = prettyPrintFirstElement(FirstElement,
576  /*MoreItemsExpected=*/true,
577  IndirectionLevel, os);
578 
579  os << Sep;
580 
581  // Can only reasonably pretty-print DeclRegions.
582  if (!isa<DeclRegion>(R))
583  return false;
584 
585  const auto *DR = cast<DeclRegion>(R);
586  Sep = DR->getValueType()->isAnyPointerType() ? "->" : ".";
587  DR->getDecl()->getDeclName().print(os, PP);
588  }
589 
590  if (Sep.empty())
591  prettyPrintFirstElement(FirstElement,
592  /*MoreItemsExpected=*/false, IndirectionLevel,
593  os);
594  return true;
595  }
596 
597  /// Print first item in the chain, return new separator.
598  StringRef prettyPrintFirstElement(StringRef FirstElement,
599  bool MoreItemsExpected,
600  int IndirectionLevel,
601  llvm::raw_svector_ostream &os) {
602  StringRef Out = ".";
603 
604  if (IndirectionLevel > 0 && MoreItemsExpected) {
605  IndirectionLevel--;
606  Out = "->";
607  }
608 
609  if (IndirectionLevel > 0 && MoreItemsExpected)
610  os << "(";
611 
612  for (int i=0; i<IndirectionLevel; i++)
613  os << "*";
614  os << FirstElement;
615 
616  if (IndirectionLevel > 0 && MoreItemsExpected)
617  os << ")";
618 
619  return Out;
620  }
621 };
622 
623 /// Suppress null-pointer-dereference bugs where dereferenced null was returned
624 /// the macro.
625 class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
626  const SubRegion *RegionOfInterest;
627  const SVal ValueAtDereference;
628 
629  // Do not invalidate the reports where the value was modified
630  // after it got assigned to from the macro.
631  bool WasModified = false;
632 
633 public:
634  MacroNullReturnSuppressionVisitor(const SubRegion *R,
635  const SVal V) : RegionOfInterest(R),
636  ValueAtDereference(V) {}
637 
638  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
639  BugReporterContext &BRC,
640  BugReport &BR) override {
641  if (WasModified)
642  return nullptr;
643 
644  auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
645  if (!BugPoint)
646  return nullptr;
647 
648  const SourceManager &SMgr = BRC.getSourceManager();
649  if (auto Loc = matchAssignment(N)) {
650  if (isFunctionMacroExpansion(*Loc, SMgr)) {
651  std::string MacroName = getMacroName(*Loc, BRC);
652  SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
653  if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
654  BR.markInvalid(getTag(), MacroName.c_str());
655  }
656  }
657 
658  if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
659  WasModified = true;
660 
661  return nullptr;
662  }
663 
664  static void addMacroVisitorIfNecessary(
665  const ExplodedNode *N, const MemRegion *R,
666  bool EnableNullFPSuppression, BugReport &BR,
667  const SVal V) {
668  AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
669  if (EnableNullFPSuppression &&
670  Options.ShouldSuppressNullReturnPaths && V.getAs<Loc>())
671  BR.addVisitor(llvm::make_unique<MacroNullReturnSuppressionVisitor>(
672  R->getAs<SubRegion>(), V));
673  }
674 
675  void* getTag() const {
676  static int Tag = 0;
677  return static_cast<void *>(&Tag);
678  }
679 
680  void Profile(llvm::FoldingSetNodeID &ID) const override {
681  ID.AddPointer(getTag());
682  }
683 
684 private:
685  /// \return Source location of right hand side of an assignment
686  /// into \c RegionOfInterest, empty optional if none found.
687  Optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
689  ProgramStateRef State = N->getState();
690  auto *LCtx = N->getLocationContext();
691  if (!S)
692  return None;
693 
694  if (const auto *DS = dyn_cast<DeclStmt>(S)) {
695  if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
696  if (const Expr *RHS = VD->getInit())
697  if (RegionOfInterest->isSubRegionOf(
698  State->getLValue(VD, LCtx).getAsRegion()))
699  return RHS->getBeginLoc();
700  } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
701  const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
702  const Expr *RHS = BO->getRHS();
703  if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
704  return RHS->getBeginLoc();
705  }
706  }
707  return None;
708  }
709 };
710 
711 /// Emits an extra note at the return statement of an interesting stack frame.
712 ///
713 /// The returned value is marked as an interesting value, and if it's null,
714 /// adds a visitor to track where it became null.
715 ///
716 /// This visitor is intended to be used when another visitor discovers that an
717 /// interesting value comes from an inlined function call.
718 class ReturnVisitor : public BugReporterVisitor {
719  const StackFrameContext *StackFrame;
720  enum {
721  Initial,
722  MaybeUnsuppress,
723  Satisfied
724  } Mode = Initial;
725 
726  bool EnableNullFPSuppression;
727  bool ShouldInvalidate = true;
728  AnalyzerOptions& Options;
729 
730 public:
731  ReturnVisitor(const StackFrameContext *Frame,
732  bool Suppressed,
733  AnalyzerOptions &Options)
734  : StackFrame(Frame), EnableNullFPSuppression(Suppressed),
735  Options(Options) {}
736 
737  static void *getTag() {
738  static int Tag = 0;
739  return static_cast<void *>(&Tag);
740  }
741 
742  void Profile(llvm::FoldingSetNodeID &ID) const override {
743  ID.AddPointer(ReturnVisitor::getTag());
744  ID.AddPointer(StackFrame);
745  ID.AddBoolean(EnableNullFPSuppression);
746  }
747 
748  /// Adds a ReturnVisitor if the given statement represents a call that was
749  /// inlined.
750  ///
751  /// This will search back through the ExplodedGraph, starting from the given
752  /// node, looking for when the given statement was processed. If it turns out
753  /// the statement is a call that was inlined, we add the visitor to the
754  /// bug report, so it can print a note later.
755  static void addVisitorIfNecessary(const ExplodedNode *Node, const Stmt *S,
756  BugReport &BR,
757  bool InEnableNullFPSuppression) {
758  if (!CallEvent::isCallStmt(S))
759  return;
760 
761  // First, find when we processed the statement.
762  do {
763  if (auto CEE = Node->getLocationAs<CallExitEnd>())
764  if (CEE->getCalleeContext()->getCallSite() == S)
765  break;
766  if (auto SP = Node->getLocationAs<StmtPoint>())
767  if (SP->getStmt() == S)
768  break;
769 
770  Node = Node->getFirstPred();
771  } while (Node);
772 
773  // Next, step over any post-statement checks.
774  while (Node && Node->getLocation().getAs<PostStmt>())
775  Node = Node->getFirstPred();
776  if (!Node)
777  return;
778 
779  // Finally, see if we inlined the call.
780  Optional<CallExitEnd> CEE = Node->getLocationAs<CallExitEnd>();
781  if (!CEE)
782  return;
783 
784  const StackFrameContext *CalleeContext = CEE->getCalleeContext();
785  if (CalleeContext->getCallSite() != S)
786  return;
787 
788  // Check the return value.
789  ProgramStateRef State = Node->getState();
790  SVal RetVal = Node->getSVal(S);
791 
792  // Handle cases where a reference is returned and then immediately used.
793  if (cast<Expr>(S)->isGLValue())
794  if (Optional<Loc> LValue = RetVal.getAs<Loc>())
795  RetVal = State->getSVal(*LValue);
796 
797  // See if the return value is NULL. If so, suppress the report.
798  AnalyzerOptions &Options = State->getAnalysisManager().options;
799 
800  bool EnableNullFPSuppression = false;
801  if (InEnableNullFPSuppression &&
802  Options.ShouldSuppressNullReturnPaths)
803  if (Optional<Loc> RetLoc = RetVal.getAs<Loc>())
804  EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
805 
806  BR.markInteresting(CalleeContext);
807  BR.addVisitor(llvm::make_unique<ReturnVisitor>(CalleeContext,
808  EnableNullFPSuppression,
809  Options));
810  }
811 
812  std::shared_ptr<PathDiagnosticPiece>
813  visitNodeInitial(const ExplodedNode *N,
814  BugReporterContext &BRC, BugReport &BR) {
815  // Only print a message at the interesting return statement.
816  if (N->getLocationContext() != StackFrame)
817  return nullptr;
818 
819  Optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
820  if (!SP)
821  return nullptr;
822 
823  const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
824  if (!Ret)
825  return nullptr;
826 
827  // Okay, we're at the right return statement, but do we have the return
828  // value available?
829  ProgramStateRef State = N->getState();
830  SVal V = State->getSVal(Ret, StackFrame);
831  if (V.isUnknownOrUndef())
832  return nullptr;
833 
834  // Don't print any more notes after this one.
835  Mode = Satisfied;
836 
837  const Expr *RetE = Ret->getRetValue();
838  assert(RetE && "Tracking a return value for a void function");
839 
840  // Handle cases where a reference is returned and then immediately used.
841  Optional<Loc> LValue;
842  if (RetE->isGLValue()) {
843  if ((LValue = V.getAs<Loc>())) {
844  SVal RValue = State->getRawSVal(*LValue, RetE->getType());
845  if (RValue.getAs<DefinedSVal>())
846  V = RValue;
847  }
848  }
849 
850  // Ignore aggregate rvalues.
851  if (V.getAs<nonloc::LazyCompoundVal>() ||
852  V.getAs<nonloc::CompoundVal>())
853  return nullptr;
854 
855  RetE = RetE->IgnoreParenCasts();
856 
857  // If we're returning 0, we should track where that 0 came from.
858  bugreporter::trackExpressionValue(N, RetE, BR, EnableNullFPSuppression);
859 
860  // Build an appropriate message based on the return value.
861  SmallString<64> Msg;
862  llvm::raw_svector_ostream Out(Msg);
863 
864  if (State->isNull(V).isConstrainedTrue()) {
865  if (V.getAs<Loc>()) {
866 
867  // If we have counter-suppression enabled, make sure we keep visiting
868  // future nodes. We want to emit a path note as well, in case
869  // the report is resurrected as valid later on.
870  if (EnableNullFPSuppression &&
871  Options.ShouldAvoidSuppressingNullArgumentPaths)
872  Mode = MaybeUnsuppress;
873 
874  if (RetE->getType()->isObjCObjectPointerType()) {
875  Out << "Returning nil";
876  } else {
877  Out << "Returning null pointer";
878  }
879  } else {
880  Out << "Returning zero";
881  }
882 
883  } else {
884  if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
885  Out << "Returning the value " << CI->getValue();
886  } else if (V.getAs<Loc>()) {
887  Out << "Returning pointer";
888  } else {
889  Out << "Returning value";
890  }
891  }
892 
893  if (LValue) {
894  if (const MemRegion *MR = LValue->getAsRegion()) {
895  if (MR->canPrintPretty()) {
896  Out << " (reference to ";
897  MR->printPretty(Out);
898  Out << ")";
899  }
900  }
901  } else {
902  // FIXME: We should have a more generalized location printing mechanism.
903  if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
904  if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
905  Out << " (loaded from '" << *DD << "')";
906  }
907 
908  PathDiagnosticLocation L(Ret, BRC.getSourceManager(), StackFrame);
909  if (!L.isValid() || !L.asLocation().isValid())
910  return nullptr;
911 
912  return std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
913  }
914 
915  std::shared_ptr<PathDiagnosticPiece>
916  visitNodeMaybeUnsuppress(const ExplodedNode *N,
917  BugReporterContext &BRC, BugReport &BR) {
918 #ifndef NDEBUG
919  assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
920 #endif
921 
922  // Are we at the entry node for this call?
923  Optional<CallEnter> CE = N->getLocationAs<CallEnter>();
924  if (!CE)
925  return nullptr;
926 
927  if (CE->getCalleeContext() != StackFrame)
928  return nullptr;
929 
930  Mode = Satisfied;
931 
932  // Don't automatically suppress a report if one of the arguments is
933  // known to be a null pointer. Instead, start tracking /that/ null
934  // value back to its origin.
935  ProgramStateManager &StateMgr = BRC.getStateManager();
936  CallEventManager &CallMgr = StateMgr.getCallEventManager();
937 
938  ProgramStateRef State = N->getState();
939  CallEventRef<> Call = CallMgr.getCaller(StackFrame, State);
940  for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
941  Optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
942  if (!ArgV)
943  continue;
944 
945  const Expr *ArgE = Call->getArgExpr(I);
946  if (!ArgE)
947  continue;
948 
949  // Is it possible for this argument to be non-null?
950  if (!State->isNull(*ArgV).isConstrainedTrue())
951  continue;
952 
953  if (bugreporter::trackExpressionValue(N, ArgE, BR, EnableNullFPSuppression))
954  ShouldInvalidate = false;
955 
956  // If we /can't/ track the null pointer, we should err on the side of
957  // false negatives, and continue towards marking this report invalid.
958  // (We will still look at the other arguments, though.)
959  }
960 
961  return nullptr;
962  }
963 
964  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
965  BugReporterContext &BRC,
966  BugReport &BR) override {
967  switch (Mode) {
968  case Initial:
969  return visitNodeInitial(N, BRC, BR);
970  case MaybeUnsuppress:
971  return visitNodeMaybeUnsuppress(N, BRC, BR);
972  case Satisfied:
973  return nullptr;
974  }
975 
976  llvm_unreachable("Invalid visit mode!");
977  }
978 
979  void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
980  BugReport &BR) override {
981  if (EnableNullFPSuppression && ShouldInvalidate)
982  BR.markInvalid(ReturnVisitor::getTag(), StackFrame);
983  }
984 };
985 
986 } // namespace
987 
988 void FindLastStoreBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
989  static int tag = 0;
990  ID.AddPointer(&tag);
991  ID.AddPointer(R);
992  ID.Add(V);
993  ID.AddBoolean(EnableNullFPSuppression);
994 }
995 
996 /// Returns true if \p N represents the DeclStmt declaring and initializing
997 /// \p VR.
998 static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
999  Optional<PostStmt> P = N->getLocationAs<PostStmt>();
1000  if (!P)
1001  return false;
1002 
1003  const DeclStmt *DS = P->getStmtAs<DeclStmt>();
1004  if (!DS)
1005  return false;
1006 
1007  if (DS->getSingleDecl() != VR->getDecl())
1008  return false;
1009 
1010  const MemSpaceRegion *VarSpace = VR->getMemorySpace();
1011  const auto *FrameSpace = dyn_cast<StackSpaceRegion>(VarSpace);
1012  if (!FrameSpace) {
1013  // If we ever directly evaluate global DeclStmts, this assertion will be
1014  // invalid, but this still seems preferable to silently accepting an
1015  // initialization that may be for a path-sensitive variable.
1016  assert(VR->getDecl()->isStaticLocal() && "non-static stackless VarRegion");
1017  return true;
1018  }
1019 
1020  assert(VR->getDecl()->hasLocalStorage());
1021  const LocationContext *LCtx = N->getLocationContext();
1022  return FrameSpace->getStackFrame() == LCtx->getStackFrame();
1023 }
1024 
1025 /// Show diagnostics for initializing or declaring a region \p R with a bad value.
1026 static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os,
1027  const MemRegion *R, SVal V, const DeclStmt *DS) {
1028  if (R->canPrintPretty()) {
1029  R->printPretty(os);
1030  os << " ";
1031  }
1032 
1033  if (V.getAs<loc::ConcreteInt>()) {
1034  bool b = false;
1035  if (R->isBoundable()) {
1036  if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1037  if (TR->getValueType()->isObjCObjectPointerType()) {
1038  os << action << "nil";
1039  b = true;
1040  }
1041  }
1042  }
1043  if (!b)
1044  os << action << "a null pointer value";
1045 
1046  } else if (auto CVal = V.getAs<nonloc::ConcreteInt>()) {
1047  os << action << CVal->getValue();
1048  } else if (DS) {
1049  if (V.isUndef()) {
1050  if (isa<VarRegion>(R)) {
1051  const auto *VD = cast<VarDecl>(DS->getSingleDecl());
1052  if (VD->getInit()) {
1053  os << (R->canPrintPretty() ? "initialized" : "Initializing")
1054  << " to a garbage value";
1055  } else {
1056  os << (R->canPrintPretty() ? "declared" : "Declaring")
1057  << " without an initial value";
1058  }
1059  }
1060  } else {
1061  os << (R->canPrintPretty() ? "initialized" : "Initialized")
1062  << " here";
1063  }
1064  }
1065 }
1066 
1067 /// Display diagnostics for passing bad region as a parameter.
1068 static void showBRParamDiagnostics(llvm::raw_svector_ostream& os,
1069  const VarRegion *VR,
1070  SVal V) {
1071  const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1072 
1073  os << "Passing ";
1074 
1075  if (V.getAs<loc::ConcreteInt>()) {
1076  if (Param->getType()->isObjCObjectPointerType())
1077  os << "nil object reference";
1078  else
1079  os << "null pointer value";
1080  } else if (V.isUndef()) {
1081  os << "uninitialized value";
1082  } else if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1083  os << "the value " << CI->getValue();
1084  } else {
1085  os << "value";
1086  }
1087 
1088  // Printed parameter indexes are 1-based, not 0-based.
1089  unsigned Idx = Param->getFunctionScopeIndex() + 1;
1090  os << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
1091  if (VR->canPrintPretty()) {
1092  os << " ";
1093  VR->printPretty(os);
1094  }
1095 }
1096 
1097 /// Show default diagnostics for storing bad region.
1098 static void showBRDefaultDiagnostics(llvm::raw_svector_ostream& os,
1099  const MemRegion *R,
1100  SVal V) {
1101  if (V.getAs<loc::ConcreteInt>()) {
1102  bool b = false;
1103  if (R->isBoundable()) {
1104  if (const auto *TR = dyn_cast<TypedValueRegion>(R)) {
1105  if (TR->getValueType()->isObjCObjectPointerType()) {
1106  os << "nil object reference stored";
1107  b = true;
1108  }
1109  }
1110  }
1111  if (!b) {
1112  if (R->canPrintPretty())
1113  os << "Null pointer value stored";
1114  else
1115  os << "Storing null pointer value";
1116  }
1117 
1118  } else if (V.isUndef()) {
1119  if (R->canPrintPretty())
1120  os << "Uninitialized value stored";
1121  else
1122  os << "Storing uninitialized value";
1123 
1124  } else if (auto CV = V.getAs<nonloc::ConcreteInt>()) {
1125  if (R->canPrintPretty())
1126  os << "The value " << CV->getValue() << " is assigned";
1127  else
1128  os << "Assigning " << CV->getValue();
1129 
1130  } else {
1131  if (R->canPrintPretty())
1132  os << "Value assigned";
1133  else
1134  os << "Assigning value";
1135  }
1136 
1137  if (R->canPrintPretty()) {
1138  os << " to ";
1139  R->printPretty(os);
1140  }
1141 }
1142 
1143 std::shared_ptr<PathDiagnosticPiece>
1144 FindLastStoreBRVisitor::VisitNode(const ExplodedNode *Succ,
1145  BugReporterContext &BRC, BugReport &BR) {
1146  if (Satisfied)
1147  return nullptr;
1148 
1149  const ExplodedNode *StoreSite = nullptr;
1150  const ExplodedNode *Pred = Succ->getFirstPred();
1151  const Expr *InitE = nullptr;
1152  bool IsParam = false;
1153 
1154  // First see if we reached the declaration of the region.
1155  if (const auto *VR = dyn_cast<VarRegion>(R)) {
1156  if (isInitializationOfVar(Pred, VR)) {
1157  StoreSite = Pred;
1158  InitE = VR->getDecl()->getInit();
1159  }
1160  }
1161 
1162  // If this is a post initializer expression, initializing the region, we
1163  // should track the initializer expression.
1164  if (Optional<PostInitializer> PIP = Pred->getLocationAs<PostInitializer>()) {
1165  const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1166  if (FieldReg && FieldReg == R) {
1167  StoreSite = Pred;
1168  InitE = PIP->getInitializer()->getInit();
1169  }
1170  }
1171 
1172  // Otherwise, see if this is the store site:
1173  // (1) Succ has this binding and Pred does not, i.e. this is
1174  // where the binding first occurred.
1175  // (2) Succ has this binding and is a PostStore node for this region, i.e.
1176  // the same binding was re-assigned here.
1177  if (!StoreSite) {
1178  if (Succ->getState()->getSVal(R) != V)
1179  return nullptr;
1180 
1181  if (Pred->getState()->getSVal(R) == V) {
1182  Optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1183  if (!PS || PS->getLocationValue() != R)
1184  return nullptr;
1185  }
1186 
1187  StoreSite = Succ;
1188 
1189  // If this is an assignment expression, we can track the value
1190  // being assigned.
1191  if (Optional<PostStmt> P = Succ->getLocationAs<PostStmt>())
1192  if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>())
1193  if (BO->isAssignmentOp())
1194  InitE = BO->getRHS();
1195 
1196  // If this is a call entry, the variable should be a parameter.
1197  // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1198  // 'this' should never be NULL, but this visitor isn't just for NULL and
1199  // UndefinedVal.)
1200  if (Optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1201  if (const auto *VR = dyn_cast<VarRegion>(R)) {
1202  const auto *Param = cast<ParmVarDecl>(VR->getDecl());
1203 
1204  ProgramStateManager &StateMgr = BRC.getStateManager();
1205  CallEventManager &CallMgr = StateMgr.getCallEventManager();
1206 
1207  CallEventRef<> Call = CallMgr.getCaller(CE->getCalleeContext(),
1208  Succ->getState());
1209  InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1210  IsParam = true;
1211  }
1212  }
1213 
1214  // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1215  // is wrapped inside of it.
1216  if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1217  InitE = TmpR->getExpr();
1218  }
1219 
1220  if (!StoreSite)
1221  return nullptr;
1222  Satisfied = true;
1223 
1224  // If we have an expression that provided the value, try to track where it
1225  // came from.
1226  if (InitE) {
1227  if (V.isUndef() ||
1228  V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1229  if (!IsParam)
1230  InitE = InitE->IgnoreParenCasts();
1231  bugreporter::trackExpressionValue(StoreSite, InitE, BR,
1232  EnableNullFPSuppression);
1233  }
1234  ReturnVisitor::addVisitorIfNecessary(StoreSite, InitE->IgnoreParenCasts(),
1235  BR, EnableNullFPSuppression);
1236  }
1237 
1238  // Okay, we've found the binding. Emit an appropriate message.
1239  SmallString<256> sbuf;
1240  llvm::raw_svector_ostream os(sbuf);
1241 
1242  if (Optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1243  const Stmt *S = PS->getStmt();
1244  const char *action = nullptr;
1245  const auto *DS = dyn_cast<DeclStmt>(S);
1246  const auto *VR = dyn_cast<VarRegion>(R);
1247 
1248  if (DS) {
1249  action = R->canPrintPretty() ? "initialized to " :
1250  "Initializing to ";
1251  } else if (isa<BlockExpr>(S)) {
1252  action = R->canPrintPretty() ? "captured by block as " :
1253  "Captured by block as ";
1254  if (VR) {
1255  // See if we can get the BlockVarRegion.
1256  ProgramStateRef State = StoreSite->getState();
1257  SVal V = StoreSite->getSVal(S);
1258  if (const auto *BDR =
1259  dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1260  if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1261  if (auto KV = State->getSVal(OriginalR).getAs<KnownSVal>())
1262  BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1263  *KV, OriginalR, EnableNullFPSuppression));
1264  }
1265  }
1266  }
1267  }
1268  if (action)
1269  showBRDiagnostics(action, os, R, V, DS);
1270 
1271  } else if (StoreSite->getLocation().getAs<CallEnter>()) {
1272  if (const auto *VR = dyn_cast<VarRegion>(R))
1273  showBRParamDiagnostics(os, VR, V);
1274  }
1275 
1276  if (os.str().empty())
1277  showBRDefaultDiagnostics(os, R, V);
1278 
1279  // Construct a new PathDiagnosticPiece.
1280  ProgramPoint P = StoreSite->getLocation();
1281  PathDiagnosticLocation L;
1282  if (P.getAs<CallEnter>() && InitE)
1283  L = PathDiagnosticLocation(InitE, BRC.getSourceManager(),
1284  P.getLocationContext());
1285 
1286  if (!L.isValid() || !L.asLocation().isValid())
1287  L = PathDiagnosticLocation::create(P, BRC.getSourceManager());
1288 
1289  if (!L.isValid() || !L.asLocation().isValid())
1290  return nullptr;
1291 
1292  return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1293 }
1294 
1295 void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1296  static int tag = 0;
1297  ID.AddPointer(&tag);
1298  ID.AddBoolean(Assumption);
1299  ID.Add(Constraint);
1300 }
1301 
1302 /// Return the tag associated with this visitor. This tag will be used
1303 /// to make all PathDiagnosticPieces created by this visitor.
1304 const char *TrackConstraintBRVisitor::getTag() {
1305  return "TrackConstraintBRVisitor";
1306 }
1307 
1308 bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1309  if (IsZeroCheck)
1310  return N->getState()->isNull(Constraint).isUnderconstrained();
1311  return (bool)N->getState()->assume(Constraint, !Assumption);
1312 }
1313 
1314 std::shared_ptr<PathDiagnosticPiece>
1315 TrackConstraintBRVisitor::VisitNode(const ExplodedNode *N,
1316  BugReporterContext &BRC, BugReport &) {
1317  const ExplodedNode *PrevN = N->getFirstPred();
1318  if (IsSatisfied)
1319  return nullptr;
1320 
1321  // Start tracking after we see the first state in which the value is
1322  // constrained.
1323  if (!IsTrackingTurnedOn)
1324  if (!isUnderconstrained(N))
1325  IsTrackingTurnedOn = true;
1326  if (!IsTrackingTurnedOn)
1327  return nullptr;
1328 
1329  // Check if in the previous state it was feasible for this constraint
1330  // to *not* be true.
1331  if (isUnderconstrained(PrevN)) {
1332  IsSatisfied = true;
1333 
1334  // As a sanity check, make sure that the negation of the constraint
1335  // was infeasible in the current state. If it is feasible, we somehow
1336  // missed the transition point.
1337  assert(!isUnderconstrained(N));
1338 
1339  // We found the transition point for the constraint. We now need to
1340  // pretty-print the constraint. (work-in-progress)
1341  SmallString<64> sbuf;
1342  llvm::raw_svector_ostream os(sbuf);
1343 
1344  if (Constraint.getAs<Loc>()) {
1345  os << "Assuming pointer value is ";
1346  os << (Assumption ? "non-null" : "null");
1347  }
1348 
1349  if (os.str().empty())
1350  return nullptr;
1351 
1352  // Construct a new PathDiagnosticPiece.
1353  ProgramPoint P = N->getLocation();
1354  PathDiagnosticLocation L =
1355  PathDiagnosticLocation::create(P, BRC.getSourceManager());
1356  if (!L.isValid())
1357  return nullptr;
1358 
1359  auto X = std::make_shared<PathDiagnosticEventPiece>(L, os.str());
1360  X->setTag(getTag());
1361  return std::move(X);
1362  }
1363 
1364  return nullptr;
1365 }
1366 
1367 SuppressInlineDefensiveChecksVisitor::
1368 SuppressInlineDefensiveChecksVisitor(DefinedSVal Value, const ExplodedNode *N)
1369  : V(Value) {
1370  // Check if the visitor is disabled.
1371  AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
1372  if (!Options.ShouldSuppressInlinedDefensiveChecks)
1373  IsSatisfied = true;
1374 
1375  assert(N->getState()->isNull(V).isConstrainedTrue() &&
1376  "The visitor only tracks the cases where V is constrained to 0");
1377 }
1378 
1379 void SuppressInlineDefensiveChecksVisitor::Profile(
1380  llvm::FoldingSetNodeID &ID) const {
1381  static int id = 0;
1382  ID.AddPointer(&id);
1383  ID.Add(V);
1384 }
1385 
1386 const char *SuppressInlineDefensiveChecksVisitor::getTag() {
1387  return "IDCVisitor";
1388 }
1389 
1390 std::shared_ptr<PathDiagnosticPiece>
1391 SuppressInlineDefensiveChecksVisitor::VisitNode(const ExplodedNode *Succ,
1392  BugReporterContext &BRC,
1393  BugReport &BR) {
1394  const ExplodedNode *Pred = Succ->getFirstPred();
1395  if (IsSatisfied)
1396  return nullptr;
1397 
1398  // Start tracking after we see the first state in which the value is null.
1399  if (!IsTrackingTurnedOn)
1400  if (Succ->getState()->isNull(V).isConstrainedTrue())
1401  IsTrackingTurnedOn = true;
1402  if (!IsTrackingTurnedOn)
1403  return nullptr;
1404 
1405  // Check if in the previous state it was feasible for this value
1406  // to *not* be null.
1407  if (!Pred->getState()->isNull(V).isConstrainedTrue()) {
1408  IsSatisfied = true;
1409 
1410  assert(Succ->getState()->isNull(V).isConstrainedTrue());
1411 
1412  // Check if this is inlined defensive checks.
1413  const LocationContext *CurLC =Succ->getLocationContext();
1414  const LocationContext *ReportLC = BR.getErrorNode()->getLocationContext();
1415  if (CurLC != ReportLC && !CurLC->isParentOf(ReportLC)) {
1416  BR.markInvalid("Suppress IDC", CurLC);
1417  return nullptr;
1418  }
1419 
1420  // Treat defensive checks in function-like macros as if they were an inlined
1421  // defensive check. If the bug location is not in a macro and the
1422  // terminator for the current location is in a macro then suppress the
1423  // warning.
1424  auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1425 
1426  if (!BugPoint)
1427  return nullptr;
1428 
1429  ProgramPoint CurPoint = Succ->getLocation();
1430  const Stmt *CurTerminatorStmt = nullptr;
1431  if (auto BE = CurPoint.getAs<BlockEdge>()) {
1432  CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1433  } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1434  const Stmt *CurStmt = SP->getStmt();
1435  if (!CurStmt->getBeginLoc().isMacroID())
1436  return nullptr;
1437 
1438  CFGStmtMap *Map = CurLC->getAnalysisDeclContext()->getCFGStmtMap();
1439  CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminator();
1440  } else {
1441  return nullptr;
1442  }
1443 
1444  if (!CurTerminatorStmt)
1445  return nullptr;
1446 
1447  SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
1448  if (TerminatorLoc.isMacroID()) {
1449  SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
1450 
1451  // Suppress reports unless we are in that same macro.
1452  if (!BugLoc.isMacroID() ||
1453  getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1454  BR.markInvalid("Suppress Macro IDC", CurLC);
1455  }
1456  return nullptr;
1457  }
1458  }
1459  return nullptr;
1460 }
1461 
1462 static const MemRegion *getLocationRegionIfReference(const Expr *E,
1463  const ExplodedNode *N) {
1464  if (const auto *DR = dyn_cast<DeclRefExpr>(E)) {
1465  if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1466  if (!VD->getType()->isReferenceType())
1467  return nullptr;
1468  ProgramStateManager &StateMgr = N->getState()->getStateManager();
1469  MemRegionManager &MRMgr = StateMgr.getRegionManager();
1470  return MRMgr.getVarRegion(VD, N->getLocationContext());
1471  }
1472  }
1473 
1474  // FIXME: This does not handle other kinds of null references,
1475  // for example, references from FieldRegions:
1476  // struct Wrapper { int &ref; };
1477  // Wrapper w = { *(int *)0 };
1478  // w.ref = 1;
1479 
1480  return nullptr;
1481 }
1482 
1483 /// \return A subexpression of {@code Ex} which represents the
1484 /// expression-of-interest.
1485 static const Expr *peelOffOuterExpr(const Expr *Ex,
1486  const ExplodedNode *N) {
1487  Ex = Ex->IgnoreParenCasts();
1488  if (const auto *FE = dyn_cast<FullExpr>(Ex))
1489  return peelOffOuterExpr(FE->getSubExpr(), N);
1490  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
1491  return peelOffOuterExpr(OVE->getSourceExpr(), N);
1492  if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
1493  const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
1494  if (PropRef && PropRef->isMessagingGetter()) {
1495  const Expr *GetterMessageSend =
1496  POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
1497  assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
1498  return peelOffOuterExpr(GetterMessageSend, N);
1499  }
1500  }
1501 
1502  // Peel off the ternary operator.
1503  if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
1504  // Find a node where the branching occurred and find out which branch
1505  // we took (true/false) by looking at the ExplodedGraph.
1506  const ExplodedNode *NI = N;
1507  do {
1508  ProgramPoint ProgPoint = NI->getLocation();
1509  if (Optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
1510  const CFGBlock *srcBlk = BE->getSrc();
1511  if (const Stmt *term = srcBlk->getTerminator()) {
1512  if (term == CO) {
1513  bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
1514  if (TookTrueBranch)
1515  return peelOffOuterExpr(CO->getTrueExpr(), N);
1516  else
1517  return peelOffOuterExpr(CO->getFalseExpr(), N);
1518  }
1519  }
1520  }
1521  NI = NI->getFirstPred();
1522  } while (NI);
1523  }
1524 
1525  if (auto *BO = dyn_cast<BinaryOperator>(Ex))
1526  if (const Expr *SubEx = peelOffPointerArithmetic(BO))
1527  return peelOffOuterExpr(SubEx, N);
1528 
1529  if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
1530  if (UO->getOpcode() == UO_LNot)
1531  return peelOffOuterExpr(UO->getSubExpr(), N);
1532 
1533  // FIXME: There's a hack in our Store implementation that always computes
1534  // field offsets around null pointers as if they are always equal to 0.
1535  // The idea here is to report accesses to fields as null dereferences
1536  // even though the pointer value that's being dereferenced is actually
1537  // the offset of the field rather than exactly 0.
1538  // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
1539  // This code interacts heavily with this hack; otherwise the value
1540  // would not be null at all for most fields, so we'd be unable to track it.
1541  if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue())
1542  if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
1543  return peelOffOuterExpr(DerefEx, N);
1544  }
1545 
1546  return Ex;
1547 }
1548 
1549 /// Find the ExplodedNode where the lvalue (the value of 'Ex')
1550 /// was computed.
1551 static const ExplodedNode* findNodeForExpression(const ExplodedNode *N,
1552  const Expr *Inner) {
1553  while (N) {
1554  if (PathDiagnosticLocation::getStmt(N) == Inner)
1555  return N;
1556  N = N->getFirstPred();
1557  }
1558  return N;
1559 }
1560 
1561 bool bugreporter::trackExpressionValue(const ExplodedNode *InputNode,
1562  const Expr *E, BugReport &report,
1563  bool EnableNullFPSuppression) {
1564  if (!E || !InputNode)
1565  return false;
1566 
1567  const Expr *Inner = peelOffOuterExpr(E, InputNode);
1568  const ExplodedNode *LVNode = findNodeForExpression(InputNode, Inner);
1569  if (!LVNode)
1570  return false;
1571 
1572  ProgramStateRef LVState = LVNode->getState();
1573 
1574  // The message send could be nil due to the receiver being nil.
1575  // At this point in the path, the receiver should be live since we are at the
1576  // message send expr. If it is nil, start tracking it.
1577  if (const Expr *Receiver = NilReceiverBRVisitor::getNilReceiver(Inner, LVNode))
1578  trackExpressionValue(LVNode, Receiver, report, EnableNullFPSuppression);
1579 
1580  // See if the expression we're interested refers to a variable.
1581  // If so, we can track both its contents and constraints on its value.
1583  SVal LVal = LVNode->getSVal(Inner);
1584 
1585  const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
1586  bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
1587 
1588  // If this is a C++ reference to a null pointer, we are tracking the
1589  // pointer. In addition, we should find the store at which the reference
1590  // got initialized.
1591  if (RR && !LVIsNull)
1592  if (auto KV = LVal.getAs<KnownSVal>())
1593  report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1594  *KV, RR, EnableNullFPSuppression));
1595 
1596  // In case of C++ references, we want to differentiate between a null
1597  // reference and reference to null pointer.
1598  // If the LVal is null, check if we are dealing with null reference.
1599  // For those, we want to track the location of the reference.
1600  const MemRegion *R = (RR && LVIsNull) ? RR :
1601  LVNode->getSVal(Inner).getAsRegion();
1602 
1603  if (R) {
1604 
1605  // Mark both the variable region and its contents as interesting.
1606  SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
1607  report.addVisitor(
1608  llvm::make_unique<NoStoreFuncVisitor>(cast<SubRegion>(R)));
1609 
1610  MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
1611  LVNode, R, EnableNullFPSuppression, report, V);
1612 
1613  report.markInteresting(V);
1614  report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(R));
1615 
1616  // If the contents are symbolic, find out when they became null.
1617  if (V.getAsLocSymbol(/*IncludeBaseRegions*/ true))
1618  report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1619  V.castAs<DefinedSVal>(), false));
1620 
1621  // Add visitor, which will suppress inline defensive checks.
1622  if (auto DV = V.getAs<DefinedSVal>())
1623  if (!DV->isZeroConstant() && LVState->isNull(*DV).isConstrainedTrue() &&
1624  EnableNullFPSuppression)
1625  report.addVisitor(
1626  llvm::make_unique<SuppressInlineDefensiveChecksVisitor>(*DV,
1627  LVNode));
1628 
1629  if (auto KV = V.getAs<KnownSVal>())
1630  report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1631  *KV, R, EnableNullFPSuppression));
1632  return true;
1633  }
1634  }
1635 
1636  // If the expression is not an "lvalue expression", we can still
1637  // track the constraints on its contents.
1638  SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getLocationContext());
1639 
1640  ReturnVisitor::addVisitorIfNecessary(
1641  LVNode, Inner, report, EnableNullFPSuppression);
1642 
1643  // Is it a symbolic value?
1644  if (auto L = V.getAs<loc::MemRegionVal>()) {
1645  report.addVisitor(llvm::make_unique<UndefOrNullArgVisitor>(L->getRegion()));
1646 
1647  // FIXME: this is a hack for fixing a later crash when attempting to
1648  // dereference a void* pointer.
1649  // We should not try to dereference pointers at all when we don't care
1650  // what is written inside the pointer.
1651  bool CanDereference = true;
1652  if (const auto *SR = dyn_cast<SymbolicRegion>(L->getRegion()))
1653  if (SR->getSymbol()->getType()->getPointeeType()->isVoidType())
1654  CanDereference = false;
1655 
1656  // At this point we are dealing with the region's LValue.
1657  // However, if the rvalue is a symbolic region, we should track it as well.
1658  // Try to use the correct type when looking up the value.
1659  SVal RVal;
1661  RVal = LVState->getRawSVal(L.getValue(), Inner->getType());
1662  } else if (CanDereference) {
1663  RVal = LVState->getSVal(L->getRegion());
1664  }
1665 
1666  if (CanDereference)
1667  if (auto KV = RVal.getAs<KnownSVal>())
1668  report.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1669  *KV, L->getRegion(), EnableNullFPSuppression));
1670 
1671  const MemRegion *RegionRVal = RVal.getAsRegion();
1672  if (RegionRVal && isa<SymbolicRegion>(RegionRVal)) {
1673  report.markInteresting(RegionRVal);
1674  report.addVisitor(llvm::make_unique<TrackConstraintBRVisitor>(
1675  loc::MemRegionVal(RegionRVal), /*assumption=*/false));
1676  }
1677  }
1678  return true;
1679 }
1680 
1681 const Expr *NilReceiverBRVisitor::getNilReceiver(const Stmt *S,
1682  const ExplodedNode *N) {
1683  const auto *ME = dyn_cast<ObjCMessageExpr>(S);
1684  if (!ME)
1685  return nullptr;
1686  if (const Expr *Receiver = ME->getInstanceReceiver()) {
1687  ProgramStateRef state = N->getState();
1688  SVal V = N->getSVal(Receiver);
1689  if (state->isNull(V).isConstrainedTrue())
1690  return Receiver;
1691  }
1692  return nullptr;
1693 }
1694 
1695 std::shared_ptr<PathDiagnosticPiece>
1696 NilReceiverBRVisitor::VisitNode(const ExplodedNode *N,
1697  BugReporterContext &BRC, BugReport &BR) {
1698  Optional<PreStmt> P = N->getLocationAs<PreStmt>();
1699  if (!P)
1700  return nullptr;
1701 
1702  const Stmt *S = P->getStmt();
1703  const Expr *Receiver = getNilReceiver(S, N);
1704  if (!Receiver)
1705  return nullptr;
1706 
1708  llvm::raw_svector_ostream OS(Buf);
1709 
1710  if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
1711  OS << "'";
1712  ME->getSelector().print(OS);
1713  OS << "' not called";
1714  }
1715  else {
1716  OS << "No method is called";
1717  }
1718  OS << " because the receiver is nil";
1719 
1720  // The receiver was nil, and hence the method was skipped.
1721  // Register a BugReporterVisitor to issue a message telling us how
1722  // the receiver was null.
1723  bugreporter::trackExpressionValue(N, Receiver, BR,
1724  /*EnableNullFPSuppression*/ false);
1725  // Issue a message saying that the method was skipped.
1726  PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
1727  N->getLocationContext());
1728  return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
1729 }
1730 
1731 // Registers every VarDecl inside a Stmt with a last store visitor.
1732 void FindLastStoreBRVisitor::registerStatementVarDecls(BugReport &BR,
1733  const Stmt *S,
1734  bool EnableNullFPSuppression) {
1735  const ExplodedNode *N = BR.getErrorNode();
1736  std::deque<const Stmt *> WorkList;
1737  WorkList.push_back(S);
1738 
1739  while (!WorkList.empty()) {
1740  const Stmt *Head = WorkList.front();
1741  WorkList.pop_front();
1742 
1743  ProgramStateManager &StateMgr = N->getState()->getStateManager();
1744 
1745  if (const auto *DR = dyn_cast<DeclRefExpr>(Head)) {
1746  if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1747  const VarRegion *R =
1748  StateMgr.getRegionManager().getVarRegion(VD, N->getLocationContext());
1749 
1750  // What did we load?
1751  SVal V = N->getSVal(S);
1752 
1753  if (V.getAs<loc::ConcreteInt>() || V.getAs<nonloc::ConcreteInt>()) {
1754  // Register a new visitor with the BugReport.
1755  BR.addVisitor(llvm::make_unique<FindLastStoreBRVisitor>(
1756  V.castAs<KnownSVal>(), R, EnableNullFPSuppression));
1757  }
1758  }
1759  }
1760 
1761  for (const Stmt *SubStmt : Head->children())
1762  WorkList.push_back(SubStmt);
1763  }
1764 }
1765 
1766 //===----------------------------------------------------------------------===//
1767 // Visitor that tries to report interesting diagnostics from conditions.
1768 //===----------------------------------------------------------------------===//
1769 
1770 /// Return the tag associated with this visitor. This tag will be used
1771 /// to make all PathDiagnosticPieces created by this visitor.
1772 const char *ConditionBRVisitor::getTag() {
1773  return "ConditionBRVisitor";
1774 }
1775 
1776 std::shared_ptr<PathDiagnosticPiece>
1777 ConditionBRVisitor::VisitNode(const ExplodedNode *N,
1778  BugReporterContext &BRC, BugReport &BR) {
1779  auto piece = VisitNodeImpl(N, BRC, BR);
1780  if (piece) {
1781  piece->setTag(getTag());
1782  if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
1783  ev->setPrunable(true, /* override */ false);
1784  }
1785  return piece;
1786 }
1787 
1788 std::shared_ptr<PathDiagnosticPiece>
1789 ConditionBRVisitor::VisitNodeImpl(const ExplodedNode *N,
1790  BugReporterContext &BRC, BugReport &BR) {
1791  ProgramPoint progPoint = N->getLocation();
1792  ProgramStateRef CurrentState = N->getState();
1793  ProgramStateRef PrevState = N->getFirstPred()->getState();
1794 
1795  // Compare the GDMs of the state, because that is where constraints
1796  // are managed. Note that ensure that we only look at nodes that
1797  // were generated by the analyzer engine proper, not checkers.
1798  if (CurrentState->getGDM().getRoot() ==
1799  PrevState->getGDM().getRoot())
1800  return nullptr;
1801 
1802  // If an assumption was made on a branch, it should be caught
1803  // here by looking at the state transition.
1804  if (Optional<BlockEdge> BE = progPoint.getAs<BlockEdge>()) {
1805  const CFGBlock *srcBlk = BE->getSrc();
1806  if (const Stmt *term = srcBlk->getTerminator())
1807  return VisitTerminator(term, N, srcBlk, BE->getDst(), BR, BRC);
1808  return nullptr;
1809  }
1810 
1811  if (Optional<PostStmt> PS = progPoint.getAs<PostStmt>()) {
1812  const std::pair<const ProgramPointTag *, const ProgramPointTag *> &tags =
1814 
1815  const ProgramPointTag *tag = PS->getTag();
1816  if (tag == tags.first)
1817  return VisitTrueTest(cast<Expr>(PS->getStmt()), true,
1818  BRC, BR, N);
1819  if (tag == tags.second)
1820  return VisitTrueTest(cast<Expr>(PS->getStmt()), false,
1821  BRC, BR, N);
1822 
1823  return nullptr;
1824  }
1825 
1826  return nullptr;
1827 }
1828 
1829 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitTerminator(
1830  const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
1831  const CFGBlock *dstBlk, BugReport &R, BugReporterContext &BRC) {
1832  const Expr *Cond = nullptr;
1833 
1834  // In the code below, Term is a CFG terminator and Cond is a branch condition
1835  // expression upon which the decision is made on this terminator.
1836  //
1837  // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
1838  // and "x == 0" is the respective condition.
1839  //
1840  // Another example: in "if (x && y)", we've got two terminators and two
1841  // conditions due to short-circuit nature of operator "&&":
1842  // 1. The "if (x && y)" statement is a terminator,
1843  // and "y" is the respective condition.
1844  // 2. Also "x && ..." is another terminator,
1845  // and "x" is its condition.
1846 
1847  switch (Term->getStmtClass()) {
1848  // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
1849  // more tricky because there are more than two branches to account for.
1850  default:
1851  return nullptr;
1852  case Stmt::IfStmtClass:
1853  Cond = cast<IfStmt>(Term)->getCond();
1854  break;
1855  case Stmt::ConditionalOperatorClass:
1856  Cond = cast<ConditionalOperator>(Term)->getCond();
1857  break;
1858  case Stmt::BinaryOperatorClass:
1859  // When we encounter a logical operator (&& or ||) as a CFG terminator,
1860  // then the condition is actually its LHS; otherwise, we'd encounter
1861  // the parent, such as if-statement, as a terminator.
1862  const auto *BO = cast<BinaryOperator>(Term);
1863  assert(BO->isLogicalOp() &&
1864  "CFG terminator is not a short-circuit operator!");
1865  Cond = BO->getLHS();
1866  break;
1867  }
1868 
1869  // However, when we encounter a logical operator as a branch condition,
1870  // then the condition is actually its RHS, because LHS would be
1871  // the condition for the logical operator terminator.
1872  while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
1873  if (!InnerBO->isLogicalOp())
1874  break;
1875  Cond = InnerBO->getRHS()->IgnoreParens();
1876  }
1877 
1878  assert(Cond);
1879  assert(srcBlk->succ_size() == 2);
1880  const bool tookTrue = *(srcBlk->succ_begin()) == dstBlk;
1881  return VisitTrueTest(Cond, tookTrue, BRC, R, N);
1882 }
1883 
1884 std::shared_ptr<PathDiagnosticPiece>
1885 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, bool tookTrue,
1886  BugReporterContext &BRC, BugReport &R,
1887  const ExplodedNode *N) {
1888  // These will be modified in code below, but we need to preserve the original
1889  // values in case we want to throw the generic message.
1890  const Expr *CondTmp = Cond;
1891  bool tookTrueTmp = tookTrue;
1892 
1893  while (true) {
1894  CondTmp = CondTmp->IgnoreParenCasts();
1895  switch (CondTmp->getStmtClass()) {
1896  default:
1897  break;
1898  case Stmt::BinaryOperatorClass:
1899  if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
1900  tookTrueTmp, BRC, R, N))
1901  return P;
1902  break;
1903  case Stmt::DeclRefExprClass:
1904  if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
1905  tookTrueTmp, BRC, R, N))
1906  return P;
1907  break;
1908  case Stmt::UnaryOperatorClass: {
1909  const auto *UO = cast<UnaryOperator>(CondTmp);
1910  if (UO->getOpcode() == UO_LNot) {
1911  tookTrueTmp = !tookTrueTmp;
1912  CondTmp = UO->getSubExpr();
1913  continue;
1914  }
1915  break;
1916  }
1917  }
1918  break;
1919  }
1920 
1921  // Condition too complex to explain? Just say something so that the user
1922  // knew we've made some path decision at this point.
1923  const LocationContext *LCtx = N->getLocationContext();
1924  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
1925  if (!Loc.isValid() || !Loc.asLocation().isValid())
1926  return nullptr;
1927 
1928  return std::make_shared<PathDiagnosticEventPiece>(
1929  Loc, tookTrue ? GenericTrueMessage : GenericFalseMessage);
1930 }
1931 
1932 bool ConditionBRVisitor::patternMatch(const Expr *Ex,
1933  const Expr *ParentEx,
1934  raw_ostream &Out,
1935  BugReporterContext &BRC,
1936  BugReport &report,
1937  const ExplodedNode *N,
1938  Optional<bool> &prunable) {
1939  const Expr *OriginalExpr = Ex;
1940  Ex = Ex->IgnoreParenCasts();
1941 
1942  // Use heuristics to determine if Ex is a macro expending to a literal and
1943  // if so, use the macro's name.
1944  SourceLocation LocStart = Ex->getBeginLoc();
1945  SourceLocation LocEnd = Ex->getEndLoc();
1946  if (LocStart.isMacroID() && LocEnd.isMacroID() &&
1947  (isa<GNUNullExpr>(Ex) ||
1948  isa<ObjCBoolLiteralExpr>(Ex) ||
1949  isa<CXXBoolLiteralExpr>(Ex) ||
1950  isa<IntegerLiteral>(Ex) ||
1951  isa<FloatingLiteral>(Ex))) {
1952  StringRef StartName = Lexer::getImmediateMacroNameForDiagnostics(LocStart,
1953  BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1954  StringRef EndName = Lexer::getImmediateMacroNameForDiagnostics(LocEnd,
1955  BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1956  bool beginAndEndAreTheSameMacro = StartName.equals(EndName);
1957 
1958  bool partOfParentMacro = false;
1959  if (ParentEx->getBeginLoc().isMacroID()) {
1961  ParentEx->getBeginLoc(), BRC.getSourceManager(),
1962  BRC.getASTContext().getLangOpts());
1963  partOfParentMacro = PName.equals(StartName);
1964  }
1965 
1966  if (beginAndEndAreTheSameMacro && !partOfParentMacro ) {
1967  // Get the location of the macro name as written by the caller.
1968  SourceLocation Loc = LocStart;
1969  while (LocStart.isMacroID()) {
1970  Loc = LocStart;
1971  LocStart = BRC.getSourceManager().getImmediateMacroCallerLoc(LocStart);
1972  }
1973  StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
1974  Loc, BRC.getSourceManager(), BRC.getASTContext().getLangOpts());
1975 
1976  // Return the macro name.
1977  Out << MacroName;
1978  return false;
1979  }
1980  }
1981 
1982  if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
1983  const bool quotes = isa<VarDecl>(DR->getDecl());
1984  if (quotes) {
1985  Out << '\'';
1986  const LocationContext *LCtx = N->getLocationContext();
1987  const ProgramState *state = N->getState().get();
1988  if (const MemRegion *R = state->getLValue(cast<VarDecl>(DR->getDecl()),
1989  LCtx).getAsRegion()) {
1990  if (report.isInteresting(R))
1991  prunable = false;
1992  else {
1993  const ProgramState *state = N->getState().get();
1994  SVal V = state->getSVal(R);
1995  if (report.isInteresting(V))
1996  prunable = false;
1997  }
1998  }
1999  }
2000  Out << DR->getDecl()->getDeclName().getAsString();
2001  if (quotes)
2002  Out << '\'';
2003  return quotes;
2004  }
2005 
2006  if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
2007  QualType OriginalTy = OriginalExpr->getType();
2008  if (OriginalTy->isPointerType()) {
2009  if (IL->getValue() == 0) {
2010  Out << "null";
2011  return false;
2012  }
2013  }
2014  else if (OriginalTy->isObjCObjectPointerType()) {
2015  if (IL->getValue() == 0) {
2016  Out << "nil";
2017  return false;
2018  }
2019  }
2020 
2021  Out << IL->getValue();
2022  return false;
2023  }
2024 
2025  return false;
2026 }
2027 
2028 std::shared_ptr<PathDiagnosticPiece>
2029 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const BinaryOperator *BExpr,
2030  const bool tookTrue, BugReporterContext &BRC,
2031  BugReport &R, const ExplodedNode *N) {
2032  bool shouldInvert = false;
2033  Optional<bool> shouldPrune;
2034 
2035  SmallString<128> LhsString, RhsString;
2036  {
2037  llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
2038  const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS,
2039  BRC, R, N, shouldPrune);
2040  const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS,
2041  BRC, R, N, shouldPrune);
2042 
2043  shouldInvert = !isVarLHS && isVarRHS;
2044  }
2045 
2046  BinaryOperator::Opcode Op = BExpr->getOpcode();
2047 
2049  // For assignment operators, all that we care about is that the LHS
2050  // evaluates to "true" or "false".
2051  return VisitConditionVariable(LhsString, BExpr->getLHS(), tookTrue,
2052  BRC, R, N);
2053  }
2054 
2055  // For non-assignment operations, we require that we can understand
2056  // both the LHS and RHS.
2057  if (LhsString.empty() || RhsString.empty() ||
2058  !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
2059  return nullptr;
2060 
2061  // Should we invert the strings if the LHS is not a variable name?
2062  SmallString<256> buf;
2063  llvm::raw_svector_ostream Out(buf);
2064  Out << "Assuming " << (shouldInvert ? RhsString : LhsString) << " is ";
2065 
2066  // Do we need to invert the opcode?
2067  if (shouldInvert)
2068  switch (Op) {
2069  default: break;
2070  case BO_LT: Op = BO_GT; break;
2071  case BO_GT: Op = BO_LT; break;
2072  case BO_LE: Op = BO_GE; break;
2073  case BO_GE: Op = BO_LE; break;
2074  }
2075 
2076  if (!tookTrue)
2077  switch (Op) {
2078  case BO_EQ: Op = BO_NE; break;
2079  case BO_NE: Op = BO_EQ; break;
2080  case BO_LT: Op = BO_GE; break;
2081  case BO_GT: Op = BO_LE; break;
2082  case BO_LE: Op = BO_GT; break;
2083  case BO_GE: Op = BO_LT; break;
2084  default:
2085  return nullptr;
2086  }
2087 
2088  switch (Op) {
2089  case BO_EQ:
2090  Out << "equal to ";
2091  break;
2092  case BO_NE:
2093  Out << "not equal to ";
2094  break;
2095  default:
2096  Out << BinaryOperator::getOpcodeStr(Op) << ' ';
2097  break;
2098  }
2099 
2100  Out << (shouldInvert ? LhsString : RhsString);
2101  const LocationContext *LCtx = N->getLocationContext();
2102  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2103  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2104  if (shouldPrune.hasValue())
2105  event->setPrunable(shouldPrune.getValue());
2106  return event;
2107 }
2108 
2109 std::shared_ptr<PathDiagnosticPiece> ConditionBRVisitor::VisitConditionVariable(
2110  StringRef LhsString, const Expr *CondVarExpr, const bool tookTrue,
2111  BugReporterContext &BRC, BugReport &report, const ExplodedNode *N) {
2112  // FIXME: If there's already a constraint tracker for this variable,
2113  // we shouldn't emit anything here (c.f. the double note in
2114  // test/Analysis/inlining/path-notes.c)
2115  SmallString<256> buf;
2116  llvm::raw_svector_ostream Out(buf);
2117  Out << "Assuming " << LhsString << " is ";
2118 
2119  QualType Ty = CondVarExpr->getType();
2120 
2121  if (Ty->isPointerType())
2122  Out << (tookTrue ? "not null" : "null");
2123  else if (Ty->isObjCObjectPointerType())
2124  Out << (tookTrue ? "not nil" : "nil");
2125  else if (Ty->isBooleanType())
2126  Out << (tookTrue ? "true" : "false");
2127  else if (Ty->isIntegralOrEnumerationType())
2128  Out << (tookTrue ? "non-zero" : "zero");
2129  else
2130  return nullptr;
2131 
2132  const LocationContext *LCtx = N->getLocationContext();
2133  PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(), LCtx);
2134  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2135 
2136  if (const auto *DR = dyn_cast<DeclRefExpr>(CondVarExpr)) {
2137  if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2138  const ProgramState *state = N->getState().get();
2139  if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2140  if (report.isInteresting(R))
2141  event->setPrunable(false);
2142  }
2143  }
2144  }
2145 
2146  return event;
2147 }
2148 
2149 std::shared_ptr<PathDiagnosticPiece>
2150 ConditionBRVisitor::VisitTrueTest(const Expr *Cond, const DeclRefExpr *DR,
2151  const bool tookTrue, BugReporterContext &BRC,
2152  BugReport &report, const ExplodedNode *N) {
2153  const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
2154  if (!VD)
2155  return nullptr;
2156 
2157  SmallString<256> Buf;
2158  llvm::raw_svector_ostream Out(Buf);
2159 
2160  Out << "Assuming '" << VD->getDeclName() << "' is ";
2161 
2162  QualType VDTy = VD->getType();
2163 
2164  if (VDTy->isPointerType())
2165  Out << (tookTrue ? "non-null" : "null");
2166  else if (VDTy->isObjCObjectPointerType())
2167  Out << (tookTrue ? "non-nil" : "nil");
2168  else if (VDTy->isScalarType())
2169  Out << (tookTrue ? "not equal to 0" : "0");
2170  else
2171  return nullptr;
2172 
2173  const LocationContext *LCtx = N->getLocationContext();
2174  PathDiagnosticLocation Loc(Cond, BRC.getSourceManager(), LCtx);
2175  auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
2176 
2177  const ProgramState *state = N->getState().get();
2178  if (const MemRegion *R = state->getLValue(VD, LCtx).getAsRegion()) {
2179  if (report.isInteresting(R))
2180  event->setPrunable(false);
2181  else {
2182  SVal V = state->getSVal(R);
2183  if (report.isInteresting(V))
2184  event->setPrunable(false);
2185  }
2186  }
2187  return std::move(event);
2188 }
2189 
2190 const char *const ConditionBRVisitor::GenericTrueMessage =
2191  "Assuming the condition is true";
2192 const char *const ConditionBRVisitor::GenericFalseMessage =
2193  "Assuming the condition is false";
2194 
2195 bool ConditionBRVisitor::isPieceMessageGeneric(
2196  const PathDiagnosticPiece *Piece) {
2197  return Piece->getString() == GenericTrueMessage ||
2198  Piece->getString() == GenericFalseMessage;
2199 }
2200 
2201 void LikelyFalsePositiveSuppressionBRVisitor::finalizeVisitor(
2202  BugReporterContext &BRC, const ExplodedNode *N, BugReport &BR) {
2203  // Here we suppress false positives coming from system headers. This list is
2204  // based on known issues.
2205  AnalyzerOptions &Options = BRC.getAnalyzerOptions();
2206  const Decl *D = N->getLocationContext()->getDecl();
2207 
2209  // Skip reports within the 'std' namespace. Although these can sometimes be
2210  // the user's fault, we currently don't report them very well, and
2211  // Note that this will not help for any other data structure libraries, like
2212  // TR1, Boost, or llvm/ADT.
2213  if (Options.ShouldSuppressFromCXXStandardLibrary) {
2214  BR.markInvalid(getTag(), nullptr);
2215  return;
2216  } else {
2217  // If the complete 'std' suppression is not enabled, suppress reports
2218  // from the 'std' namespace that are known to produce false positives.
2219 
2220  // The analyzer issues a false use-after-free when std::list::pop_front
2221  // or std::list::pop_back are called multiple times because we cannot
2222  // reason about the internal invariants of the data structure.
2223  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2224  const CXXRecordDecl *CD = MD->getParent();
2225  if (CD->getName() == "list") {
2226  BR.markInvalid(getTag(), nullptr);
2227  return;
2228  }
2229  }
2230 
2231  // The analyzer issues a false positive when the constructor of
2232  // std::__independent_bits_engine from algorithms is used.
2233  if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
2234  const CXXRecordDecl *CD = MD->getParent();
2235  if (CD->getName() == "__independent_bits_engine") {
2236  BR.markInvalid(getTag(), nullptr);
2237  return;
2238  }
2239  }
2240 
2241  for (const LocationContext *LCtx = N->getLocationContext(); LCtx;
2242  LCtx = LCtx->getParent()) {
2243  const auto *MD = dyn_cast<CXXMethodDecl>(LCtx->getDecl());
2244  if (!MD)
2245  continue;
2246 
2247  const CXXRecordDecl *CD = MD->getParent();
2248  // The analyzer issues a false positive on
2249  // std::basic_string<uint8_t> v; v.push_back(1);
2250  // and
2251  // std::u16string s; s += u'a';
2252  // because we cannot reason about the internal invariants of the
2253  // data structure.
2254  if (CD->getName() == "basic_string") {
2255  BR.markInvalid(getTag(), nullptr);
2256  return;
2257  }
2258 
2259  // The analyzer issues a false positive on
2260  // std::shared_ptr<int> p(new int(1)); p = nullptr;
2261  // because it does not reason properly about temporary destructors.
2262  if (CD->getName() == "shared_ptr") {
2263  BR.markInvalid(getTag(), nullptr);
2264  return;
2265  }
2266  }
2267  }
2268  }
2269 
2270  // Skip reports within the sys/queue.h macros as we do not have the ability to
2271  // reason about data structure shapes.
2272  SourceManager &SM = BRC.getSourceManager();
2273  FullSourceLoc Loc = BR.getLocation(SM).asLocation();
2274  while (Loc.isMacroID()) {
2275  Loc = Loc.getSpellingLoc();
2276  if (SM.getFilename(Loc).endswith("sys/queue.h")) {
2277  BR.markInvalid(getTag(), nullptr);
2278  return;
2279  }
2280  }
2281 }
2282 
2283 std::shared_ptr<PathDiagnosticPiece>
2284 UndefOrNullArgVisitor::VisitNode(const ExplodedNode *N,
2285  BugReporterContext &BRC, BugReport &BR) {
2286  ProgramStateRef State = N->getState();
2287  ProgramPoint ProgLoc = N->getLocation();
2288 
2289  // We are only interested in visiting CallEnter nodes.
2290  Optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
2291  if (!CEnter)
2292  return nullptr;
2293 
2294  // Check if one of the arguments is the region the visitor is tracking.
2295  CallEventManager &CEMgr = BRC.getStateManager().getCallEventManager();
2296  CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeContext(), State);
2297  unsigned Idx = 0;
2298  ArrayRef<ParmVarDecl *> parms = Call->parameters();
2299 
2300  for (const auto ParamDecl : parms) {
2301  const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
2302  ++Idx;
2303 
2304  // Are we tracking the argument or its subregion?
2305  if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
2306  continue;
2307 
2308  // Check the function parameter type.
2309  assert(ParamDecl && "Formal parameter has no decl?");
2310  QualType T = ParamDecl->getType();
2311 
2312  if (!(T->isAnyPointerType() || T->isReferenceType())) {
2313  // Function can only change the value passed in by address.
2314  continue;
2315  }
2316 
2317  // If it is a const pointer value, the function does not intend to
2318  // change the value.
2319  if (T->getPointeeType().isConstQualified())
2320  continue;
2321 
2322  // Mark the call site (LocationContext) as interesting if the value of the
2323  // argument is undefined or '0'/'NULL'.
2324  SVal BoundVal = State->getSVal(R);
2325  if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
2326  BR.markInteresting(CEnter->getCalleeContext());
2327  return nullptr;
2328  }
2329  }
2330  return nullptr;
2331 }
2332 
2333 std::shared_ptr<PathDiagnosticPiece>
2334 CXXSelfAssignmentBRVisitor::VisitNode(const ExplodedNode *Succ,
2335  BugReporterContext &BRC, BugReport &) {
2336  if (Satisfied)
2337  return nullptr;
2338 
2339  const auto Edge = Succ->getLocation().getAs<BlockEdge>();
2340  if (!Edge.hasValue())
2341  return nullptr;
2342 
2343  auto Tag = Edge->getTag();
2344  if (!Tag)
2345  return nullptr;
2346 
2347  if (Tag->getTagDescription() != "cplusplus.SelfAssignment")
2348  return nullptr;
2349 
2350  Satisfied = true;
2351 
2352  const auto *Met =
2353  dyn_cast<CXXMethodDecl>(Succ->getCodeDecl().getAsFunction());
2354  assert(Met && "Not a C++ method.");
2355  assert((Met->isCopyAssignmentOperator() || Met->isMoveAssignmentOperator()) &&
2356  "Not a copy/move assignment operator.");
2357 
2358  const auto *LCtx = Edge->getLocationContext();
2359 
2360  const auto &State = Succ->getState();
2361  auto &SVB = State->getStateManager().getSValBuilder();
2362 
2363  const auto Param =
2364  State->getSVal(State->getRegion(Met->getParamDecl(0), LCtx));
2365  const auto This =
2366  State->getSVal(SVB.getCXXThis(Met, LCtx->getStackFrame()));
2367 
2368  auto L = PathDiagnosticLocation::create(Met, BRC.getSourceManager());
2369 
2370  if (!L.isValid() || !L.asLocation().isValid())
2371  return nullptr;
2372 
2373  SmallString<256> Buf;
2374  llvm::raw_svector_ostream Out(Buf);
2375 
2376  Out << "Assuming " << Met->getParamDecl(0)->getName() <<
2377  ((Param == This) ? " == " : " != ") << "*this";
2378 
2379  auto Piece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
2380  Piece->addRange(Met->getSourceRange());
2381 
2382  return std::move(Piece);
2383 }
2384 
2385 std::shared_ptr<PathDiagnosticPiece>
2386 TaintBugVisitor::VisitNode(const ExplodedNode *N,
2387  BugReporterContext &BRC, BugReport &) {
2388 
2389  // Find the ExplodedNode where the taint was first introduced
2390  if (!N->getState()->isTainted(V) || N->getFirstPred()->getState()->isTainted(V))
2391  return nullptr;
2392 
2393  const Stmt *S = PathDiagnosticLocation::getStmt(N);
2394  if (!S)
2395  return nullptr;
2396 
2397  const LocationContext *NCtx = N->getLocationContext();
2398  PathDiagnosticLocation L =
2399  PathDiagnosticLocation::createBegin(S, BRC.getSourceManager(), NCtx);
2400  if (!L.isValid() || !L.asLocation().isValid())
2401  return nullptr;
2402 
2403  return std::make_shared<PathDiagnosticEventPiece>(L, "Taint originated here");
2404 }
2405 
2406 FalsePositiveRefutationBRVisitor::FalsePositiveRefutationBRVisitor()
2407  : Constraints(ConstraintRangeTy::Factory().getEmptyMap()) {}
2408 
2409 void FalsePositiveRefutationBRVisitor::finalizeVisitor(
2410  BugReporterContext &BRC, const ExplodedNode *EndPathNode, BugReport &BR) {
2411  // Collect new constraints
2412  VisitNode(EndPathNode, BRC, BR);
2413 
2414  // Create a refutation manager
2415  SMTSolverRef RefutationSolver = CreateZ3Solver();
2416  ASTContext &Ctx = BRC.getASTContext();
2417 
2418  // Add constraints to the solver
2419  for (const auto &I : Constraints) {
2420  const SymbolRef Sym = I.first;
2421  auto RangeIt = I.second.begin();
2422 
2423  SMTExprRef Constraints = SMTConv::getRangeExpr(
2424  RefutationSolver, Ctx, Sym, RangeIt->From(), RangeIt->To(),
2425  /*InRange=*/true);
2426  while ((++RangeIt) != I.second.end()) {
2427  Constraints = RefutationSolver->mkOr(
2428  Constraints, SMTConv::getRangeExpr(RefutationSolver, Ctx, Sym,
2429  RangeIt->From(), RangeIt->To(),
2430  /*InRange=*/true));
2431  }
2432 
2433  RefutationSolver->addConstraint(Constraints);
2434  }
2435 
2436  // And check for satisfiability
2437  Optional<bool> isSat = RefutationSolver->check();
2438  if (!isSat.hasValue())
2439  return;
2440 
2441  if (!isSat.getValue())
2442  BR.markInvalid("Infeasible constraints", EndPathNode->getLocationContext());
2443 }
2444 
2445 std::shared_ptr<PathDiagnosticPiece>
2446 FalsePositiveRefutationBRVisitor::VisitNode(const ExplodedNode *N,
2447  BugReporterContext &,
2448  BugReport &) {
2449  // Collect new constraints
2450  const ConstraintRangeTy &NewCs = N->getState()->get<ConstraintRange>();
2451  ConstraintRangeTy::Factory &CF =
2452  N->getState()->get_context<ConstraintRange>();
2453 
2454  // Add constraints if we don't have them yet
2455  for (auto const &C : NewCs) {
2456  const SymbolRef &Sym = C.first;
2457  if (!Constraints.contains(Sym)) {
2458  Constraints = CF.add(Constraints, Sym, C.second);
2459  }
2460  }
2461 
2462  return nullptr;
2463 }
2464 
2465 void FalsePositiveRefutationBRVisitor::Profile(
2466  llvm::FoldingSetNodeID &ID) const {
2467  static int Tag = 0;
2468  ID.AddPointer(&Tag);
2469 }
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:577
Indicates that the tracked object is a CF object.
Defines the clang::ASTContext interface.
This is a discriminated union of FileInfo and ExpansionInfo.
A (possibly-)qualified type.
Definition: Type.h:638
static StringRef getMacroName(SourceLocation Loc, BugReporterContext &BRC)
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
static SMTExprRef getRangeExpr(SMTSolverRef &Solver, ASTContext &Ctx, SymbolRef Sym, const llvm::APSInt &From, const llvm::APSInt &To, bool InRange)
Definition: SMTConv.h:491
succ_iterator succ_begin()
Definition: CFG.h:751
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:979
const SymExpr * SymbolRef
Stmt - This represents one statement.
Definition: Stmt.h:66
internal::Matcher< Stmt > StatementMatcher
Definition: ASTMatchers.h:146
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, internal::Matcher< Decl >, void(internal::HasDeclarationSupportedTypes)> hasDeclaration(const internal::Matcher< Decl > &InnerMatcher)
Matches a node if the declaration associated with that node matches the given matcher.
Definition: ASTMatchers.h:2865
C Language Family Type Representation.
Defines the SourceManager interface.
static bool isPointerToConst(const QualType &QT)
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
Represents a point when we begin processing an inlined call.
Definition: ProgramPoint.h:632
Manages the lifetime of CallEvent objects.
Definition: CallEvent.h:1087
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
Opcode getOpcode() const
Definition: Expr.h:3329
StringRef P
const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher > hasDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher. ...
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded...
llvm::ImmutableMap< SymbolRef, RangeSet > ConstraintRangeTy
unsigned succ_size() const
Definition: CFG.h:769
Represents a variable declaration or definition.
Definition: Decl.h:813
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6755
const internal::VariadicDynCastAllOfMatcher< Stmt, BinaryOperator > binaryOperator
Matches binary operator expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, ObjCIvarRefExpr > objcIvarRefExpr
Matches a reference to an ObjCIvar.
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
Represents a parameter to a function.
Definition: Decl.h:1550
Defines the clang::Expr interface and subclasses for C++ expressions.
bool isParentOf(const LocationContext *LC) const
Represents a struct/union/class.
Definition: Decl.h:3593
SourceLocation getBegin() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
LineState State
field_range fields() const
Definition: Decl.h:3784
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
Represents a member of a struct/union/class.
Definition: Decl.h:2579
Represents a program point after a store evaluation.
Definition: ProgramPoint.h:433
bool isReferenceType() const
Definition: Type.h:6311
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
bool isAssignmentOp() const
Definition: Expr.h:3420
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:6651
Represents a point when we start the call exit sequence (for inlined call).
Definition: ProgramPoint.h:670
StringRef getOpcodeStr() const
Definition: Expr.h:3350
bool isGLValue() const
Definition: Expr.h:253
BinaryOperatorKind
static bool isInStdNamespace(const Decl *D)
Returns true if the root namespace of the given declaration is the &#39;std&#39; C++ namespace.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
child_range children()
Definition: Stmt.cpp:237
const LocationContext * getParent() const
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3294
static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest, const ExplodedNode *N, SVal ValueAfter)
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2595
static const Expr * peelOffPointerArithmetic(const BinaryOperator *B)
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
static const MemRegion * getLocationRegionIfReference(const Expr *E, const ExplodedNode *N)
bool isScalarType() const
Definition: Type.h:6636
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
NodeId Parent
Definition: ASTDiff.cpp:192
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1617
const Stmt * getCallSite() const
Represents a single basic block in a source-level CFG.
Definition: CFG.h:552
Represents a point when we finish the call exit sequence (for inlined call).
Definition: ProgramPoint.h:690
This represents one expression.
Definition: Expr.h:107
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
CFGBlock * getBlock(Stmt *S)
Returns the CFGBlock the specified Stmt* appears in.
Definition: CFGStmtMap.cpp:27
CallEventRef getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State)
Gets an outside caller given a callee context.
Definition: CallEvent.cpp:1363
bool inTopFrame() const override
Return true if the current LocationContext has no caller context.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
static std::pair< const ProgramPointTag *, const ProgramPointTag * > geteagerlyAssumeBinOpBifurcationTags()
QualType getType() const
Definition: Expr.h:129
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1752
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:2443
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
ValueDecl * getDecl()
Definition: Expr.h:1121
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
const SourceManager & SM
Definition: Format.cpp:1490
const ExpansionInfo & getExpansion() const
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:301
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: DeclBase.h:985
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6134
bool isComparisonOp() const
Definition: Expr.h:3385
static const Stmt * getStmt(const ExplodedNode *N)
Given an exploded node, retrieve the statement that should be used for the diagnostic location...
Maps string IDs to AST nodes matched by parts of a matcher.
Definition: ASTMatchers.h:102
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
CFGTerminator getTerminator()
Definition: CFG.h:840
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
QualType getCanonicalType() const
Definition: Type.h:6114
Encodes a location in the source.
static bool isCallStmt(const Stmt *S)
Returns true if this is a statement is a function or method call of some kind.
Definition: CallEvent.cpp:442
ProgramPoints can be "tagged" as representing points specific to a given analysis entity...
Definition: ProgramPoint.h:40
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:1143
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2041
bool isAnyPointerType() const
Definition: Type.h:6303
bool isObjCObjectPointerType() const
Definition: Type.h:6396
SMTSolverRef CreateZ3Solver()
Convenience method to create and Z3Solver object.
static void showBRDiagnostics(const char *action, llvm::raw_svector_ostream &os, const MemRegion *R, SVal V, const DeclStmt *DS)
Show diagnostics for initializing or declaring a region R with a bad value.
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:968
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1015
static bool isFunctionMacroExpansion(SourceLocation Loc, const SourceManager &SM)
Expr * getLHS() const
Definition: Expr.h:3334
ast_type_traits::DynTypedNode Node
Dataflow Directional Tag Classes.
static void showBRDefaultDiagnostics(llvm::raw_svector_ostream &os, const MemRegion *R, SVal V)
Show default diagnostics for storing bad region.
Parameter for Objective-C &#39;self&#39; argument.
Definition: Decl.h:1495
StmtClass getStmtClass() const
Definition: Stmt.h:1029
bool isBooleanType() const
Definition: Type.h:6664
const Decl * getSingleDecl() const
Definition: Stmt.h:1158
const ProgramPointTag * getTag() const
Definition: ProgramPoint.h:179
static void showBRParamDiagnostics(llvm::raw_svector_ostream &os, const VarRegion *VR, SVal V)
Display diagnostics for passing bad region as a parameter.
std::shared_ptr< SMTSolver > SMTSolverRef
Shared pointer for SMTSolvers.
Definition: SMTSolver.h:295
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument&#39;s expansion into the function-lik...
Indicates that the tracking object is a descendant of a referenced-counted OSObject, used in the Darwin kernel.
const LocationContext * getLocationContext() const
Definition: ProgramPoint.h:181
static bool isAdditiveOp(Opcode Opc)
Definition: Expr.h:3370
const StackFrameContext * getStackFrame() const
Stores options for the analyzer from the command line.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13969
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Defines the clang::SourceLocation class and associated facilities.
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
bool isVoidType() const
Definition: Type.h:6547
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1945
static PathDiagnosticLocation createEndOfPath(const ExplodedNode *N, const SourceManager &SM)
Create a location corresponding to the next valid ExplodedNode as end of path location.
static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR)
Returns true if N represents the DeclStmt declaring and initializing VR.
FullSourceLoc getSpellingLoc() const
A SourceLocation and its associated SourceManager.
std::shared_ptr< SMTExpr > SMTExprRef
Shared pointer for SMTExprs, used by SMTSolver API.
Definition: SMTExpr.h:57
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1048
Expr * getRHS() const
Definition: Expr.h:3336
bool isFunctionMacroExpansion() const
bool isPointerType() const
Definition: Type.h:6299
QualType getType() const
Definition: Decl.h:648
A trivial tuple used to represent a source range.
Optional< T > getAs() const
Convert to the specified ProgramPoint type, returning None if this ProgramPoint is not of the desired...
Definition: ProgramPoint.h:153
static bool isInterestingLValueExpr(const Expr *Ex)
Returns true if nodes for the given expression kind are always kept around.
This class handles loading and caching of source files into memory.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2560