clang  8.0.0svn
MallocChecker.cpp
Go to the documentation of this file.
1 //=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
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 malloc/free checker, which checks for potential memory
11 // leaks, double free, and use-after-free problems.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ClangSACheckers.h"
16 #include "InterCheckerAPI.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/ParentMap.h"
20 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "AllocationState.h"
34 #include <climits>
35 #include <utility>
36 
37 using namespace clang;
38 using namespace ento;
39 
40 namespace {
41 
42 // Used to check correspondence between allocators and deallocators.
44  AF_None,
45  AF_Malloc,
46  AF_CXXNew,
47  AF_CXXNewArray,
48  AF_IfNameIndex,
49  AF_Alloca,
50  AF_InnerBuffer
51 };
52 
53 class RefState {
54  enum Kind { // Reference to allocated memory.
55  Allocated,
56  // Reference to zero-allocated memory.
57  AllocatedOfSizeZero,
58  // Reference to released/freed memory.
59  Released,
60  // The responsibility for freeing resources has transferred from
61  // this reference. A relinquished symbol should not be freed.
62  Relinquished,
63  // We are no longer guaranteed to have observed all manipulations
64  // of this pointer/memory. For example, it could have been
65  // passed as a parameter to an opaque function.
66  Escaped
67  };
68 
69  const Stmt *S;
70  unsigned K : 3; // Kind enum, but stored as a bitfield.
71  unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
72  // family.
73 
74  RefState(Kind k, const Stmt *s, unsigned family)
75  : S(s), K(k), Family(family) {
76  assert(family != AF_None);
77  }
78 public:
79  bool isAllocated() const { return K == Allocated; }
80  bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
81  bool isReleased() const { return K == Released; }
82  bool isRelinquished() const { return K == Relinquished; }
83  bool isEscaped() const { return K == Escaped; }
84  AllocationFamily getAllocationFamily() const {
85  return (AllocationFamily)Family;
86  }
87  const Stmt *getStmt() const { return S; }
88 
89  bool operator==(const RefState &X) const {
90  return K == X.K && S == X.S && Family == X.Family;
91  }
92 
93  static RefState getAllocated(unsigned family, const Stmt *s) {
94  return RefState(Allocated, s, family);
95  }
96  static RefState getAllocatedOfSizeZero(const RefState *RS) {
97  return RefState(AllocatedOfSizeZero, RS->getStmt(),
98  RS->getAllocationFamily());
99  }
100  static RefState getReleased(unsigned family, const Stmt *s) {
101  return RefState(Released, s, family);
102  }
103  static RefState getRelinquished(unsigned family, const Stmt *s) {
104  return RefState(Relinquished, s, family);
105  }
106  static RefState getEscaped(const RefState *RS) {
107  return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
108  }
109 
110  void Profile(llvm::FoldingSetNodeID &ID) const {
111  ID.AddInteger(K);
112  ID.AddPointer(S);
113  ID.AddInteger(Family);
114  }
115 
116  void dump(raw_ostream &OS) const {
117  switch (static_cast<Kind>(K)) {
118 #define CASE(ID) case ID: OS << #ID; break;
119  CASE(Allocated)
120  CASE(AllocatedOfSizeZero)
121  CASE(Released)
122  CASE(Relinquished)
123  CASE(Escaped)
124  }
125  }
126 
127  LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
128 };
129 
131  RPToBeFreedAfterFailure,
132  // The symbol has been freed when reallocation failed.
133  RPIsFreeOnFailure,
134  // The symbol does not need to be freed after reallocation fails.
135  RPDoNotTrackAfterFailure
136 };
137 
138 /// \class ReallocPair
139 /// Stores information about the symbol being reallocated by a call to
140 /// 'realloc' to allow modeling failed reallocation later in the path.
141 struct ReallocPair {
142  // The symbol which realloc reallocated.
143  SymbolRef ReallocatedSym;
145 
146  ReallocPair(SymbolRef S, ReallocPairKind K) :
147  ReallocatedSym(S), Kind(K) {}
148  void Profile(llvm::FoldingSetNodeID &ID) const {
149  ID.AddInteger(Kind);
150  ID.AddPointer(ReallocatedSym);
151  }
152  bool operator==(const ReallocPair &X) const {
153  return ReallocatedSym == X.ReallocatedSym &&
154  Kind == X.Kind;
155  }
156 };
157 
158 typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
159 
160 class MallocChecker : public Checker<check::DeadSymbols,
161  check::PointerEscape,
162  check::ConstPointerEscape,
163  check::PreStmt<ReturnStmt>,
164  check::EndFunction,
165  check::PreCall,
166  check::PostStmt<CallExpr>,
167  check::PostStmt<CXXNewExpr>,
168  check::NewAllocator,
169  check::PreStmt<CXXDeleteExpr>,
170  check::PostStmt<BlockExpr>,
171  check::PostObjCMessage,
172  check::Location,
173  eval::Assume>
174 {
175 public:
176  MallocChecker()
177  : II_alloca(nullptr), II_win_alloca(nullptr), II_malloc(nullptr),
178  II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
179  II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
180  II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr),
181  II_if_nameindex(nullptr), II_if_freenameindex(nullptr),
182  II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr),
183  II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr),
184  II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr),
185  II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr),
186  II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr),
187  II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr),
188  II_g_try_realloc_n(nullptr) {}
189 
190  /// In pessimistic mode, the checker assumes that it does not know which
191  /// functions might free the memory.
192  enum CheckKind {
193  CK_MallocChecker,
194  CK_NewDeleteChecker,
195  CK_NewDeleteLeaksChecker,
196  CK_MismatchedDeallocatorChecker,
197  CK_InnerPointerChecker,
198  CK_NumCheckKinds
199  };
200 
201  enum class MemoryOperationKind {
202  MOK_Allocate,
203  MOK_Free,
204  MOK_Any
205  };
206 
207  DefaultBool IsOptimistic;
208 
209  DefaultBool ChecksEnabled[CK_NumCheckKinds];
210  CheckName CheckNames[CK_NumCheckKinds];
211 
212  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
213  void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
214  void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
215  void checkNewAllocator(const CXXNewExpr *NE, SVal Target,
216  CheckerContext &C) const;
217  void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
218  void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
219  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
220  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
221  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
222  void checkEndFunction(const ReturnStmt *S, CheckerContext &C) const;
223  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
224  bool Assumption) const;
225  void checkLocation(SVal l, bool isLoad, const Stmt *S,
226  CheckerContext &C) const;
227 
228  ProgramStateRef checkPointerEscape(ProgramStateRef State,
229  const InvalidatedSymbols &Escaped,
230  const CallEvent *Call,
231  PointerEscapeKind Kind) const;
232  ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
233  const InvalidatedSymbols &Escaped,
234  const CallEvent *Call,
235  PointerEscapeKind Kind) const;
236 
237  void printState(raw_ostream &Out, ProgramStateRef State,
238  const char *NL, const char *Sep) const override;
239 
240 private:
241  mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
242  mutable std::unique_ptr<BugType> BT_DoubleDelete;
243  mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
244  mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
245  mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
246  mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
247  mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
248  mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
249  mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
250  mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
251  *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
252  *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
253  *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
254  *II_win_wcsdup, *II_g_malloc, *II_g_malloc0,
255  *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0,
256  *II_g_try_realloc, *II_g_free, *II_g_memdup,
257  *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n,
258  *II_g_try_malloc_n, *II_g_try_malloc0_n,
259  *II_g_try_realloc_n;
260  mutable Optional<uint64_t> KernelZeroFlagVal;
261 
262  void initIdentifierInfo(ASTContext &C) const;
263 
264  /// Determine family of a deallocation expression.
265  AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
266 
267  /// Print names of allocators and deallocators.
268  ///
269  /// \returns true on success.
270  bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
271  const Expr *E) const;
272 
273  /// Print expected name of an allocator based on the deallocator's
274  /// family derived from the DeallocExpr.
275  void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
276  const Expr *DeallocExpr) const;
277  /// Print expected name of a deallocator based on the allocator's
278  /// family.
279  void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
280 
281  ///@{
282  /// Check if this is one of the functions which can allocate/reallocate memory
283  /// pointed to by one of its arguments.
284  bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
285  bool isCMemFunction(const FunctionDecl *FD,
286  ASTContext &C,
287  AllocationFamily Family,
288  MemoryOperationKind MemKind) const;
289  bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
290  ///@}
291 
292  /// Process C++ operator new()'s allocation, which is the part of C++
293  /// new-expression that goes before the constructor.
294  void processNewAllocation(const CXXNewExpr *NE, CheckerContext &C,
295  SVal Target) const;
296 
297  /// Perform a zero-allocation check.
298  /// The optional \p RetVal parameter specifies the newly allocated pointer
299  /// value; if unspecified, the value of expression \p E is used.
300  ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
301  const unsigned AllocationSizeArg,
302  ProgramStateRef State,
303  Optional<SVal> RetVal = None) const;
304 
305  ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
306  const CallExpr *CE,
307  const OwnershipAttr* Att,
308  ProgramStateRef State) const;
309  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
310  const Expr *SizeEx, SVal Init,
311  ProgramStateRef State,
312  AllocationFamily Family = AF_Malloc);
313  static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
314  SVal SizeEx, SVal Init,
315  ProgramStateRef State,
316  AllocationFamily Family = AF_Malloc);
317 
318  static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
319  ProgramStateRef State, SVal Target);
320 
321  // Check if this malloc() for special flags. At present that means M_ZERO or
322  // __GFP_ZERO (in which case, treat it like calloc).
324  performKernelMalloc(const CallExpr *CE, CheckerContext &C,
325  const ProgramStateRef &State) const;
326 
327  /// Update the RefState to reflect the new memory allocation.
328  /// The optional \p RetVal parameter specifies the newly allocated pointer
329  /// value; if unspecified, the value of expression \p E is used.
330  static ProgramStateRef
331  MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
332  AllocationFamily Family = AF_Malloc,
333  Optional<SVal> RetVal = None);
334 
335  ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
336  const OwnershipAttr* Att,
337  ProgramStateRef State) const;
338  ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
339  ProgramStateRef state, unsigned Num,
340  bool Hold,
341  bool &ReleasedAllocated,
342  bool ReturnsNullOnFailure = false) const;
343  ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
344  const Expr *ParentExpr,
345  ProgramStateRef State,
346  bool Hold,
347  bool &ReleasedAllocated,
348  bool ReturnsNullOnFailure = false) const;
349 
350  ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE,
351  bool FreesMemOnFailure,
352  ProgramStateRef State,
353  bool SuffixWithN = false) const;
354  static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
355  const Expr *BlockBytes);
356  static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
357  ProgramStateRef State);
358 
359  /// Check if the memory associated with this symbol was released.
360  bool isReleased(SymbolRef Sym, CheckerContext &C) const;
361 
362  bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
363 
364  void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
365  const Stmt *S) const;
366 
367  bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
368 
369  /// Check if the function is known free memory, or if it is
370  /// "interesting" and should be modeled explicitly.
371  ///
372  /// \param [out] EscapingSymbol A function might not free memory in general,
373  /// but could be known to free a particular symbol. In this case, false is
374  /// returned and the single escaping symbol is returned through the out
375  /// parameter.
376  ///
377  /// We assume that pointers do not escape through calls to system functions
378  /// not handled by this checker.
379  bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
380  ProgramStateRef State,
381  SymbolRef &EscapingSymbol) const;
382 
383  // Implementation of the checkPointerEscape callbacks.
384  ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
385  const InvalidatedSymbols &Escaped,
386  const CallEvent *Call,
387  PointerEscapeKind Kind,
388  bool(*CheckRefState)(const RefState*)) const;
389 
390  // Implementation of the checkPreStmt and checkEndFunction callbacks.
391  void checkEscapeOnReturn(const ReturnStmt *S, CheckerContext &C) const;
392 
393  ///@{
394  /// Tells if a given family/call/symbol is tracked by the current checker.
395  /// Sets CheckKind to the kind of the checker responsible for this
396  /// family/call/symbol.
397  Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
398  bool IsALeakCheck = false) const;
399  Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
400  const Stmt *AllocDeallocStmt,
401  bool IsALeakCheck = false) const;
402  Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
403  bool IsALeakCheck = false) const;
404  ///@}
405  static bool SummarizeValue(raw_ostream &os, SVal V);
406  static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
407  void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
408  const Expr *DeallocExpr) const;
409  void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
410  SourceRange Range) const;
411  void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
412  const Expr *DeallocExpr, const RefState *RS,
413  SymbolRef Sym, bool OwnershipTransferred) const;
414  void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
415  const Expr *DeallocExpr,
416  const Expr *AllocExpr = nullptr) const;
417  void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
418  SymbolRef Sym) const;
419  void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
420  SymbolRef Sym, SymbolRef PrevSym) const;
421 
422  void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
423 
424  void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
425  SymbolRef Sym) const;
426 
427  void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
428  SourceRange Range, const Expr *FreeExpr) const;
429 
430  /// Find the location of the allocation for Sym on the path leading to the
431  /// exploded node N.
432  LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
433  CheckerContext &C) const;
434 
435  void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
436 
437  /// The bug visitor which allows us to print extra diagnostics along the
438  /// BugReport path. For example, showing the allocation site of the leaked
439  /// region.
440  class MallocBugVisitor final : public BugReporterVisitor {
441  protected:
442  enum NotificationMode {
443  Normal,
444  ReallocationFailed
445  };
446 
447  // The allocated region symbol tracked by the main analysis.
448  SymbolRef Sym;
449 
450  // The mode we are in, i.e. what kind of diagnostics will be emitted.
451  NotificationMode Mode;
452 
453  // A symbol from when the primary region should have been reallocated.
454  SymbolRef FailedReallocSymbol;
455 
456  // A C++ destructor stack frame in which memory was released. Used for
457  // miscellaneous false positive suppression.
458  const StackFrameContext *ReleaseDestructorLC;
459 
460  bool IsLeak;
461 
462  public:
463  MallocBugVisitor(SymbolRef S, bool isLeak = false)
464  : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr),
465  ReleaseDestructorLC(nullptr), IsLeak(isLeak) {}
466 
467  static void *getTag() {
468  static int Tag = 0;
469  return &Tag;
470  }
471 
472  void Profile(llvm::FoldingSetNodeID &ID) const override {
473  ID.AddPointer(getTag());
474  ID.AddPointer(Sym);
475  }
476 
477  inline bool isAllocated(const RefState *S, const RefState *SPrev,
478  const Stmt *Stmt) {
479  // Did not track -> allocated. Other state (released) -> allocated.
480  return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
481  (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
482  (!SPrev || !(SPrev->isAllocated() ||
483  SPrev->isAllocatedOfSizeZero())));
484  }
485 
486  inline bool isReleased(const RefState *S, const RefState *SPrev,
487  const Stmt *Stmt) {
488  // Did not track -> released. Other state (allocated) -> released.
489  // The statement associated with the release might be missing.
490  bool IsReleased = (S && S->isReleased()) &&
491  (!SPrev || !SPrev->isReleased());
492  assert(!IsReleased ||
493  (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt))) ||
494  (!Stmt && S->getAllocationFamily() == AF_InnerBuffer));
495  return IsReleased;
496  }
497 
498  inline bool isRelinquished(const RefState *S, const RefState *SPrev,
499  const Stmt *Stmt) {
500  // Did not track -> relinquished. Other state (allocated) -> relinquished.
501  return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
502  isa<ObjCPropertyRefExpr>(Stmt)) &&
503  (S && S->isRelinquished()) &&
504  (!SPrev || !SPrev->isRelinquished()));
505  }
506 
507  inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
508  const Stmt *Stmt) {
509  // If the expression is not a call, and the state change is
510  // released -> allocated, it must be the realloc return value
511  // check. If we have to handle more cases here, it might be cleaner just
512  // to track this extra bit in the state itself.
513  return ((!Stmt || !isa<CallExpr>(Stmt)) &&
514  (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
515  (SPrev && !(SPrev->isAllocated() ||
516  SPrev->isAllocatedOfSizeZero())));
517  }
518 
519  std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
520  const ExplodedNode *PrevN,
521  BugReporterContext &BRC,
522  BugReport &BR) override;
523 
524  std::shared_ptr<PathDiagnosticPiece>
525  getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
526  BugReport &BR) override {
527  if (!IsLeak)
528  return nullptr;
529 
530  PathDiagnosticLocation L =
532  BRC.getSourceManager());
533  // Do not add the statement itself as a range in case of leak.
534  return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
535  false);
536  }
537 
538  private:
539  class StackHintGeneratorForReallocationFailed
540  : public StackHintGeneratorForSymbol {
541  public:
542  StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
543  : StackHintGeneratorForSymbol(S, M) {}
544 
545  std::string getMessageForArg(const Expr *ArgE,
546  unsigned ArgIndex) override {
547  // Printed parameters start at 1, not 0.
548  ++ArgIndex;
549 
550  SmallString<200> buf;
551  llvm::raw_svector_ostream os(buf);
552 
553  os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
554  << " parameter failed";
555 
556  return os.str();
557  }
558 
559  std::string getMessageForReturn(const CallExpr *CallExpr) override {
560  return "Reallocation of returned value failed";
561  }
562  };
563  };
564 };
565 } // end anonymous namespace
566 
567 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
568 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
569 REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
570 
571 // A map from the freed symbol to the symbol representing the return value of
572 // the free function.
574 
575 namespace {
576 class StopTrackingCallback final : public SymbolVisitor {
578 public:
579  StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
580  ProgramStateRef getState() const { return state; }
581 
582  bool VisitSymbol(SymbolRef sym) override {
583  state = state->remove<RegionState>(sym);
584  return true;
585  }
586 };
587 } // end anonymous namespace
588 
589 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
590  if (II_malloc)
591  return;
592  II_alloca = &Ctx.Idents.get("alloca");
593  II_malloc = &Ctx.Idents.get("malloc");
594  II_free = &Ctx.Idents.get("free");
595  II_realloc = &Ctx.Idents.get("realloc");
596  II_reallocf = &Ctx.Idents.get("reallocf");
597  II_calloc = &Ctx.Idents.get("calloc");
598  II_valloc = &Ctx.Idents.get("valloc");
599  II_strdup = &Ctx.Idents.get("strdup");
600  II_strndup = &Ctx.Idents.get("strndup");
601  II_wcsdup = &Ctx.Idents.get("wcsdup");
602  II_kmalloc = &Ctx.Idents.get("kmalloc");
603  II_if_nameindex = &Ctx.Idents.get("if_nameindex");
604  II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
605 
606  //MSVC uses `_`-prefixed instead, so we check for them too.
607  II_win_strdup = &Ctx.Idents.get("_strdup");
608  II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
609  II_win_alloca = &Ctx.Idents.get("_alloca");
610 
611  // Glib
612  II_g_malloc = &Ctx.Idents.get("g_malloc");
613  II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
614  II_g_realloc = &Ctx.Idents.get("g_realloc");
615  II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
616  II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
617  II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
618  II_g_free = &Ctx.Idents.get("g_free");
619  II_g_memdup = &Ctx.Idents.get("g_memdup");
620  II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
621  II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
622  II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
623  II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
624  II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
625  II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
626 }
627 
628 bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
629  if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
630  return true;
631 
632  if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
633  return true;
634 
635  if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
636  return true;
637 
638  if (isStandardNewDelete(FD, C))
639  return true;
640 
641  return false;
642 }
643 
644 bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
645  ASTContext &C,
646  AllocationFamily Family,
647  MemoryOperationKind MemKind) const {
648  if (!FD)
649  return false;
650 
651  bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
652  MemKind == MemoryOperationKind::MOK_Free);
653  bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
654  MemKind == MemoryOperationKind::MOK_Allocate);
655 
656  if (FD->getKind() == Decl::Function) {
657  const IdentifierInfo *FunI = FD->getIdentifier();
658  initIdentifierInfo(C);
659 
660  if (Family == AF_Malloc && CheckFree) {
661  if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
662  FunI == II_g_free)
663  return true;
664  }
665 
666  if (Family == AF_Malloc && CheckAlloc) {
667  if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
668  FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
669  FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
670  FunI == II_win_wcsdup || FunI == II_kmalloc ||
671  FunI == II_g_malloc || FunI == II_g_malloc0 ||
672  FunI == II_g_realloc || FunI == II_g_try_malloc ||
673  FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
674  FunI == II_g_memdup || FunI == II_g_malloc_n ||
675  FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
676  FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
677  FunI == II_g_try_realloc_n)
678  return true;
679  }
680 
681  if (Family == AF_IfNameIndex && CheckFree) {
682  if (FunI == II_if_freenameindex)
683  return true;
684  }
685 
686  if (Family == AF_IfNameIndex && CheckAlloc) {
687  if (FunI == II_if_nameindex)
688  return true;
689  }
690 
691  if (Family == AF_Alloca && CheckAlloc) {
692  if (FunI == II_alloca || FunI == II_win_alloca)
693  return true;
694  }
695  }
696 
697  if (Family != AF_Malloc)
698  return false;
699 
700  if (IsOptimistic && FD->hasAttrs()) {
701  for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
702  OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
703  if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
704  if (CheckFree)
705  return true;
706  } else if (OwnKind == OwnershipAttr::Returns) {
707  if (CheckAlloc)
708  return true;
709  }
710  }
711  }
712 
713  return false;
714 }
715 
716 // Tells if the callee is one of the following:
717 // 1) A global non-placement new/delete operator function.
718 // 2) A global placement operator function with the single placement argument
719 // of type std::nothrow_t.
720 bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
721  ASTContext &C) const {
722  if (!FD)
723  return false;
724 
726  if (Kind != OO_New && Kind != OO_Array_New &&
727  Kind != OO_Delete && Kind != OO_Array_Delete)
728  return false;
729 
730  // Skip all operator new/delete methods.
731  if (isa<CXXMethodDecl>(FD))
732  return false;
733 
734  // Return true if tested operator is a standard placement nothrow operator.
735  if (FD->getNumParams() == 2) {
736  QualType T = FD->getParamDecl(1)->getType();
737  if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
738  return II->getName().equals("nothrow_t");
739  }
740 
741  // Skip placement operators.
742  if (FD->getNumParams() != 1 || FD->isVariadic())
743  return false;
744 
745  // One of the standard new/new[]/delete/delete[] non-placement operators.
746  return true;
747 }
748 
749 llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
750  const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
751  // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
752  //
753  // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
754  //
755  // One of the possible flags is M_ZERO, which means 'give me back an
756  // allocation which is already zeroed', like calloc.
757 
758  // 2-argument kmalloc(), as used in the Linux kernel:
759  //
760  // void *kmalloc(size_t size, gfp_t flags);
761  //
762  // Has the similar flag value __GFP_ZERO.
763 
764  // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
765  // code could be shared.
766 
767  ASTContext &Ctx = C.getASTContext();
768  llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
769 
770  if (!KernelZeroFlagVal.hasValue()) {
771  if (OS == llvm::Triple::FreeBSD)
772  KernelZeroFlagVal = 0x0100;
773  else if (OS == llvm::Triple::NetBSD)
774  KernelZeroFlagVal = 0x0002;
775  else if (OS == llvm::Triple::OpenBSD)
776  KernelZeroFlagVal = 0x0008;
777  else if (OS == llvm::Triple::Linux)
778  // __GFP_ZERO
779  KernelZeroFlagVal = 0x8000;
780  else
781  // FIXME: We need a more general way of getting the M_ZERO value.
782  // See also: O_CREAT in UnixAPIChecker.cpp.
783 
784  // Fall back to normal malloc behavior on platforms where we don't
785  // know M_ZERO.
786  return None;
787  }
788 
789  // We treat the last argument as the flags argument, and callers fall-back to
790  // normal malloc on a None return. This works for the FreeBSD kernel malloc
791  // as well as Linux kmalloc.
792  if (CE->getNumArgs() < 2)
793  return None;
794 
795  const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
796  const SVal V = C.getSVal(FlagsEx);
797  if (!V.getAs<NonLoc>()) {
798  // The case where 'V' can be a location can only be due to a bad header,
799  // so in this case bail out.
800  return None;
801  }
802 
803  NonLoc Flags = V.castAs<NonLoc>();
804  NonLoc ZeroFlag = C.getSValBuilder()
805  .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
806  .castAs<NonLoc>();
807  SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
808  Flags, ZeroFlag,
809  FlagsEx->getType());
810  if (MaskedFlagsUC.isUnknownOrUndef())
811  return None;
812  DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
813 
814  // Check if maskedFlags is non-zero.
815  ProgramStateRef TrueState, FalseState;
816  std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
817 
818  // If M_ZERO is set, treat this like calloc (initialized).
819  if (TrueState && !FalseState) {
820  SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
821  return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
822  }
823 
824  return None;
825 }
826 
827 SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
828  const Expr *BlockBytes) {
829  SValBuilder &SB = C.getSValBuilder();
830  SVal BlocksVal = C.getSVal(Blocks);
831  SVal BlockBytesVal = C.getSVal(BlockBytes);
832  ProgramStateRef State = C.getState();
833  SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
834  SB.getContext().getSizeType());
835  return TotalSize;
836 }
837 
838 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
839  if (C.wasInlined)
840  return;
841 
842  const FunctionDecl *FD = C.getCalleeDecl(CE);
843  if (!FD)
844  return;
845 
846  ProgramStateRef State = C.getState();
847  bool ReleasedAllocatedMemory = false;
848 
849  if (FD->getKind() == Decl::Function) {
850  initIdentifierInfo(C.getASTContext());
851  IdentifierInfo *FunI = FD->getIdentifier();
852 
853  if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
854  if (CE->getNumArgs() < 1)
855  return;
856  if (CE->getNumArgs() < 3) {
857  State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
858  if (CE->getNumArgs() == 1)
859  State = ProcessZeroAllocation(C, CE, 0, State);
860  } else if (CE->getNumArgs() == 3) {
862  performKernelMalloc(CE, C, State);
863  if (MaybeState.hasValue())
864  State = MaybeState.getValue();
865  else
866  State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
867  }
868  } else if (FunI == II_kmalloc) {
869  if (CE->getNumArgs() < 1)
870  return;
872  performKernelMalloc(CE, C, State);
873  if (MaybeState.hasValue())
874  State = MaybeState.getValue();
875  else
876  State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
877  } else if (FunI == II_valloc) {
878  if (CE->getNumArgs() < 1)
879  return;
880  State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
881  State = ProcessZeroAllocation(C, CE, 0, State);
882  } else if (FunI == II_realloc || FunI == II_g_realloc ||
883  FunI == II_g_try_realloc) {
884  State = ReallocMemAux(C, CE, false, State);
885  State = ProcessZeroAllocation(C, CE, 1, State);
886  } else if (FunI == II_reallocf) {
887  State = ReallocMemAux(C, CE, true, State);
888  State = ProcessZeroAllocation(C, CE, 1, State);
889  } else if (FunI == II_calloc) {
890  State = CallocMem(C, CE, State);
891  State = ProcessZeroAllocation(C, CE, 0, State);
892  State = ProcessZeroAllocation(C, CE, 1, State);
893  } else if (FunI == II_free || FunI == II_g_free) {
894  State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
895  } else if (FunI == II_strdup || FunI == II_win_strdup ||
896  FunI == II_wcsdup || FunI == II_win_wcsdup) {
897  State = MallocUpdateRefState(C, CE, State);
898  } else if (FunI == II_strndup) {
899  State = MallocUpdateRefState(C, CE, State);
900  } else if (FunI == II_alloca || FunI == II_win_alloca) {
901  if (CE->getNumArgs() < 1)
902  return;
903  State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
904  AF_Alloca);
905  State = ProcessZeroAllocation(C, CE, 0, State);
906  } else if (isStandardNewDelete(FD, C.getASTContext())) {
907  // Process direct calls to operator new/new[]/delete/delete[] functions
908  // as distinct from new/new[]/delete/delete[] expressions that are
909  // processed by the checkPostStmt callbacks for CXXNewExpr and
910  // CXXDeleteExpr.
912  if (K == OO_New) {
913  State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
914  AF_CXXNew);
915  State = ProcessZeroAllocation(C, CE, 0, State);
916  }
917  else if (K == OO_Array_New) {
918  State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
919  AF_CXXNewArray);
920  State = ProcessZeroAllocation(C, CE, 0, State);
921  }
922  else if (K == OO_Delete || K == OO_Array_Delete)
923  State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
924  else
925  llvm_unreachable("not a new/delete operator");
926  } else if (FunI == II_if_nameindex) {
927  // Should we model this differently? We can allocate a fixed number of
928  // elements with zeros in the last one.
929  State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
930  AF_IfNameIndex);
931  } else if (FunI == II_if_freenameindex) {
932  State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
933  } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
934  if (CE->getNumArgs() < 1)
935  return;
936  SValBuilder &svalBuilder = C.getSValBuilder();
937  SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
938  State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
939  State = ProcessZeroAllocation(C, CE, 0, State);
940  } else if (FunI == II_g_memdup) {
941  if (CE->getNumArgs() < 2)
942  return;
943  State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
944  State = ProcessZeroAllocation(C, CE, 1, State);
945  } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
946  FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
947  if (CE->getNumArgs() < 2)
948  return;
949  SVal Init = UndefinedVal();
950  if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
951  SValBuilder &SB = C.getSValBuilder();
952  Init = SB.makeZeroVal(SB.getContext().CharTy);
953  }
954  SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
955  State = MallocMemAux(C, CE, TotalSize, Init, State);
956  State = ProcessZeroAllocation(C, CE, 0, State);
957  State = ProcessZeroAllocation(C, CE, 1, State);
958  } else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
959  if (CE->getNumArgs() < 3)
960  return;
961  State = ReallocMemAux(C, CE, false, State, true);
962  State = ProcessZeroAllocation(C, CE, 1, State);
963  State = ProcessZeroAllocation(C, CE, 2, State);
964  }
965  }
966 
967  if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
968  // Check all the attributes, if there are any.
969  // There can be multiple of these attributes.
970  if (FD->hasAttrs())
971  for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
972  switch (I->getOwnKind()) {
973  case OwnershipAttr::Returns:
974  State = MallocMemReturnsAttr(C, CE, I, State);
975  break;
976  case OwnershipAttr::Takes:
977  case OwnershipAttr::Holds:
978  State = FreeMemAttr(C, CE, I, State);
979  break;
980  }
981  }
982  }
983  C.addTransition(State);
984 }
985 
986 // Performs a 0-sized allocations check.
987 ProgramStateRef MallocChecker::ProcessZeroAllocation(
988  CheckerContext &C, const Expr *E, const unsigned AllocationSizeArg,
989  ProgramStateRef State, Optional<SVal> RetVal) const {
990  if (!State)
991  return nullptr;
992 
993  if (!RetVal)
994  RetVal = C.getSVal(E);
995 
996  const Expr *Arg = nullptr;
997 
998  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
999  Arg = CE->getArg(AllocationSizeArg);
1000  }
1001  else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1002  if (NE->isArray())
1003  Arg = NE->getArraySize();
1004  else
1005  return State;
1006  }
1007  else
1008  llvm_unreachable("not a CallExpr or CXXNewExpr");
1009 
1010  assert(Arg);
1011 
1012  Optional<DefinedSVal> DefArgVal = C.getSVal(Arg).getAs<DefinedSVal>();
1013 
1014  if (!DefArgVal)
1015  return State;
1016 
1017  // Check if the allocation size is 0.
1018  ProgramStateRef TrueState, FalseState;
1019  SValBuilder &SvalBuilder = C.getSValBuilder();
1020  DefinedSVal Zero =
1021  SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1022 
1023  std::tie(TrueState, FalseState) =
1024  State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1025 
1026  if (TrueState && !FalseState) {
1027  SymbolRef Sym = RetVal->getAsLocSymbol();
1028  if (!Sym)
1029  return State;
1030 
1031  const RefState *RS = State->get<RegionState>(Sym);
1032  if (RS) {
1033  if (RS->isAllocated())
1034  return TrueState->set<RegionState>(Sym,
1035  RefState::getAllocatedOfSizeZero(RS));
1036  else
1037  return State;
1038  } else {
1039  // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1040  // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1041  // tracked. Add zero-reallocated Sym to the state to catch references
1042  // to zero-allocated memory.
1043  return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1044  }
1045  }
1046 
1047  // Assume the value is non-zero going forward.
1048  assert(FalseState);
1049  return FalseState;
1050 }
1051 
1053  QualType Result = T, PointeeType = T->getPointeeType();
1054  while (!PointeeType.isNull()) {
1055  Result = PointeeType;
1056  PointeeType = PointeeType->getPointeeType();
1057  }
1058  return Result;
1059 }
1060 
1061 static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1062 
1063  const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1064  if (!ConstructE)
1065  return false;
1066 
1067  if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1068  return false;
1069 
1070  const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1071 
1072  // Iterate over the constructor parameters.
1073  for (const auto *CtorParam : CtorD->parameters()) {
1074 
1075  QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1076  if (CtorParamPointeeT.isNull())
1077  continue;
1078 
1079  CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1080 
1081  if (CtorParamPointeeT->getAsCXXRecordDecl())
1082  return true;
1083  }
1084 
1085  return false;
1086 }
1087 
1088 void MallocChecker::processNewAllocation(const CXXNewExpr *NE,
1089  CheckerContext &C,
1090  SVal Target) const {
1091  if (NE->getNumPlacementArgs())
1093  E = NE->placement_arg_end(); I != E; ++I)
1094  if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1095  checkUseAfterFree(Sym, C, *I);
1096 
1097  if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1098  return;
1099 
1100  ParentMap &PM = C.getLocationContext()->getParentMap();
1101  if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1102  return;
1103 
1104  ProgramStateRef State = C.getState();
1105  // The return value from operator new is bound to a specified initialization
1106  // value (if any) and we don't want to loose this value. So we call
1107  // MallocUpdateRefState() instead of MallocMemAux() which breakes the
1108  // existing binding.
1109  State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
1110  : AF_CXXNew, Target);
1111  State = addExtentSize(C, NE, State, Target);
1112  State = ProcessZeroAllocation(C, NE, 0, State, Target);
1113  C.addTransition(State);
1114 }
1115 
1116 void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1117  CheckerContext &C) const {
1118  if (!C.getAnalysisManager().getAnalyzerOptions().mayInlineCXXAllocator())
1119  processNewAllocation(NE, C, C.getSVal(NE));
1120 }
1121 
1122 void MallocChecker::checkNewAllocator(const CXXNewExpr *NE, SVal Target,
1123  CheckerContext &C) const {
1124  if (!C.wasInlined)
1125  processNewAllocation(NE, C, Target);
1126 }
1127 
1128 // Sets the extent value of the MemRegion allocated by
1129 // new expression NE to its size in Bytes.
1130 //
1131 ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1132  const CXXNewExpr *NE,
1134  SVal Target) {
1135  if (!State)
1136  return nullptr;
1137  SValBuilder &svalBuilder = C.getSValBuilder();
1138  SVal ElementCount;
1139  const SubRegion *Region;
1140  if (NE->isArray()) {
1141  const Expr *SizeExpr = NE->getArraySize();
1142  ElementCount = C.getSVal(SizeExpr);
1143  // Store the extent size for the (symbolic)region
1144  // containing the elements.
1145  Region = Target.getAsRegion()
1146  ->getAs<SubRegion>()
1147  ->StripCasts()
1148  ->getAs<SubRegion>();
1149  } else {
1150  ElementCount = svalBuilder.makeIntVal(1, true);
1151  Region = Target.getAsRegion()->getAs<SubRegion>();
1152  }
1153  assert(Region);
1154 
1155  // Set the region's extent equal to the Size in Bytes.
1156  QualType ElementType = NE->getAllocatedType();
1157  ASTContext &AstContext = C.getASTContext();
1158  CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1159 
1160  if (ElementCount.getAs<NonLoc>()) {
1161  DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1162  // size in Bytes = ElementCount*TypeSize
1163  SVal SizeInBytes = svalBuilder.evalBinOpNN(
1164  State, BO_Mul, ElementCount.castAs<NonLoc>(),
1165  svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1166  svalBuilder.getArrayIndexType());
1167  DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1168  State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1169  State = State->assume(extentMatchesSize, true);
1170  }
1171  return State;
1172 }
1173 
1174 void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
1175  CheckerContext &C) const {
1176 
1177  if (!ChecksEnabled[CK_NewDeleteChecker])
1178  if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1179  checkUseAfterFree(Sym, C, DE->getArgument());
1180 
1181  if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1182  return;
1183 
1184  ProgramStateRef State = C.getState();
1185  bool ReleasedAllocated;
1186  State = FreeMemAux(C, DE->getArgument(), DE, State,
1187  /*Hold*/false, ReleasedAllocated);
1188 
1189  C.addTransition(State);
1190 }
1191 
1193  // If the first selector piece is one of the names below, assume that the
1194  // object takes ownership of the memory, promising to eventually deallocate it
1195  // with free().
1196  // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1197  // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1198  StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1199  return FirstSlot == "dataWithBytesNoCopy" ||
1200  FirstSlot == "initWithBytesNoCopy" ||
1201  FirstSlot == "initWithCharactersNoCopy";
1202 }
1203 
1205  Selector S = Call.getSelector();
1206 
1207  // FIXME: We should not rely on fully-constrained symbols being folded.
1208  for (unsigned i = 1; i < S.getNumArgs(); ++i)
1209  if (S.getNameForSlot(i).equals("freeWhenDone"))
1210  return !Call.getArgSVal(i).isZeroConstant();
1211 
1212  return None;
1213 }
1214 
1215 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1216  CheckerContext &C) const {
1217  if (C.wasInlined)
1218  return;
1219 
1220  if (!isKnownDeallocObjCMethodName(Call))
1221  return;
1222 
1223  if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1224  if (!*FreeWhenDone)
1225  return;
1226 
1227  bool ReleasedAllocatedMemory;
1228  ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1229  Call.getOriginExpr(), C.getState(),
1230  /*Hold=*/true, ReleasedAllocatedMemory,
1231  /*RetNullOnFailure=*/true);
1232 
1233  C.addTransition(State);
1234 }
1235 
1237 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
1238  const OwnershipAttr *Att,
1239  ProgramStateRef State) const {
1240  if (!State)
1241  return nullptr;
1242 
1243  if (Att->getModule() != II_malloc)
1244  return nullptr;
1245 
1246  OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1247  if (I != E) {
1248  return MallocMemAux(C, CE, CE->getArg(I->getASTIndex()), UndefinedVal(),
1249  State);
1250  }
1251  return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1252 }
1253 
1254 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1255  const CallExpr *CE,
1256  const Expr *SizeEx, SVal Init,
1258  AllocationFamily Family) {
1259  if (!State)
1260  return nullptr;
1261 
1262  return MallocMemAux(C, CE, C.getSVal(SizeEx), Init, State, Family);
1263 }
1264 
1265 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1266  const CallExpr *CE,
1267  SVal Size, SVal Init,
1269  AllocationFamily Family) {
1270  if (!State)
1271  return nullptr;
1272 
1273  // We expect the malloc functions to return a pointer.
1274  if (!Loc::isLocType(CE->getType()))
1275  return nullptr;
1276 
1277  // Bind the return value to the symbolic value from the heap region.
1278  // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1279  // side effects other than what we model here.
1280  unsigned Count = C.blockCount();
1281  SValBuilder &svalBuilder = C.getSValBuilder();
1282  const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1283  DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1284  .castAs<DefinedSVal>();
1285  State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1286 
1287  // Fill the region with the initialization value.
1288  State = State->bindDefaultInitial(RetVal, Init, LCtx);
1289 
1290  // Set the region's extent equal to the Size parameter.
1291  const SymbolicRegion *R =
1292  dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1293  if (!R)
1294  return nullptr;
1295  if (Optional<DefinedOrUnknownSVal> DefinedSize =
1296  Size.getAs<DefinedOrUnknownSVal>()) {
1297  SValBuilder &svalBuilder = C.getSValBuilder();
1298  DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1299  DefinedOrUnknownSVal extentMatchesSize =
1300  svalBuilder.evalEQ(State, Extent, *DefinedSize);
1301 
1302  State = State->assume(extentMatchesSize, true);
1303  assert(State);
1304  }
1305 
1306  return MallocUpdateRefState(C, CE, State, Family);
1307 }
1308 
1309 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
1310  const Expr *E,
1312  AllocationFamily Family,
1313  Optional<SVal> RetVal) {
1314  if (!State)
1315  return nullptr;
1316 
1317  // Get the return value.
1318  if (!RetVal)
1319  RetVal = C.getSVal(E);
1320 
1321  // We expect the malloc functions to return a pointer.
1322  if (!RetVal->getAs<Loc>())
1323  return nullptr;
1324 
1325  SymbolRef Sym = RetVal->getAsLocSymbol();
1326  // This is a return value of a function that was not inlined, such as malloc()
1327  // or new(). We've checked that in the caller. Therefore, it must be a symbol.
1328  assert(Sym);
1329 
1330  // Set the symbol's state to Allocated.
1331  return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1332 }
1333 
1334 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1335  const CallExpr *CE,
1336  const OwnershipAttr *Att,
1337  ProgramStateRef State) const {
1338  if (!State)
1339  return nullptr;
1340 
1341  if (Att->getModule() != II_malloc)
1342  return nullptr;
1343 
1344  bool ReleasedAllocated = false;
1345 
1346  for (const auto &Arg : Att->args()) {
1347  ProgramStateRef StateI = FreeMemAux(
1348  C, CE, State, Arg.getASTIndex(),
1349  Att->getOwnKind() == OwnershipAttr::Holds, ReleasedAllocated);
1350  if (StateI)
1351  State = StateI;
1352  }
1353  return State;
1354 }
1355 
1356 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1357  const CallExpr *CE,
1359  unsigned Num,
1360  bool Hold,
1361  bool &ReleasedAllocated,
1362  bool ReturnsNullOnFailure) const {
1363  if (!State)
1364  return nullptr;
1365 
1366  if (CE->getNumArgs() < (Num + 1))
1367  return nullptr;
1368 
1369  return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
1370  ReleasedAllocated, ReturnsNullOnFailure);
1371 }
1372 
1373 /// Checks if the previous call to free on the given symbol failed - if free
1374 /// failed, returns true. Also, returns the corresponding return value symbol.
1376  SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1377  const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1378  if (Ret) {
1379  assert(*Ret && "We should not store the null return symbol");
1380  ConstraintManager &CMgr = State->getConstraintManager();
1381  ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1382  RetStatusSymbol = *Ret;
1383  return FreeFailed.isConstrainedTrue();
1384  }
1385  return false;
1386 }
1387 
1388 AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1389  const Stmt *S) const {
1390  if (!S)
1391  return AF_None;
1392 
1393  if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1394  const FunctionDecl *FD = C.getCalleeDecl(CE);
1395 
1396  if (!FD)
1397  FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1398 
1399  ASTContext &Ctx = C.getASTContext();
1400 
1401  if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1402  return AF_Malloc;
1403 
1404  if (isStandardNewDelete(FD, Ctx)) {
1406  if (Kind == OO_New || Kind == OO_Delete)
1407  return AF_CXXNew;
1408  else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1409  return AF_CXXNewArray;
1410  }
1411 
1412  if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1413  return AF_IfNameIndex;
1414 
1415  if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1416  return AF_Alloca;
1417 
1418  return AF_None;
1419  }
1420 
1421  if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1422  return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1423 
1424  if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1425  return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1426 
1427  if (isa<ObjCMessageExpr>(S))
1428  return AF_Malloc;
1429 
1430  return AF_None;
1431 }
1432 
1433 bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1434  const Expr *E) const {
1435  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1436  // FIXME: This doesn't handle indirect calls.
1437  const FunctionDecl *FD = CE->getDirectCallee();
1438  if (!FD)
1439  return false;
1440 
1441  os << *FD;
1442  if (!FD->isOverloadedOperator())
1443  os << "()";
1444  return true;
1445  }
1446 
1447  if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1448  if (Msg->isInstanceMessage())
1449  os << "-";
1450  else
1451  os << "+";
1452  Msg->getSelector().print(os);
1453  return true;
1454  }
1455 
1456  if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1457  os << "'"
1459  << "'";
1460  return true;
1461  }
1462 
1463  if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1464  os << "'"
1466  << "'";
1467  return true;
1468  }
1469 
1470  return false;
1471 }
1472 
1473 void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1474  const Expr *E) const {
1475  AllocationFamily Family = getAllocationFamily(C, E);
1476 
1477  switch(Family) {
1478  case AF_Malloc: os << "malloc()"; return;
1479  case AF_CXXNew: os << "'new'"; return;
1480  case AF_CXXNewArray: os << "'new[]'"; return;
1481  case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1482  case AF_InnerBuffer: os << "container-specific allocator"; return;
1483  case AF_Alloca:
1484  case AF_None: llvm_unreachable("not a deallocation expression");
1485  }
1486 }
1487 
1488 void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1489  AllocationFamily Family) const {
1490  switch(Family) {
1491  case AF_Malloc: os << "free()"; return;
1492  case AF_CXXNew: os << "'delete'"; return;
1493  case AF_CXXNewArray: os << "'delete[]'"; return;
1494  case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1495  case AF_InnerBuffer: os << "container-specific deallocator"; return;
1496  case AF_Alloca:
1497  case AF_None: llvm_unreachable("suspicious argument");
1498  }
1499 }
1500 
1501 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1502  const Expr *ArgExpr,
1503  const Expr *ParentExpr,
1505  bool Hold,
1506  bool &ReleasedAllocated,
1507  bool ReturnsNullOnFailure) const {
1508 
1509  if (!State)
1510  return nullptr;
1511 
1512  SVal ArgVal = C.getSVal(ArgExpr);
1513  if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1514  return nullptr;
1515  DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1516 
1517  // Check for null dereferences.
1518  if (!location.getAs<Loc>())
1519  return nullptr;
1520 
1521  // The explicit NULL case, no operation is performed.
1522  ProgramStateRef notNullState, nullState;
1523  std::tie(notNullState, nullState) = State->assume(location);
1524  if (nullState && !notNullState)
1525  return nullptr;
1526 
1527  // Unknown values could easily be okay
1528  // Undefined values are handled elsewhere
1529  if (ArgVal.isUnknownOrUndef())
1530  return nullptr;
1531 
1532  const MemRegion *R = ArgVal.getAsRegion();
1533 
1534  // Nonlocs can't be freed, of course.
1535  // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1536  if (!R) {
1537  ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1538  return nullptr;
1539  }
1540 
1541  R = R->StripCasts();
1542 
1543  // Blocks might show up as heap data, but should not be free()d
1544  if (isa<BlockDataRegion>(R)) {
1545  ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1546  return nullptr;
1547  }
1548 
1549  const MemSpaceRegion *MS = R->getMemorySpace();
1550 
1551  // Parameters, locals, statics, globals, and memory returned by
1552  // __builtin_alloca() shouldn't be freed.
1553  if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1554  // FIXME: at the time this code was written, malloc() regions were
1555  // represented by conjured symbols, which are all in UnknownSpaceRegion.
1556  // This means that there isn't actually anything from HeapSpaceRegion
1557  // that should be freed, even though we allow it here.
1558  // Of course, free() can work on memory allocated outside the current
1559  // function, so UnknownSpaceRegion is always a possibility.
1560  // False negatives are better than false positives.
1561 
1562  if (isa<AllocaRegion>(R))
1563  ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1564  else
1565  ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1566 
1567  return nullptr;
1568  }
1569 
1570  const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1571  // Various cases could lead to non-symbol values here.
1572  // For now, ignore them.
1573  if (!SrBase)
1574  return nullptr;
1575 
1576  SymbolRef SymBase = SrBase->getSymbol();
1577  const RefState *RsBase = State->get<RegionState>(SymBase);
1578  SymbolRef PreviousRetStatusSymbol = nullptr;
1579 
1580  if (RsBase) {
1581 
1582  // Memory returned by alloca() shouldn't be freed.
1583  if (RsBase->getAllocationFamily() == AF_Alloca) {
1584  ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1585  return nullptr;
1586  }
1587 
1588  // Check for double free first.
1589  if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1590  !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1591  ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1592  SymBase, PreviousRetStatusSymbol);
1593  return nullptr;
1594 
1595  // If the pointer is allocated or escaped, but we are now trying to free it,
1596  // check that the call to free is proper.
1597  } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1598  RsBase->isEscaped()) {
1599 
1600  // Check if an expected deallocation function matches the real one.
1601  bool DeallocMatchesAlloc =
1602  RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1603  if (!DeallocMatchesAlloc) {
1604  ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1605  ParentExpr, RsBase, SymBase, Hold);
1606  return nullptr;
1607  }
1608 
1609  // Check if the memory location being freed is the actual location
1610  // allocated, or an offset.
1611  RegionOffset Offset = R->getAsOffset();
1612  if (Offset.isValid() &&
1613  !Offset.hasSymbolicOffset() &&
1614  Offset.getOffset() != 0) {
1615  const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1616  ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1617  AllocExpr);
1618  return nullptr;
1619  }
1620  }
1621  }
1622 
1623  if (SymBase->getType()->isFunctionPointerType()) {
1624  ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1625  return nullptr;
1626  }
1627 
1628  ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
1629  RsBase->isAllocatedOfSizeZero());
1630 
1631  // Clean out the info on previous call to free return info.
1632  State = State->remove<FreeReturnValue>(SymBase);
1633 
1634  // Keep track of the return value. If it is NULL, we will know that free
1635  // failed.
1636  if (ReturnsNullOnFailure) {
1637  SVal RetVal = C.getSVal(ParentExpr);
1638  SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1639  if (RetStatusSymbol) {
1640  C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1641  State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1642  }
1643  }
1644 
1645  AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1646  : getAllocationFamily(C, ParentExpr);
1647  // Normal free.
1648  if (Hold)
1649  return State->set<RegionState>(SymBase,
1650  RefState::getRelinquished(Family,
1651  ParentExpr));
1652 
1653  return State->set<RegionState>(SymBase,
1654  RefState::getReleased(Family, ParentExpr));
1655 }
1656 
1658 MallocChecker::getCheckIfTracked(AllocationFamily Family,
1659  bool IsALeakCheck) const {
1660  switch (Family) {
1661  case AF_Malloc:
1662  case AF_Alloca:
1663  case AF_IfNameIndex: {
1664  if (ChecksEnabled[CK_MallocChecker])
1665  return CK_MallocChecker;
1666  return None;
1667  }
1668  case AF_CXXNew:
1669  case AF_CXXNewArray: {
1670  if (IsALeakCheck) {
1671  if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1672  return CK_NewDeleteLeaksChecker;
1673  }
1674  else {
1675  if (ChecksEnabled[CK_NewDeleteChecker])
1676  return CK_NewDeleteChecker;
1677  }
1678  return None;
1679  }
1680  case AF_InnerBuffer: {
1681  if (ChecksEnabled[CK_InnerPointerChecker])
1682  return CK_InnerPointerChecker;
1683  return None;
1684  }
1685  case AF_None: {
1686  llvm_unreachable("no family");
1687  }
1688  }
1689  llvm_unreachable("unhandled family");
1690 }
1691 
1693 MallocChecker::getCheckIfTracked(CheckerContext &C,
1694  const Stmt *AllocDeallocStmt,
1695  bool IsALeakCheck) const {
1696  return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1697  IsALeakCheck);
1698 }
1699 
1701 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1702  bool IsALeakCheck) const {
1703  if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1704  return CK_MallocChecker;
1705 
1706  const RefState *RS = C.getState()->get<RegionState>(Sym);
1707  assert(RS);
1708  return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1709 }
1710 
1711 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1712  if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1713  os << "an integer (" << IntVal->getValue() << ")";
1714  else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1715  os << "a constant address (" << ConstAddr->getValue() << ")";
1716  else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1717  os << "the address of the label '" << Label->getLabel()->getName() << "'";
1718  else
1719  return false;
1720 
1721  return true;
1722 }
1723 
1724 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1725  const MemRegion *MR) {
1726  switch (MR->getKind()) {
1727  case MemRegion::FunctionCodeRegionKind: {
1728  const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1729  if (FD)
1730  os << "the address of the function '" << *FD << '\'';
1731  else
1732  os << "the address of a function";
1733  return true;
1734  }
1735  case MemRegion::BlockCodeRegionKind:
1736  os << "block text";
1737  return true;
1738  case MemRegion::BlockDataRegionKind:
1739  // FIXME: where the block came from?
1740  os << "a block";
1741  return true;
1742  default: {
1743  const MemSpaceRegion *MS = MR->getMemorySpace();
1744 
1745  if (isa<StackLocalsSpaceRegion>(MS)) {
1746  const VarRegion *VR = dyn_cast<VarRegion>(MR);
1747  const VarDecl *VD;
1748  if (VR)
1749  VD = VR->getDecl();
1750  else
1751  VD = nullptr;
1752 
1753  if (VD)
1754  os << "the address of the local variable '" << VD->getName() << "'";
1755  else
1756  os << "the address of a local stack variable";
1757  return true;
1758  }
1759 
1760  if (isa<StackArgumentsSpaceRegion>(MS)) {
1761  const VarRegion *VR = dyn_cast<VarRegion>(MR);
1762  const VarDecl *VD;
1763  if (VR)
1764  VD = VR->getDecl();
1765  else
1766  VD = nullptr;
1767 
1768  if (VD)
1769  os << "the address of the parameter '" << VD->getName() << "'";
1770  else
1771  os << "the address of a parameter";
1772  return true;
1773  }
1774 
1775  if (isa<GlobalsSpaceRegion>(MS)) {
1776  const VarRegion *VR = dyn_cast<VarRegion>(MR);
1777  const VarDecl *VD;
1778  if (VR)
1779  VD = VR->getDecl();
1780  else
1781  VD = nullptr;
1782 
1783  if (VD) {
1784  if (VD->isStaticLocal())
1785  os << "the address of the static variable '" << VD->getName() << "'";
1786  else
1787  os << "the address of the global variable '" << VD->getName() << "'";
1788  } else
1789  os << "the address of a global variable";
1790  return true;
1791  }
1792 
1793  return false;
1794  }
1795  }
1796 }
1797 
1798 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1799  SourceRange Range,
1800  const Expr *DeallocExpr) const {
1801 
1802  if (!ChecksEnabled[CK_MallocChecker] &&
1803  !ChecksEnabled[CK_NewDeleteChecker])
1804  return;
1805 
1807  getCheckIfTracked(C, DeallocExpr);
1808  if (!CheckKind.hasValue())
1809  return;
1810 
1811  if (ExplodedNode *N = C.generateErrorNode()) {
1812  if (!BT_BadFree[*CheckKind])
1813  BT_BadFree[*CheckKind].reset(new BugType(
1814  CheckNames[*CheckKind], "Bad free", categories::MemoryError));
1815 
1816  SmallString<100> buf;
1817  llvm::raw_svector_ostream os(buf);
1818 
1819  const MemRegion *MR = ArgVal.getAsRegion();
1820  while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1821  MR = ER->getSuperRegion();
1822 
1823  os << "Argument to ";
1824  if (!printAllocDeallocName(os, C, DeallocExpr))
1825  os << "deallocator";
1826 
1827  os << " is ";
1828  bool Summarized = MR ? SummarizeRegion(os, MR)
1829  : SummarizeValue(os, ArgVal);
1830  if (Summarized)
1831  os << ", which is not memory allocated by ";
1832  else
1833  os << "not memory allocated by ";
1834 
1835  printExpectedAllocName(os, C, DeallocExpr);
1836 
1837  auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
1838  R->markInteresting(MR);
1839  R->addRange(Range);
1840  C.emitReport(std::move(R));
1841  }
1842 }
1843 
1844 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1845  SourceRange Range) const {
1846 
1848 
1849  if (ChecksEnabled[CK_MallocChecker])
1850  CheckKind = CK_MallocChecker;
1851  else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1852  CheckKind = CK_MismatchedDeallocatorChecker;
1853  else
1854  return;
1855 
1856  if (ExplodedNode *N = C.generateErrorNode()) {
1857  if (!BT_FreeAlloca[*CheckKind])
1858  BT_FreeAlloca[*CheckKind].reset(new BugType(
1859  CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
1860 
1861  auto R = llvm::make_unique<BugReport>(
1862  *BT_FreeAlloca[*CheckKind],
1863  "Memory allocated by alloca() should not be deallocated", N);
1864  R->markInteresting(ArgVal.getAsRegion());
1865  R->addRange(Range);
1866  C.emitReport(std::move(R));
1867  }
1868 }
1869 
1870 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1871  SourceRange Range,
1872  const Expr *DeallocExpr,
1873  const RefState *RS,
1874  SymbolRef Sym,
1875  bool OwnershipTransferred) const {
1876 
1877  if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1878  return;
1879 
1880  if (ExplodedNode *N = C.generateErrorNode()) {
1881  if (!BT_MismatchedDealloc)
1882  BT_MismatchedDealloc.reset(
1883  new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1884  "Bad deallocator", categories::MemoryError));
1885 
1886  SmallString<100> buf;
1887  llvm::raw_svector_ostream os(buf);
1888 
1889  const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1890  SmallString<20> AllocBuf;
1891  llvm::raw_svector_ostream AllocOs(AllocBuf);
1892  SmallString<20> DeallocBuf;
1893  llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1894 
1895  if (OwnershipTransferred) {
1896  if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1897  os << DeallocOs.str() << " cannot";
1898  else
1899  os << "Cannot";
1900 
1901  os << " take ownership of memory";
1902 
1903  if (printAllocDeallocName(AllocOs, C, AllocExpr))
1904  os << " allocated by " << AllocOs.str();
1905  } else {
1906  os << "Memory";
1907  if (printAllocDeallocName(AllocOs, C, AllocExpr))
1908  os << " allocated by " << AllocOs.str();
1909 
1910  os << " should be deallocated by ";
1911  printExpectedDeallocName(os, RS->getAllocationFamily());
1912 
1913  if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1914  os << ", not " << DeallocOs.str();
1915  }
1916 
1917  auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
1918  R->markInteresting(Sym);
1919  R->addRange(Range);
1920  R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1921  C.emitReport(std::move(R));
1922  }
1923 }
1924 
1925 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1926  SourceRange Range, const Expr *DeallocExpr,
1927  const Expr *AllocExpr) const {
1928 
1929 
1930  if (!ChecksEnabled[CK_MallocChecker] &&
1931  !ChecksEnabled[CK_NewDeleteChecker])
1932  return;
1933 
1935  getCheckIfTracked(C, AllocExpr);
1936  if (!CheckKind.hasValue())
1937  return;
1938 
1939  ExplodedNode *N = C.generateErrorNode();
1940  if (!N)
1941  return;
1942 
1943  if (!BT_OffsetFree[*CheckKind])
1944  BT_OffsetFree[*CheckKind].reset(new BugType(
1945  CheckNames[*CheckKind], "Offset free", categories::MemoryError));
1946 
1947  SmallString<100> buf;
1948  llvm::raw_svector_ostream os(buf);
1949  SmallString<20> AllocNameBuf;
1950  llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1951 
1952  const MemRegion *MR = ArgVal.getAsRegion();
1953  assert(MR && "Only MemRegion based symbols can have offset free errors");
1954 
1955  RegionOffset Offset = MR->getAsOffset();
1956  assert((Offset.isValid() &&
1957  !Offset.hasSymbolicOffset() &&
1958  Offset.getOffset() != 0) &&
1959  "Only symbols with a valid offset can have offset free errors");
1960 
1961  int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1962 
1963  os << "Argument to ";
1964  if (!printAllocDeallocName(os, C, DeallocExpr))
1965  os << "deallocator";
1966  os << " is offset by "
1967  << offsetBytes
1968  << " "
1969  << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1970  << " from the start of ";
1971  if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1972  os << "memory allocated by " << AllocNameOs.str();
1973  else
1974  os << "allocated memory";
1975 
1976  auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
1977  R->markInteresting(MR->getBaseRegion());
1978  R->addRange(Range);
1979  C.emitReport(std::move(R));
1980 }
1981 
1982 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1983  SymbolRef Sym) const {
1984 
1985  if (!ChecksEnabled[CK_MallocChecker] &&
1986  !ChecksEnabled[CK_NewDeleteChecker] &&
1987  !ChecksEnabled[CK_InnerPointerChecker])
1988  return;
1989 
1990  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1991  if (!CheckKind.hasValue())
1992  return;
1993 
1994  if (ExplodedNode *N = C.generateErrorNode()) {
1995  if (!BT_UseFree[*CheckKind])
1996  BT_UseFree[*CheckKind].reset(new BugType(
1997  CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
1998 
1999  AllocationFamily AF =
2000  C.getState()->get<RegionState>(Sym)->getAllocationFamily();
2001 
2002  auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
2003  AF == AF_InnerBuffer
2004  ? "Inner pointer of container used after re/deallocation"
2005  : "Use of memory after it is freed",
2006  N);
2007 
2008  R->markInteresting(Sym);
2009  R->addRange(Range);
2010  R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2011 
2012  if (AF == AF_InnerBuffer)
2013  R->addVisitor(allocation_state::getInnerPointerBRVisitor(Sym));
2014 
2015  C.emitReport(std::move(R));
2016  }
2017 }
2018 
2019 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
2020  bool Released, SymbolRef Sym,
2021  SymbolRef PrevSym) const {
2022 
2023  if (!ChecksEnabled[CK_MallocChecker] &&
2024  !ChecksEnabled[CK_NewDeleteChecker])
2025  return;
2026 
2027  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2028  if (!CheckKind.hasValue())
2029  return;
2030 
2031  if (ExplodedNode *N = C.generateErrorNode()) {
2032  if (!BT_DoubleFree[*CheckKind])
2033  BT_DoubleFree[*CheckKind].reset(new BugType(
2034  CheckNames[*CheckKind], "Double free", categories::MemoryError));
2035 
2036  auto R = llvm::make_unique<BugReport>(
2037  *BT_DoubleFree[*CheckKind],
2038  (Released ? "Attempt to free released memory"
2039  : "Attempt to free non-owned memory"),
2040  N);
2041  R->addRange(Range);
2042  R->markInteresting(Sym);
2043  if (PrevSym)
2044  R->markInteresting(PrevSym);
2045  R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2046  C.emitReport(std::move(R));
2047  }
2048 }
2049 
2050 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2051 
2052  if (!ChecksEnabled[CK_NewDeleteChecker])
2053  return;
2054 
2055  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2056  if (!CheckKind.hasValue())
2057  return;
2058 
2059  if (ExplodedNode *N = C.generateErrorNode()) {
2060  if (!BT_DoubleDelete)
2061  BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
2062  "Double delete",
2064 
2065  auto R = llvm::make_unique<BugReport>(
2066  *BT_DoubleDelete, "Attempt to delete released memory", N);
2067 
2068  R->markInteresting(Sym);
2069  R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2070  C.emitReport(std::move(R));
2071  }
2072 }
2073 
2074 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2075  SourceRange Range,
2076  SymbolRef Sym) const {
2077 
2078  if (!ChecksEnabled[CK_MallocChecker] &&
2079  !ChecksEnabled[CK_NewDeleteChecker])
2080  return;
2081 
2082  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2083 
2084  if (!CheckKind.hasValue())
2085  return;
2086 
2087  if (ExplodedNode *N = C.generateErrorNode()) {
2088  if (!BT_UseZerroAllocated[*CheckKind])
2089  BT_UseZerroAllocated[*CheckKind].reset(
2090  new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2092 
2093  auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2094  "Use of zero-allocated memory", N);
2095 
2096  R->addRange(Range);
2097  if (Sym) {
2098  R->markInteresting(Sym);
2099  R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2100  }
2101  C.emitReport(std::move(R));
2102  }
2103 }
2104 
2105 void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2106  SourceRange Range,
2107  const Expr *FreeExpr) const {
2108  if (!ChecksEnabled[CK_MallocChecker])
2109  return;
2110 
2111  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2112  if (!CheckKind.hasValue())
2113  return;
2114 
2115  if (ExplodedNode *N = C.generateErrorNode()) {
2116  if (!BT_BadFree[*CheckKind])
2117  BT_BadFree[*CheckKind].reset(new BugType(
2118  CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2119 
2120  SmallString<100> Buf;
2121  llvm::raw_svector_ostream Os(Buf);
2122 
2123  const MemRegion *MR = ArgVal.getAsRegion();
2124  while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2125  MR = ER->getSuperRegion();
2126 
2127  Os << "Argument to ";
2128  if (!printAllocDeallocName(Os, C, FreeExpr))
2129  Os << "deallocator";
2130 
2131  Os << " is a function pointer";
2132 
2133  auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2134  R->markInteresting(MR);
2135  R->addRange(Range);
2136  C.emitReport(std::move(R));
2137  }
2138 }
2139 
2140 ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2141  const CallExpr *CE,
2142  bool FreesOnFail,
2144  bool SuffixWithN) const {
2145  if (!State)
2146  return nullptr;
2147 
2148  if (SuffixWithN && CE->getNumArgs() < 3)
2149  return nullptr;
2150  else if (CE->getNumArgs() < 2)
2151  return nullptr;
2152 
2153  const Expr *arg0Expr = CE->getArg(0);
2154  SVal Arg0Val = C.getSVal(arg0Expr);
2155  if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2156  return nullptr;
2157  DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2158 
2159  SValBuilder &svalBuilder = C.getSValBuilder();
2160 
2161  DefinedOrUnknownSVal PtrEQ =
2162  svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
2163 
2164  // Get the size argument.
2165  const Expr *Arg1 = CE->getArg(1);
2166 
2167  // Get the value of the size argument.
2168  SVal TotalSize = C.getSVal(Arg1);
2169  if (SuffixWithN)
2170  TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2171  if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2172  return nullptr;
2173 
2174  // Compare the size argument to 0.
2175  DefinedOrUnknownSVal SizeZero =
2176  svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2177  svalBuilder.makeIntValWithPtrWidth(0, false));
2178 
2179  ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2180  std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2181  ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2182  std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2183  // We only assume exceptional states if they are definitely true; if the
2184  // state is under-constrained, assume regular realloc behavior.
2185  bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2186  bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2187 
2188  // If the ptr is NULL and the size is not 0, the call is equivalent to
2189  // malloc(size).
2190  if (PrtIsNull && !SizeIsZero) {
2191  ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
2192  UndefinedVal(), StatePtrIsNull);
2193  return stateMalloc;
2194  }
2195 
2196  if (PrtIsNull && SizeIsZero)
2197  return State;
2198 
2199  // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2200  assert(!PrtIsNull);
2201  SymbolRef FromPtr = arg0Val.getAsSymbol();
2202  SVal RetVal = C.getSVal(CE);
2203  SymbolRef ToPtr = RetVal.getAsSymbol();
2204  if (!FromPtr || !ToPtr)
2205  return nullptr;
2206 
2207  bool ReleasedAllocated = false;
2208 
2209  // If the size is 0, free the memory.
2210  if (SizeIsZero)
2211  if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2212  false, ReleasedAllocated)){
2213  // The semantics of the return value are:
2214  // If size was equal to 0, either NULL or a pointer suitable to be passed
2215  // to free() is returned. We just free the input pointer and do not add
2216  // any constrains on the output pointer.
2217  return stateFree;
2218  }
2219 
2220  // Default behavior.
2221  if (ProgramStateRef stateFree =
2222  FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
2223 
2224  ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
2225  UnknownVal(), stateFree);
2226  if (!stateRealloc)
2227  return nullptr;
2228 
2229  ReallocPairKind Kind = RPToBeFreedAfterFailure;
2230  if (FreesOnFail)
2231  Kind = RPIsFreeOnFailure;
2232  else if (!ReleasedAllocated)
2233  Kind = RPDoNotTrackAfterFailure;
2234 
2235  // Record the info about the reallocated symbol so that we could properly
2236  // process failed reallocation.
2237  stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2238  ReallocPair(FromPtr, Kind));
2239  // The reallocated symbol should stay alive for as long as the new symbol.
2240  C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2241  return stateRealloc;
2242  }
2243  return nullptr;
2244 }
2245 
2246 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
2248  if (!State)
2249  return nullptr;
2250 
2251  if (CE->getNumArgs() < 2)
2252  return nullptr;
2253 
2254  SValBuilder &svalBuilder = C.getSValBuilder();
2255  SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2256  SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
2257 
2258  return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2259 }
2260 
2261 LeakInfo
2262 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2263  CheckerContext &C) const {
2264  const LocationContext *LeakContext = N->getLocationContext();
2265  // Walk the ExplodedGraph backwards and find the first node that referred to
2266  // the tracked symbol.
2267  const ExplodedNode *AllocNode = N;
2268  const MemRegion *ReferenceRegion = nullptr;
2269 
2270  while (N) {
2271  ProgramStateRef State = N->getState();
2272  if (!State->get<RegionState>(Sym))
2273  break;
2274 
2275  // Find the most recent expression bound to the symbol in the current
2276  // context.
2277  if (!ReferenceRegion) {
2278  if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2279  SVal Val = State->getSVal(MR);
2280  if (Val.getAsLocSymbol() == Sym) {
2281  const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
2282  // Do not show local variables belonging to a function other than
2283  // where the error is reported.
2284  if (!VR ||
2285  (VR->getStackFrame() == LeakContext->getStackFrame()))
2286  ReferenceRegion = MR;
2287  }
2288  }
2289  }
2290 
2291  // Allocation node, is the last node in the current or parent context in
2292  // which the symbol was tracked.
2293  const LocationContext *NContext = N->getLocationContext();
2294  if (NContext == LeakContext ||
2295  NContext->isParentOf(LeakContext))
2296  AllocNode = N;
2297  N = N->pred_empty() ? nullptr : *(N->pred_begin());
2298  }
2299 
2300  return LeakInfo(AllocNode, ReferenceRegion);
2301 }
2302 
2303 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2304  CheckerContext &C) const {
2305 
2306  if (!ChecksEnabled[CK_MallocChecker] &&
2307  !ChecksEnabled[CK_NewDeleteLeaksChecker])
2308  return;
2309 
2310  const RefState *RS = C.getState()->get<RegionState>(Sym);
2311  assert(RS && "cannot leak an untracked symbol");
2312  AllocationFamily Family = RS->getAllocationFamily();
2313 
2314  if (Family == AF_Alloca)
2315  return;
2316 
2318  CheckKind = getCheckIfTracked(Family, true);
2319 
2320  if (!CheckKind.hasValue())
2321  return;
2322 
2323  assert(N);
2324  if (!BT_Leak[*CheckKind]) {
2325  BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2327  // Leaks should not be reported if they are post-dominated by a sink:
2328  // (1) Sinks are higher importance bugs.
2329  // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2330  // with __noreturn functions such as assert() or exit(). We choose not
2331  // to report leaks on such paths.
2332  BT_Leak[*CheckKind]->setSuppressOnSink(true);
2333  }
2334 
2335  // Most bug reports are cached at the location where they occurred.
2336  // With leaks, we want to unique them by the location where they were
2337  // allocated, and only report a single path.
2338  PathDiagnosticLocation LocUsedForUniqueing;
2339  const ExplodedNode *AllocNode = nullptr;
2340  const MemRegion *Region = nullptr;
2341  std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2342 
2343  const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
2344  if (AllocationStmt)
2345  LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2346  C.getSourceManager(),
2347  AllocNode->getLocationContext());
2348 
2349  SmallString<200> buf;
2350  llvm::raw_svector_ostream os(buf);
2351  if (Region && Region->canPrintPretty()) {
2352  os << "Potential leak of memory pointed to by ";
2353  Region->printPretty(os);
2354  } else {
2355  os << "Potential memory leak";
2356  }
2357 
2358  auto R = llvm::make_unique<BugReport>(
2359  *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2360  AllocNode->getLocationContext()->getDecl());
2361  R->markInteresting(Sym);
2362  R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
2363  C.emitReport(std::move(R));
2364 }
2365 
2366 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2367  CheckerContext &C) const
2368 {
2369  if (!SymReaper.hasDeadSymbols())
2370  return;
2371 
2372  ProgramStateRef state = C.getState();
2373  RegionStateTy RS = state->get<RegionState>();
2374  RegionStateTy::Factory &F = state->get_context<RegionState>();
2375 
2377  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2378  if (SymReaper.isDead(I->first)) {
2379  if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2380  Errors.push_back(I->first);
2381  // Remove the dead symbol from the map.
2382  RS = F.remove(RS, I->first);
2383 
2384  }
2385  }
2386 
2387  // Cleanup the Realloc Pairs Map.
2388  ReallocPairsTy RP = state->get<ReallocPairs>();
2389  for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2390  if (SymReaper.isDead(I->first) ||
2391  SymReaper.isDead(I->second.ReallocatedSym)) {
2392  state = state->remove<ReallocPairs>(I->first);
2393  }
2394  }
2395 
2396  // Cleanup the FreeReturnValue Map.
2397  FreeReturnValueTy FR = state->get<FreeReturnValue>();
2398  for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2399  if (SymReaper.isDead(I->first) ||
2400  SymReaper.isDead(I->second)) {
2401  state = state->remove<FreeReturnValue>(I->first);
2402  }
2403  }
2404 
2405  // Generate leak node.
2406  ExplodedNode *N = C.getPredecessor();
2407  if (!Errors.empty()) {
2408  static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2409  N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2410  if (N) {
2412  I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2413  reportLeak(*I, N, C);
2414  }
2415  }
2416  }
2417 
2418  C.addTransition(state->set<RegionState>(RS), N);
2419 }
2420 
2421 void MallocChecker::checkPreCall(const CallEvent &Call,
2422  CheckerContext &C) const {
2423 
2424  if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2425  SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2426  if (!Sym || checkDoubleDelete(Sym, C))
2427  return;
2428  }
2429 
2430  // We will check for double free in the post visit.
2431  if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2432  const FunctionDecl *FD = FC->getDecl();
2433  if (!FD)
2434  return;
2435 
2436  ASTContext &Ctx = C.getASTContext();
2437  if (ChecksEnabled[CK_MallocChecker] &&
2438  (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2439  isCMemFunction(FD, Ctx, AF_IfNameIndex,
2440  MemoryOperationKind::MOK_Free)))
2441  return;
2442 
2443  if (ChecksEnabled[CK_NewDeleteChecker] &&
2444  isStandardNewDelete(FD, Ctx))
2445  return;
2446  }
2447 
2448  // Check if the callee of a method is deleted.
2449  if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2450  SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2451  if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2452  return;
2453  }
2454 
2455  // Check arguments for being used after free.
2456  for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2457  SVal ArgSVal = Call.getArgSVal(I);
2458  if (ArgSVal.getAs<Loc>()) {
2459  SymbolRef Sym = ArgSVal.getAsSymbol();
2460  if (!Sym)
2461  continue;
2462  if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2463  return;
2464  }
2465  }
2466 }
2467 
2468 void MallocChecker::checkPreStmt(const ReturnStmt *S,
2469  CheckerContext &C) const {
2470  checkEscapeOnReturn(S, C);
2471 }
2472 
2473 // In the CFG, automatic destructors come after the return statement.
2474 // This callback checks for returning memory that is freed by automatic
2475 // destructors, as those cannot be reached in checkPreStmt().
2476 void MallocChecker::checkEndFunction(const ReturnStmt *S,
2477  CheckerContext &C) const {
2478  checkEscapeOnReturn(S, C);
2479 }
2480 
2481 void MallocChecker::checkEscapeOnReturn(const ReturnStmt *S,
2482  CheckerContext &C) const {
2483  if (!S)
2484  return;
2485 
2486  const Expr *E = S->getRetValue();
2487  if (!E)
2488  return;
2489 
2490  // Check if we are returning a symbol.
2491  ProgramStateRef State = C.getState();
2492  SVal RetVal = C.getSVal(E);
2493  SymbolRef Sym = RetVal.getAsSymbol();
2494  if (!Sym)
2495  // If we are returning a field of the allocated struct or an array element,
2496  // the callee could still free the memory.
2497  // TODO: This logic should be a part of generic symbol escape callback.
2498  if (const MemRegion *MR = RetVal.getAsRegion())
2499  if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2500  if (const SymbolicRegion *BMR =
2501  dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2502  Sym = BMR->getSymbol();
2503 
2504  // Check if we are returning freed memory.
2505  if (Sym)
2506  checkUseAfterFree(Sym, C, E);
2507 }
2508 
2509 // TODO: Blocks should be either inlined or should call invalidate regions
2510 // upon invocation. After that's in place, special casing here will not be
2511 // needed.
2512 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2513  CheckerContext &C) const {
2514 
2515  // Scan the BlockDecRefExprs for any object the retain count checker
2516  // may be tracking.
2517  if (!BE->getBlockDecl()->hasCaptures())
2518  return;
2519 
2520  ProgramStateRef state = C.getState();
2521  const BlockDataRegion *R =
2522  cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
2523 
2524  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2525  E = R->referenced_vars_end();
2526 
2527  if (I == E)
2528  return;
2529 
2531  const LocationContext *LC = C.getLocationContext();
2532  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2533 
2534  for ( ; I != E; ++I) {
2535  const VarRegion *VR = I.getCapturedRegion();
2536  if (VR->getSuperRegion() == R) {
2537  VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2538  }
2539  Regions.push_back(VR);
2540  }
2541 
2542  state =
2543  state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2544  Regions.data() + Regions.size()).getState();
2545  C.addTransition(state);
2546 }
2547 
2548 bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2549  assert(Sym);
2550  const RefState *RS = C.getState()->get<RegionState>(Sym);
2551  return (RS && RS->isReleased());
2552 }
2553 
2554 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2555  const Stmt *S) const {
2556 
2557  if (isReleased(Sym, C)) {
2558  ReportUseAfterFree(C, S->getSourceRange(), Sym);
2559  return true;
2560  }
2561 
2562  return false;
2563 }
2564 
2565 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2566  const Stmt *S) const {
2567  assert(Sym);
2568 
2569  if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2570  if (RS->isAllocatedOfSizeZero())
2571  ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2572  }
2573  else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2574  ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2575  }
2576 }
2577 
2578 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2579 
2580  if (isReleased(Sym, C)) {
2581  ReportDoubleDelete(C, Sym);
2582  return true;
2583  }
2584  return false;
2585 }
2586 
2587 // Check if the location is a freed symbolic region.
2588 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2589  CheckerContext &C) const {
2590  SymbolRef Sym = l.getLocSymbolInBase();
2591  if (Sym) {
2592  checkUseAfterFree(Sym, C, S);
2593  checkUseZeroAllocated(Sym, C, S);
2594  }
2595 }
2596 
2597 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2598 // it - assuming that allocation failed on this path.
2599 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2600  SVal Cond,
2601  bool Assumption) const {
2602  RegionStateTy RS = state->get<RegionState>();
2603  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2604  // If the symbol is assumed to be NULL, remove it from consideration.
2605  ConstraintManager &CMgr = state->getConstraintManager();
2606  ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2607  if (AllocFailed.isConstrainedTrue())
2608  state = state->remove<RegionState>(I.getKey());
2609  }
2610 
2611  // Realloc returns 0 when reallocation fails, which means that we should
2612  // restore the state of the pointer being reallocated.
2613  ReallocPairsTy RP = state->get<ReallocPairs>();
2614  for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2615  // If the symbol is assumed to be NULL, remove it from consideration.
2616  ConstraintManager &CMgr = state->getConstraintManager();
2617  ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2618  if (!AllocFailed.isConstrainedTrue())
2619  continue;
2620 
2621  SymbolRef ReallocSym = I.getData().ReallocatedSym;
2622  if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2623  if (RS->isReleased()) {
2624  if (I.getData().Kind == RPToBeFreedAfterFailure)
2625  state = state->set<RegionState>(ReallocSym,
2626  RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2627  else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2628  state = state->remove<RegionState>(ReallocSym);
2629  else
2630  assert(I.getData().Kind == RPIsFreeOnFailure);
2631  }
2632  }
2633  state = state->remove<ReallocPairs>(I.getKey());
2634  }
2635 
2636  return state;
2637 }
2638 
2639 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2640  const CallEvent *Call,
2642  SymbolRef &EscapingSymbol) const {
2643  assert(Call);
2644  EscapingSymbol = nullptr;
2645 
2646  // For now, assume that any C++ or block call can free memory.
2647  // TODO: If we want to be more optimistic here, we'll need to make sure that
2648  // regions escape to C++ containers. They seem to do that even now, but for
2649  // mysterious reasons.
2650  if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2651  return true;
2652 
2653  // Check Objective-C messages by selector name.
2654  if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2655  // If it's not a framework call, or if it takes a callback, assume it
2656  // can free memory.
2657  if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2658  return true;
2659 
2660  // If it's a method we know about, handle it explicitly post-call.
2661  // This should happen before the "freeWhenDone" check below.
2662  if (isKnownDeallocObjCMethodName(*Msg))
2663  return false;
2664 
2665  // If there's a "freeWhenDone" parameter, but the method isn't one we know
2666  // about, we can't be sure that the object will use free() to deallocate the
2667  // memory, so we can't model it explicitly. The best we can do is use it to
2668  // decide whether the pointer escapes.
2669  if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2670  return *FreeWhenDone;
2671 
2672  // If the first selector piece ends with "NoCopy", and there is no
2673  // "freeWhenDone" parameter set to zero, we know ownership is being
2674  // transferred. Again, though, we can't be sure that the object will use
2675  // free() to deallocate the memory, so we can't model it explicitly.
2676  StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2677  if (FirstSlot.endswith("NoCopy"))
2678  return true;
2679 
2680  // If the first selector starts with addPointer, insertPointer,
2681  // or replacePointer, assume we are dealing with NSPointerArray or similar.
2682  // This is similar to C++ containers (vector); we still might want to check
2683  // that the pointers get freed by following the container itself.
2684  if (FirstSlot.startswith("addPointer") ||
2685  FirstSlot.startswith("insertPointer") ||
2686  FirstSlot.startswith("replacePointer") ||
2687  FirstSlot.equals("valueWithPointer")) {
2688  return true;
2689  }
2690 
2691  // We should escape receiver on call to 'init'. This is especially relevant
2692  // to the receiver, as the corresponding symbol is usually not referenced
2693  // after the call.
2694  if (Msg->getMethodFamily() == OMF_init) {
2695  EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2696  return true;
2697  }
2698 
2699  // Otherwise, assume that the method does not free memory.
2700  // Most framework methods do not free memory.
2701  return false;
2702  }
2703 
2704  // At this point the only thing left to handle is straight function calls.
2705  const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2706  if (!FD)
2707  return true;
2708 
2709  ASTContext &ASTC = State->getStateManager().getContext();
2710 
2711  // If it's one of the allocation functions we can reason about, we model
2712  // its behavior explicitly.
2713  if (isMemFunction(FD, ASTC))
2714  return false;
2715 
2716  // If it's not a system call, assume it frees memory.
2717  if (!Call->isInSystemHeader())
2718  return true;
2719 
2720  // White list the system functions whose arguments escape.
2721  const IdentifierInfo *II = FD->getIdentifier();
2722  if (!II)
2723  return true;
2724  StringRef FName = II->getName();
2725 
2726  // White list the 'XXXNoCopy' CoreFoundation functions.
2727  // We specifically check these before
2728  if (FName.endswith("NoCopy")) {
2729  // Look for the deallocator argument. We know that the memory ownership
2730  // is not transferred only if the deallocator argument is
2731  // 'kCFAllocatorNull'.
2732  for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2733  const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2734  if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2735  StringRef DeallocatorName = DE->getFoundDecl()->getName();
2736  if (DeallocatorName == "kCFAllocatorNull")
2737  return false;
2738  }
2739  }
2740  return true;
2741  }
2742 
2743  // Associating streams with malloced buffers. The pointer can escape if
2744  // 'closefn' is specified (and if that function does free memory),
2745  // but it will not if closefn is not specified.
2746  // Currently, we do not inspect the 'closefn' function (PR12101).
2747  if (FName == "funopen")
2748  if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2749  return false;
2750 
2751  // Do not warn on pointers passed to 'setbuf' when used with std streams,
2752  // these leaks might be intentional when setting the buffer for stdio.
2753  // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2754  if (FName == "setbuf" || FName =="setbuffer" ||
2755  FName == "setlinebuf" || FName == "setvbuf") {
2756  if (Call->getNumArgs() >= 1) {
2757  const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2758  if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2759  if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2760  if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2761  return true;
2762  }
2763  }
2764 
2765  // A bunch of other functions which either take ownership of a pointer or
2766  // wrap the result up in a struct or object, meaning it can be freed later.
2767  // (See RetainCountChecker.) Not all the parameters here are invalidated,
2768  // but the Malloc checker cannot differentiate between them. The right way
2769  // of doing this would be to implement a pointer escapes callback.
2770  if (FName == "CGBitmapContextCreate" ||
2771  FName == "CGBitmapContextCreateWithData" ||
2772  FName == "CVPixelBufferCreateWithBytes" ||
2773  FName == "CVPixelBufferCreateWithPlanarBytes" ||
2774  FName == "OSAtomicEnqueue") {
2775  return true;
2776  }
2777 
2778  if (FName == "postEvent" &&
2779  FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2780  return true;
2781  }
2782 
2783  if (FName == "postEvent" &&
2784  FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2785  return true;
2786  }
2787 
2788  if (FName == "connectImpl" &&
2789  FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2790  return true;
2791  }
2792 
2793  // Handle cases where we know a buffer's /address/ can escape.
2794  // Note that the above checks handle some special cases where we know that
2795  // even though the address escapes, it's still our responsibility to free the
2796  // buffer.
2797  if (Call->argumentsMayEscape())
2798  return true;
2799 
2800  // Otherwise, assume that the function does not free memory.
2801  // Most system calls do not free the memory.
2802  return false;
2803 }
2804 
2805 static bool retTrue(const RefState *RS) {
2806  return true;
2807 }
2808 
2809 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2810  return (RS->getAllocationFamily() == AF_CXXNewArray ||
2811  RS->getAllocationFamily() == AF_CXXNew);
2812 }
2813 
2814 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2815  const InvalidatedSymbols &Escaped,
2816  const CallEvent *Call,
2817  PointerEscapeKind Kind) const {
2818  return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2819 }
2820 
2821 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2822  const InvalidatedSymbols &Escaped,
2823  const CallEvent *Call,
2824  PointerEscapeKind Kind) const {
2825  return checkPointerEscapeAux(State, Escaped, Call, Kind,
2827 }
2828 
2829 ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2830  const InvalidatedSymbols &Escaped,
2831  const CallEvent *Call,
2833  bool(*CheckRefState)(const RefState*)) const {
2834  // If we know that the call does not free memory, or we want to process the
2835  // call later, keep tracking the top level arguments.
2836  SymbolRef EscapingSymbol = nullptr;
2837  if (Kind == PSK_DirectEscapeOnCall &&
2838  !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2839  EscapingSymbol) &&
2840  !EscapingSymbol) {
2841  return State;
2842  }
2843 
2844  for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2845  E = Escaped.end();
2846  I != E; ++I) {
2847  SymbolRef sym = *I;
2848 
2849  if (EscapingSymbol && EscapingSymbol != sym)
2850  continue;
2851 
2852  if (const RefState *RS = State->get<RegionState>(sym)) {
2853  if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2854  CheckRefState(RS)) {
2855  State = State->remove<RegionState>(sym);
2856  State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2857  }
2858  }
2859  }
2860  return State;
2861 }
2862 
2864  ProgramStateRef prevState) {
2865  ReallocPairsTy currMap = currState->get<ReallocPairs>();
2866  ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2867 
2868  for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2869  I != E; ++I) {
2870  SymbolRef sym = I.getKey();
2871  if (!currMap.lookup(sym))
2872  return sym;
2873  }
2874 
2875  return nullptr;
2876 }
2877 
2879  if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
2880  StringRef N = II->getName();
2881  if (N.contains_lower("ptr") || N.contains_lower("pointer")) {
2882  if (N.contains_lower("ref") || N.contains_lower("cnt") ||
2883  N.contains_lower("intrusive") || N.contains_lower("shared")) {
2884  return true;
2885  }
2886  }
2887  }
2888  return false;
2889 }
2890 
2891 std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2892  const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2893  BugReport &BR) {
2894 
2895  ProgramStateRef state = N->getState();
2896  ProgramStateRef statePrev = PrevN->getState();
2897 
2898  const RefState *RS = state->get<RegionState>(Sym);
2899  const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2900 
2901  const Stmt *S = PathDiagnosticLocation::getStmt(N);
2902  // When dealing with containers, we sometimes want to give a note
2903  // even if the statement is missing.
2904  if (!S && (!RS || RS->getAllocationFamily() != AF_InnerBuffer))
2905  return nullptr;
2906 
2907  const LocationContext *CurrentLC = N->getLocationContext();
2908 
2909  // If we find an atomic fetch_add or fetch_sub within the destructor in which
2910  // the pointer was released (before the release), this is likely a destructor
2911  // of a shared pointer.
2912  // Because we don't model atomics, and also because we don't know that the
2913  // original reference count is positive, we should not report use-after-frees
2914  // on objects deleted in such destructors. This can probably be improved
2915  // through better shared pointer modeling.
2916  if (ReleaseDestructorLC) {
2917  if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
2918  AtomicExpr::AtomicOp Op = AE->getOp();
2919  if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
2920  Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
2921  if (ReleaseDestructorLC == CurrentLC ||
2922  ReleaseDestructorLC->isParentOf(CurrentLC)) {
2923  BR.markInvalid(getTag(), S);
2924  }
2925  }
2926  }
2927  }
2928 
2929  // FIXME: We will eventually need to handle non-statement-based events
2930  // (__attribute__((cleanup))).
2931 
2932  // Find out if this is an interesting point and what is the kind.
2933  StringRef Msg;
2934  StackHintGeneratorForSymbol *StackHint = nullptr;
2935  SmallString<256> Buf;
2936  llvm::raw_svector_ostream OS(Buf);
2937 
2938  if (Mode == Normal) {
2939  if (isAllocated(RS, RSPrev, S)) {
2940  Msg = "Memory is allocated";
2941  StackHint = new StackHintGeneratorForSymbol(Sym,
2942  "Returned allocated memory");
2943  } else if (isReleased(RS, RSPrev, S)) {
2944  const auto Family = RS->getAllocationFamily();
2945  switch (Family) {
2946  case AF_Alloca:
2947  case AF_Malloc:
2948  case AF_CXXNew:
2949  case AF_CXXNewArray:
2950  case AF_IfNameIndex:
2951  Msg = "Memory is released";
2952  StackHint = new StackHintGeneratorForSymbol(Sym,
2953  "Returning; memory was released");
2954  break;
2955  case AF_InnerBuffer: {
2956  const MemRegion *ObjRegion =
2958  const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
2959  QualType ObjTy = TypedRegion->getValueType();
2960  OS << "Inner buffer of '" << ObjTy.getAsString() << "' ";
2961 
2962  if (N->getLocation().getKind() == ProgramPoint::PostImplicitCallKind) {
2963  OS << "deallocated by call to destructor";
2964  StackHint = new StackHintGeneratorForSymbol(Sym,
2965  "Returning; inner buffer was deallocated");
2966  } else {
2967  OS << "reallocated by call to '";
2968  const Stmt *S = RS->getStmt();
2969  if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
2970  OS << MemCallE->getMethodDecl()->getNameAsString();
2971  } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
2972  OS << OpCallE->getDirectCallee()->getNameAsString();
2973  } else if (const auto *CallE = dyn_cast<CallExpr>(S)) {
2974  auto &CEMgr = BRC.getStateManager().getCallEventManager();
2975  CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC);
2976  const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl());
2977  OS << (D ? D->getNameAsString() : "unknown");
2978  }
2979  OS << "'";
2980  StackHint = new StackHintGeneratorForSymbol(Sym,
2981  "Returning; inner buffer was reallocated");
2982  }
2983  Msg = OS.str();
2984  break;
2985  }
2986  case AF_None:
2987  llvm_unreachable("Unhandled allocation family!");
2988  }
2989 
2990  // See if we're releasing memory while inlining a destructor
2991  // (or one of its callees). This turns on various common
2992  // false positive suppressions.
2993  bool FoundAnyDestructor = false;
2994  for (const LocationContext *LC = CurrentLC; LC; LC = LC->getParent()) {
2995  if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
2997  // This immediately looks like a reference-counting destructor.
2998  // We're bad at guessing the original reference count of the object,
2999  // so suppress the report for now.
3000  BR.markInvalid(getTag(), DD);
3001  } else if (!FoundAnyDestructor) {
3002  assert(!ReleaseDestructorLC &&
3003  "There can be only one release point!");
3004  // Suspect that it's a reference counting pointer destructor.
3005  // On one of the next nodes might find out that it has atomic
3006  // reference counting operations within it (see the code above),
3007  // and if so, we'd conclude that it likely is a reference counting
3008  // pointer destructor.
3009  ReleaseDestructorLC = LC->getStackFrame();
3010  // It is unlikely that releasing memory is delegated to a destructor
3011  // inside a destructor of a shared pointer, because it's fairly hard
3012  // to pass the information that the pointer indeed needs to be
3013  // released into it. So we're only interested in the innermost
3014  // destructor.
3015  FoundAnyDestructor = true;
3016  }
3017  }
3018  }
3019  } else if (isRelinquished(RS, RSPrev, S)) {
3020  Msg = "Memory ownership is transferred";
3021  StackHint = new StackHintGeneratorForSymbol(Sym, "");
3022  } else if (isReallocFailedCheck(RS, RSPrev, S)) {
3023  Mode = ReallocationFailed;
3024  Msg = "Reallocation failed";
3025  StackHint = new StackHintGeneratorForReallocationFailed(Sym,
3026  "Reallocation failed");
3027 
3028  if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
3029  // Is it possible to fail two reallocs WITHOUT testing in between?
3030  assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
3031  "We only support one failed realloc at a time.");
3032  BR.markInteresting(sym);
3033  FailedReallocSymbol = sym;
3034  }
3035  }
3036 
3037  // We are in a special mode if a reallocation failed later in the path.
3038  } else if (Mode == ReallocationFailed) {
3039  assert(FailedReallocSymbol && "No symbol to look for.");
3040 
3041  // Is this is the first appearance of the reallocated symbol?
3042  if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
3043  // We're at the reallocation point.
3044  Msg = "Attempt to reallocate memory";
3045  StackHint = new StackHintGeneratorForSymbol(Sym,
3046  "Returned reallocated memory");
3047  FailedReallocSymbol = nullptr;
3048  Mode = Normal;
3049  }
3050  }
3051 
3052  if (Msg.empty())
3053  return nullptr;
3054  assert(StackHint);
3055 
3056  // Generate the extra diagnostic.
3057  PathDiagnosticLocation Pos;
3058  if (!S) {
3059  assert(RS->getAllocationFamily() == AF_InnerBuffer);
3060  auto PostImplCall = N->getLocation().getAs<PostImplicitCall>();
3061  if (!PostImplCall)
3062  return nullptr;
3063  Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3064  BRC.getSourceManager());
3065  } else {
3066  Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3067  N->getLocationContext());
3068  }
3069 
3070  return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
3071 }
3072 
3073 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
3074  const char *NL, const char *Sep) const {
3075 
3076  RegionStateTy RS = State->get<RegionState>();
3077 
3078  if (!RS.isEmpty()) {
3079  Out << Sep << "MallocChecker :" << NL;
3080  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
3081  const RefState *RefS = State->get<RegionState>(I.getKey());
3082  AllocationFamily Family = RefS->getAllocationFamily();
3083  Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
3084  if (!CheckKind.hasValue())
3085  CheckKind = getCheckIfTracked(Family, true);
3086 
3087  I.getKey()->dumpToStream(Out);
3088  Out << " : ";
3089  I.getData().dump(Out);
3090  if (CheckKind.hasValue())
3091  Out << " (" << CheckNames[*CheckKind].getName() << ")";
3092  Out << NL;
3093  }
3094  }
3095 }
3096 
3097 namespace clang {
3098 namespace ento {
3099 namespace allocation_state {
3100 
3103  AllocationFamily Family = AF_InnerBuffer;
3104  return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3105 }
3106 
3107 } // end namespace allocation_state
3108 } // end namespace ento
3109 } // end namespace clang
3110 
3111 void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
3113  MallocChecker *checker = mgr.registerChecker<MallocChecker>();
3114  checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
3115  "Optimistic", false, checker);
3116  checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
3117  checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
3118  mgr.getCurrentCheckName();
3119  // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
3120  // checker.
3121  if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) {
3122  checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
3123  // FIXME: This does not set the correct name, but without this workaround
3124  // no name will be set at all.
3125  checker->CheckNames[MallocChecker::CK_NewDeleteChecker] =
3126  mgr.getCurrentCheckName();
3127  }
3128 }
3129 
3130 // Intended to be used in InnerPointerChecker to register the part of
3131 // MallocChecker connected to it.
3134  MallocChecker *checker = mgr.registerChecker<MallocChecker>();
3135  checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
3136  "Optimistic", false, checker);
3137  checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] = true;
3138  checker->CheckNames[MallocChecker::CK_InnerPointerChecker] =
3139  mgr.getCurrentCheckName();
3140 }
3141 
3142 #define REGISTER_CHECKER(name) \
3143  void ento::register##name(CheckerManager &mgr) { \
3144  registerCStringCheckerBasic(mgr); \
3145  MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
3146  checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
3147  "Optimistic", false, checker); \
3148  checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
3149  checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
3150  }
3151 
3152 REGISTER_CHECKER(MallocChecker)
3153 REGISTER_CHECKER(NewDeleteChecker)
3154 REGISTER_CHECKER(MismatchedDeallocatorChecker)
const BlockDecl * getBlockDecl() const
Definition: Expr.h:4988
Represents a function declaration or definition.
Definition: Decl.h:1717
Smart pointer class that efficiently represents Objective-C method names.
A (possibly-)qualified type.
Definition: Type.h:642
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2354
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition: Decl.h:3946
bool operator==(CanQual< T > x, CanQual< U > y)
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition: Store.h:52
const SymExpr * SymbolRef
Stmt - This represents one statement.
Definition: Stmt.h:66
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2342
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:497
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:949
Defines the SourceManager interface.
void registerInnerPointerCheckerAux(CheckerManager &Mgr)
Register the part of MallocChecker connected to InnerPointerChecker.
__DEVICE__ long long abs(long long __n)
bool getBooleanOption(StringRef Name, bool DefaultVal, const ento::CheckerBase *C=nullptr, bool SearchInParents=false)
Interprets an option&#39;s string value as a boolean.
FunctionDecl * getOperatorNew() const
Definition: ExprCXX.h:1973
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const MemRegion * getContainerObjRegion(ProgramStateRef State, SymbolRef Sym)
&#39;Sym&#39; represents a pointer to the inner buffer of a container object.
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1262
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:699
constexpr XRayInstrMask Function
Definition: XRayInstr.h:39
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2475
bool isConsumedExpr(Expr *E) const
Definition: ParentMap.cpp:160
Represents a variable declaration or definition.
Definition: Decl.h:812
unsigned getNumPlacementArgs() const
Definition: ExprCXX.h:1987
std::string getName(ArrayRef< StringRef > Parts) const
Get the platform-specific name separator.
#define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem)
Declares an immutable set of type NameTy, suitable for placement into the ProgramState.
Symbolic value.
Definition: SymExpr.h:30
bool isParentOf(const LocationContext *LC) const
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call)
One of these records is kept for each identifier that is lexed.
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
LineState State
const Expr * getRetValue() const
Definition: Stmt.cpp:937
const CXXConstructExpr * getConstructExpr() const
Returns the CXXConstructExpr from this new-expression, or null.
Definition: ExprCXX.h:2026
std::unique_ptr< BugReporterVisitor > getInnerPointerBRVisitor(SymbolRef Sym)
This function provides an additional visitor that augments the bug report with information relevant t...
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
IdentifierTable & Idents
Definition: ASTContext.h:565
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2231
static bool isLocType(QualType T)
Definition: SVals.h:327
void registerCStringCheckerBasic(CheckerManager &Mgr)
Register the checker which evaluates CString API calls.
Expr * getArraySize()
Definition: ExprCXX.h:1980
Represents any expression that calls an Objective-C method.
Definition: CallEvent.h:966
FunctionDecl * getOperatorDelete() const
Definition: ExprCXX.h:2152
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
uint32_t Offset
Definition: CacheTokens.cpp:43
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
const LocationContext * getParent() const
static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD)
static bool didPreviousFreeFail(ProgramStateRef State, SymbolRef Sym, SymbolRef &RetStatusSymbol)
Checks if the previous call to free on the given symbol failed - if free failed, returns true...
arg_iterator placement_arg_end()
Definition: ExprCXX.h:2057
CheckName getCurrentCheckName() const
bool isArrayForm() const
Definition: ExprCXX.h:2141
Const iterator for iterating over Stmt * arrays that contain only Expr *.
Definition: Stmt.h:359
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1605
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3278
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1325
Represents a non-static C++ member function call, no matter how it is written.
Definition: CallEvent.h:681
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
This represents one expression.
Definition: Expr.h:105
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2668
std::string Label
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:71
Represents an implicit call to a C++ destructor.
Definition: CallEvent.h:811
static bool retTrue(const RefState *RS)
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:4974
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2697
The pointer has been passed to a function call directly.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
QualType getType() const
Definition: Expr.h:127
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:1444
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
unsigned getNumArgs() const
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:707
bool hasAttrs() const
Definition: DeclBase.h:472
static const Stmt * getStmt(const ExplodedNode *N)
Given an exploded node, retrieve the statement that should be used for the diagnostic location...
Expr * getArgument()
Definition: ExprCXX.h:2154
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
Kind
AllocationFamily
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
ReallocPairKind
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1873
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:376
static bool checkIfNewOrNewArrayFamily(const RefState *RS)
QualType getAllocatedType() const
Definition: ExprCXX.h:1947
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2254
bool isArray() const
Definition: ExprCXX.h:1978
static SymbolRef findFailedReallocSymbol(ProgramStateRef currState, ProgramStateRef prevState)
static bool treatUnusedNewEscaped(const CXXNewExpr *NE)
StringRef getName() const
Return the actual identifier string.
virtual const ObjCMessageExpr * getOriginExpr() const
Definition: CallEvent.h:990
CanQualType CharTy
Definition: ASTContext.h:1027
Selector getSelector() const
Definition: CallEvent.h:1014
Dataflow Directional Tag Classes.
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2100
Represents a program point just after an implicit call event.
Definition: ProgramPoint.h:574
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1251
static QualType getDeepPointeeType(QualType T)
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2163
Kind getKind() const
Definition: DeclBase.h:420
AnalyzerOptions & getAnalyzerOptions()
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
Decl * getCalleeDecl()
Definition: Expr.cpp:1255
#define REGISTER_CHECKER(name)
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword...
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2080
static Optional< bool > getFreeWhenDoneArg(const ObjCMethodCall &Call)
const StackFrameContext * getStackFrame() const
ProgramStateRef markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin)
arg_iterator placement_arg_begin()
Definition: ExprCXX.h:2054
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:518
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13824
const Expr * getArgExpr(unsigned Index) const override
Definition: CallEvent.h:1002
#define CASE(ID)
static PathDiagnosticLocation createEndOfPath(const ExplodedNode *N, const SourceManager &SM)
Create a location corresponding to the next valid ExplodedNode as end of path location.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:268
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2285
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:1510
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:971
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
QualType getType() const
Definition: Decl.h:647
A trivial tuple used to represent a source range.
This represents a decl that may have a name.
Definition: Decl.h:248
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3019