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