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