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