xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (revision e5c0c14213b984c8b27c593a28b29136f626ad96)
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"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
22 #include "clang/StaticAnalyzer/Core/Checker.h"
23 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
29 #include "llvm/ADT/ImmutableMap.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include <climits>
34 
35 using namespace clang;
36 using namespace ento;
37 
38 namespace {
39 
40 // Used to check correspondence between allocators and deallocators.
41 enum AllocationFamily {
42   AF_None,
43   AF_Malloc,
44   AF_CXXNew,
45   AF_CXXNewArray,
46   AF_IfNameIndex
47 };
48 
49 class RefState {
50   enum Kind { // Reference to allocated memory.
51               Allocated,
52               // Reference to released/freed memory.
53               Released,
54               // The responsibility for freeing resources has transferred from
55               // this reference. A relinquished symbol should not be freed.
56               Relinquished,
57               // We are no longer guaranteed to have observed all manipulations
58               // of this pointer/memory. For example, it could have been
59               // passed as a parameter to an opaque function.
60               Escaped
61   };
62 
63   const Stmt *S;
64   unsigned K : 2; // Kind enum, but stored as a bitfield.
65   unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
66                         // family.
67 
68   RefState(Kind k, const Stmt *s, unsigned family)
69     : S(s), K(k), Family(family) {
70     assert(family != AF_None);
71   }
72 public:
73   bool isAllocated() const { return K == Allocated; }
74   bool isReleased() const { return K == Released; }
75   bool isRelinquished() const { return K == Relinquished; }
76   bool isEscaped() const { return K == Escaped; }
77   AllocationFamily getAllocationFamily() const {
78     return (AllocationFamily)Family;
79   }
80   const Stmt *getStmt() const { return S; }
81 
82   bool operator==(const RefState &X) const {
83     return K == X.K && S == X.S && Family == X.Family;
84   }
85 
86   static RefState getAllocated(unsigned family, const Stmt *s) {
87     return RefState(Allocated, s, family);
88   }
89   static RefState getReleased(unsigned family, const Stmt *s) {
90     return RefState(Released, s, family);
91   }
92   static RefState getRelinquished(unsigned family, const Stmt *s) {
93     return RefState(Relinquished, s, family);
94   }
95   static RefState getEscaped(const RefState *RS) {
96     return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
97   }
98 
99   void Profile(llvm::FoldingSetNodeID &ID) const {
100     ID.AddInteger(K);
101     ID.AddPointer(S);
102     ID.AddInteger(Family);
103   }
104 
105   void dump(raw_ostream &OS) const {
106     switch (static_cast<Kind>(K)) {
107 #define CASE(ID) case ID: OS << #ID; break;
108     CASE(Allocated)
109     CASE(Released)
110     CASE(Relinquished)
111     CASE(Escaped)
112     }
113   }
114 
115   LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
116 };
117 
118 enum ReallocPairKind {
119   RPToBeFreedAfterFailure,
120   // The symbol has been freed when reallocation failed.
121   RPIsFreeOnFailure,
122   // The symbol does not need to be freed after reallocation fails.
123   RPDoNotTrackAfterFailure
124 };
125 
126 /// \class ReallocPair
127 /// \brief Stores information about the symbol being reallocated by a call to
128 /// 'realloc' to allow modeling failed reallocation later in the path.
129 struct ReallocPair {
130   // \brief The symbol which realloc reallocated.
131   SymbolRef ReallocatedSym;
132   ReallocPairKind Kind;
133 
134   ReallocPair(SymbolRef S, ReallocPairKind K) :
135     ReallocatedSym(S), Kind(K) {}
136   void Profile(llvm::FoldingSetNodeID &ID) const {
137     ID.AddInteger(Kind);
138     ID.AddPointer(ReallocatedSym);
139   }
140   bool operator==(const ReallocPair &X) const {
141     return ReallocatedSym == X.ReallocatedSym &&
142            Kind == X.Kind;
143   }
144 };
145 
146 typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
147 
148 class MallocChecker : public Checker<check::DeadSymbols,
149                                      check::PointerEscape,
150                                      check::ConstPointerEscape,
151                                      check::PreStmt<ReturnStmt>,
152                                      check::PreCall,
153                                      check::PostStmt<CallExpr>,
154                                      check::PostStmt<CXXNewExpr>,
155                                      check::PreStmt<CXXDeleteExpr>,
156                                      check::PostStmt<BlockExpr>,
157                                      check::PostObjCMessage,
158                                      check::Location,
159                                      eval::Assume>
160 {
161 public:
162   MallocChecker()
163       : II_malloc(nullptr), II_free(nullptr), II_realloc(nullptr),
164         II_calloc(nullptr), II_valloc(nullptr), II_reallocf(nullptr),
165         II_strndup(nullptr), II_strdup(nullptr), II_kmalloc(nullptr),
166         II_if_nameindex(nullptr), II_if_freenameindex(nullptr) {}
167 
168   /// In pessimistic mode, the checker assumes that it does not know which
169   /// functions might free the memory.
170   enum CheckKind {
171     CK_MallocPessimistic,
172     CK_MallocOptimistic,
173     CK_NewDeleteChecker,
174     CK_NewDeleteLeaksChecker,
175     CK_MismatchedDeallocatorChecker,
176     CK_NumCheckKinds
177   };
178 
179   enum class MemoryOperationKind {
180     MOK_Allocate,
181     MOK_Free,
182     MOK_Any
183   };
184 
185   DefaultBool ChecksEnabled[CK_NumCheckKinds];
186   CheckName CheckNames[CK_NumCheckKinds];
187   typedef llvm::SmallVector<CheckKind, CK_NumCheckKinds> CKVecTy;
188 
189   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
190   void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
191   void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
192   void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
193   void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
194   void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
195   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
196   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
197   ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
198                             bool Assumption) const;
199   void checkLocation(SVal l, bool isLoad, const Stmt *S,
200                      CheckerContext &C) const;
201 
202   ProgramStateRef checkPointerEscape(ProgramStateRef State,
203                                     const InvalidatedSymbols &Escaped,
204                                     const CallEvent *Call,
205                                     PointerEscapeKind Kind) const;
206   ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
207                                           const InvalidatedSymbols &Escaped,
208                                           const CallEvent *Call,
209                                           PointerEscapeKind Kind) const;
210 
211   void printState(raw_ostream &Out, ProgramStateRef State,
212                   const char *NL, const char *Sep) const override;
213 
214 private:
215   mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
216   mutable std::unique_ptr<BugType> BT_DoubleDelete;
217   mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
218   mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
219   mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
220   mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
221   mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
222   mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
223                          *II_valloc, *II_reallocf, *II_strndup, *II_strdup,
224                          *II_kmalloc, *II_if_nameindex, *II_if_freenameindex;
225   mutable Optional<uint64_t> KernelZeroFlagVal;
226 
227   void initIdentifierInfo(ASTContext &C) const;
228 
229   /// \brief Determine family of a deallocation expression.
230   AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
231 
232   /// \brief Print names of allocators and deallocators.
233   ///
234   /// \returns true on success.
235   bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
236                              const Expr *E) const;
237 
238   /// \brief Print expected name of an allocator based on the deallocator's
239   /// family derived from the DeallocExpr.
240   void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
241                               const Expr *DeallocExpr) const;
242   /// \brief Print expected name of a deallocator based on the allocator's
243   /// family.
244   void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
245 
246   ///@{
247   /// Check if this is one of the functions which can allocate/reallocate memory
248   /// pointed to by one of its arguments.
249   bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
250   bool isCMemFunction(const FunctionDecl *FD,
251                       ASTContext &C,
252                       AllocationFamily Family,
253                       MemoryOperationKind MemKind) const;
254   bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
255   ///@}
256   ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
257                                        const CallExpr *CE,
258                                        const OwnershipAttr* Att,
259                                        ProgramStateRef State) const;
260   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
261                                       const Expr *SizeEx, SVal Init,
262                                       ProgramStateRef State,
263                                       AllocationFamily Family = AF_Malloc);
264   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
265                                       SVal SizeEx, SVal Init,
266                                       ProgramStateRef State,
267                                       AllocationFamily Family = AF_Malloc);
268 
269   // Check if this malloc() for special flags. At present that means M_ZERO or
270   // __GFP_ZERO (in which case, treat it like calloc).
271   llvm::Optional<ProgramStateRef>
272   performKernelMalloc(const CallExpr *CE, CheckerContext &C,
273                       const ProgramStateRef &State) const;
274 
275   /// Update the RefState to reflect the new memory allocation.
276   static ProgramStateRef
277   MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
278                        AllocationFamily Family = AF_Malloc);
279 
280   ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
281                               const OwnershipAttr* Att,
282                               ProgramStateRef State) const;
283   ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
284                              ProgramStateRef state, unsigned Num,
285                              bool Hold,
286                              bool &ReleasedAllocated,
287                              bool ReturnsNullOnFailure = false) const;
288   ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
289                              const Expr *ParentExpr,
290                              ProgramStateRef State,
291                              bool Hold,
292                              bool &ReleasedAllocated,
293                              bool ReturnsNullOnFailure = false) const;
294 
295   ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
296                              bool FreesMemOnFailure,
297                              ProgramStateRef State) const;
298   static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
299                                    ProgramStateRef State);
300 
301   ///\brief Check if the memory associated with this symbol was released.
302   bool isReleased(SymbolRef Sym, CheckerContext &C) const;
303 
304   bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
305 
306   bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
307 
308   /// Check if the function is known free memory, or if it is
309   /// "interesting" and should be modeled explicitly.
310   ///
311   /// \param [out] EscapingSymbol A function might not free memory in general,
312   ///   but could be known to free a particular symbol. In this case, false is
313   ///   returned and the single escaping symbol is returned through the out
314   ///   parameter.
315   ///
316   /// We assume that pointers do not escape through calls to system functions
317   /// not handled by this checker.
318   bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
319                                    ProgramStateRef State,
320                                    SymbolRef &EscapingSymbol) const;
321 
322   // Implementation of the checkPointerEscape callabcks.
323   ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
324                                   const InvalidatedSymbols &Escaped,
325                                   const CallEvent *Call,
326                                   PointerEscapeKind Kind,
327                                   bool(*CheckRefState)(const RefState*)) const;
328 
329   ///@{
330   /// Tells if a given family/call/symbol is tracked by the current checker.
331   /// Looks through incoming CheckKind(s) and returns the kind of the checker
332   /// responsible for this family/call/symbol.
333   Optional<CheckKind> getCheckIfTracked(CheckKind CK,
334                                         AllocationFamily Family) const;
335   Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec,
336                                         AllocationFamily Family) const;
337   Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
338                                         const Stmt *AllocDeallocStmt) const;
339   Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
340                                         SymbolRef Sym) const;
341   ///@}
342   static bool SummarizeValue(raw_ostream &os, SVal V);
343   static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
344   void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
345                      const Expr *DeallocExpr) const;
346   void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
347                                const Expr *DeallocExpr, const RefState *RS,
348                                SymbolRef Sym, bool OwnershipTransferred) const;
349   void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
350                         const Expr *DeallocExpr,
351                         const Expr *AllocExpr = nullptr) const;
352   void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
353                           SymbolRef Sym) const;
354   void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
355                         SymbolRef Sym, SymbolRef PrevSym) const;
356 
357   void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
358 
359   /// Find the location of the allocation for Sym on the path leading to the
360   /// exploded node N.
361   LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
362                              CheckerContext &C) const;
363 
364   void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
365 
366   /// The bug visitor which allows us to print extra diagnostics along the
367   /// BugReport path. For example, showing the allocation site of the leaked
368   /// region.
369   class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
370   protected:
371     enum NotificationMode {
372       Normal,
373       ReallocationFailed
374     };
375 
376     // The allocated region symbol tracked by the main analysis.
377     SymbolRef Sym;
378 
379     // The mode we are in, i.e. what kind of diagnostics will be emitted.
380     NotificationMode Mode;
381 
382     // A symbol from when the primary region should have been reallocated.
383     SymbolRef FailedReallocSymbol;
384 
385     bool IsLeak;
386 
387   public:
388     MallocBugVisitor(SymbolRef S, bool isLeak = false)
389        : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
390 
391     virtual ~MallocBugVisitor() {}
392 
393     void Profile(llvm::FoldingSetNodeID &ID) const override {
394       static int X = 0;
395       ID.AddPointer(&X);
396       ID.AddPointer(Sym);
397     }
398 
399     inline bool isAllocated(const RefState *S, const RefState *SPrev,
400                             const Stmt *Stmt) {
401       // Did not track -> allocated. Other state (released) -> allocated.
402       return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
403               (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
404     }
405 
406     inline bool isReleased(const RefState *S, const RefState *SPrev,
407                            const Stmt *Stmt) {
408       // Did not track -> released. Other state (allocated) -> released.
409       return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
410               (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
411     }
412 
413     inline bool isRelinquished(const RefState *S, const RefState *SPrev,
414                                const Stmt *Stmt) {
415       // Did not track -> relinquished. Other state (allocated) -> relinquished.
416       return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
417                                               isa<ObjCPropertyRefExpr>(Stmt)) &&
418               (S && S->isRelinquished()) &&
419               (!SPrev || !SPrev->isRelinquished()));
420     }
421 
422     inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
423                                      const Stmt *Stmt) {
424       // If the expression is not a call, and the state change is
425       // released -> allocated, it must be the realloc return value
426       // check. If we have to handle more cases here, it might be cleaner just
427       // to track this extra bit in the state itself.
428       return ((!Stmt || !isa<CallExpr>(Stmt)) &&
429               (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
430     }
431 
432     PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
433                                    const ExplodedNode *PrevN,
434                                    BugReporterContext &BRC,
435                                    BugReport &BR) override;
436 
437     std::unique_ptr<PathDiagnosticPiece>
438     getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
439                BugReport &BR) override {
440       if (!IsLeak)
441         return nullptr;
442 
443       PathDiagnosticLocation L =
444         PathDiagnosticLocation::createEndOfPath(EndPathNode,
445                                                 BRC.getSourceManager());
446       // Do not add the statement itself as a range in case of leak.
447       return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
448                                                          false);
449     }
450 
451   private:
452     class StackHintGeneratorForReallocationFailed
453         : public StackHintGeneratorForSymbol {
454     public:
455       StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
456         : StackHintGeneratorForSymbol(S, M) {}
457 
458       std::string getMessageForArg(const Expr *ArgE,
459                                    unsigned ArgIndex) override {
460         // Printed parameters start at 1, not 0.
461         ++ArgIndex;
462 
463         SmallString<200> buf;
464         llvm::raw_svector_ostream os(buf);
465 
466         os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
467            << " parameter failed";
468 
469         return os.str();
470       }
471 
472       std::string getMessageForReturn(const CallExpr *CallExpr) override {
473         return "Reallocation of returned value failed";
474       }
475     };
476   };
477 };
478 } // end anonymous namespace
479 
480 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
481 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
482 
483 // A map from the freed symbol to the symbol representing the return value of
484 // the free function.
485 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
486 
487 namespace {
488 class StopTrackingCallback : public SymbolVisitor {
489   ProgramStateRef state;
490 public:
491   StopTrackingCallback(ProgramStateRef st) : state(st) {}
492   ProgramStateRef getState() const { return state; }
493 
494   bool VisitSymbol(SymbolRef sym) override {
495     state = state->remove<RegionState>(sym);
496     return true;
497   }
498 };
499 } // end anonymous namespace
500 
501 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
502   if (II_malloc)
503     return;
504   II_malloc = &Ctx.Idents.get("malloc");
505   II_free = &Ctx.Idents.get("free");
506   II_realloc = &Ctx.Idents.get("realloc");
507   II_reallocf = &Ctx.Idents.get("reallocf");
508   II_calloc = &Ctx.Idents.get("calloc");
509   II_valloc = &Ctx.Idents.get("valloc");
510   II_strdup = &Ctx.Idents.get("strdup");
511   II_strndup = &Ctx.Idents.get("strndup");
512   II_kmalloc = &Ctx.Idents.get("kmalloc");
513   II_if_nameindex = &Ctx.Idents.get("if_nameindex");
514   II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
515 }
516 
517 bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
518   if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
519     return true;
520 
521   if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
522     return true;
523 
524   if (isStandardNewDelete(FD, C))
525     return true;
526 
527   return false;
528 }
529 
530 bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
531                                    ASTContext &C,
532                                    AllocationFamily Family,
533                                    MemoryOperationKind MemKind) const {
534   if (!FD)
535     return false;
536 
537   bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
538                     MemKind == MemoryOperationKind::MOK_Free);
539   bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
540                      MemKind == MemoryOperationKind::MOK_Allocate);
541 
542   if (FD->getKind() == Decl::Function) {
543     const IdentifierInfo *FunI = FD->getIdentifier();
544     initIdentifierInfo(C);
545 
546     if (Family == AF_Malloc && CheckFree) {
547       if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
548         return true;
549     }
550 
551     if (Family == AF_Malloc && CheckAlloc) {
552       if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
553           FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
554           FunI == II_strndup || FunI == II_kmalloc)
555         return true;
556     }
557 
558     if (Family == AF_IfNameIndex && CheckFree) {
559       if (FunI == II_if_freenameindex)
560         return true;
561     }
562 
563     if (Family == AF_IfNameIndex && CheckAlloc) {
564       if (FunI == II_if_nameindex)
565         return true;
566     }
567   }
568 
569   if (Family != AF_Malloc)
570     return false;
571 
572   if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs()) {
573     for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
574       OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
575       if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
576         if (CheckFree)
577           return true;
578       } else if (OwnKind == OwnershipAttr::Returns) {
579         if (CheckAlloc)
580           return true;
581       }
582     }
583   }
584 
585   return false;
586 }
587 
588 // Tells if the callee is one of the following:
589 // 1) A global non-placement new/delete operator function.
590 // 2) A global placement operator function with the single placement argument
591 //    of type std::nothrow_t.
592 bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
593                                         ASTContext &C) const {
594   if (!FD)
595     return false;
596 
597   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
598   if (Kind != OO_New && Kind != OO_Array_New &&
599       Kind != OO_Delete && Kind != OO_Array_Delete)
600     return false;
601 
602   // Skip all operator new/delete methods.
603   if (isa<CXXMethodDecl>(FD))
604     return false;
605 
606   // Return true if tested operator is a standard placement nothrow operator.
607   if (FD->getNumParams() == 2) {
608     QualType T = FD->getParamDecl(1)->getType();
609     if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
610       return II->getName().equals("nothrow_t");
611   }
612 
613   // Skip placement operators.
614   if (FD->getNumParams() != 1 || FD->isVariadic())
615     return false;
616 
617   // One of the standard new/new[]/delete/delete[] non-placement operators.
618   return true;
619 }
620 
621 llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
622   const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
623   // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
624   //
625   // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
626   //
627   // One of the possible flags is M_ZERO, which means 'give me back an
628   // allocation which is already zeroed', like calloc.
629 
630   // 2-argument kmalloc(), as used in the Linux kernel:
631   //
632   // void *kmalloc(size_t size, gfp_t flags);
633   //
634   // Has the similar flag value __GFP_ZERO.
635 
636   // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
637   // code could be shared.
638 
639   ASTContext &Ctx = C.getASTContext();
640   llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
641 
642   if (!KernelZeroFlagVal.hasValue()) {
643     if (OS == llvm::Triple::FreeBSD)
644       KernelZeroFlagVal = 0x0100;
645     else if (OS == llvm::Triple::NetBSD)
646       KernelZeroFlagVal = 0x0002;
647     else if (OS == llvm::Triple::OpenBSD)
648       KernelZeroFlagVal = 0x0008;
649     else if (OS == llvm::Triple::Linux)
650       // __GFP_ZERO
651       KernelZeroFlagVal = 0x8000;
652     else
653       // FIXME: We need a more general way of getting the M_ZERO value.
654       // See also: O_CREAT in UnixAPIChecker.cpp.
655 
656       // Fall back to normal malloc behavior on platforms where we don't
657       // know M_ZERO.
658       return None;
659   }
660 
661   // We treat the last argument as the flags argument, and callers fall-back to
662   // normal malloc on a None return. This works for the FreeBSD kernel malloc
663   // as well as Linux kmalloc.
664   if (CE->getNumArgs() < 2)
665     return None;
666 
667   const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
668   const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
669   if (!V.getAs<NonLoc>()) {
670     // The case where 'V' can be a location can only be due to a bad header,
671     // so in this case bail out.
672     return None;
673   }
674 
675   NonLoc Flags = V.castAs<NonLoc>();
676   NonLoc ZeroFlag = C.getSValBuilder()
677       .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
678       .castAs<NonLoc>();
679   SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
680                                                       Flags, ZeroFlag,
681                                                       FlagsEx->getType());
682   if (MaskedFlagsUC.isUnknownOrUndef())
683     return None;
684   DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
685 
686   // Check if maskedFlags is non-zero.
687   ProgramStateRef TrueState, FalseState;
688   std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
689 
690   // If M_ZERO is set, treat this like calloc (initialized).
691   if (TrueState && !FalseState) {
692     SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
693     return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
694   }
695 
696   return None;
697 }
698 
699 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
700   if (C.wasInlined)
701     return;
702 
703   const FunctionDecl *FD = C.getCalleeDecl(CE);
704   if (!FD)
705     return;
706 
707   ProgramStateRef State = C.getState();
708   bool ReleasedAllocatedMemory = false;
709 
710   if (FD->getKind() == Decl::Function) {
711     initIdentifierInfo(C.getASTContext());
712     IdentifierInfo *FunI = FD->getIdentifier();
713 
714     if (FunI == II_malloc) {
715       if (CE->getNumArgs() < 1)
716         return;
717       if (CE->getNumArgs() < 3) {
718         State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
719       } else if (CE->getNumArgs() == 3) {
720         llvm::Optional<ProgramStateRef> MaybeState =
721           performKernelMalloc(CE, C, State);
722         if (MaybeState.hasValue())
723           State = MaybeState.getValue();
724         else
725           State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
726       }
727     } else if (FunI == II_kmalloc) {
728       llvm::Optional<ProgramStateRef> MaybeState =
729         performKernelMalloc(CE, C, State);
730       if (MaybeState.hasValue())
731         State = MaybeState.getValue();
732       else
733         State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
734     } else if (FunI == II_valloc) {
735       if (CE->getNumArgs() < 1)
736         return;
737       State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
738     } else if (FunI == II_realloc) {
739       State = ReallocMem(C, CE, false, State);
740     } else if (FunI == II_reallocf) {
741       State = ReallocMem(C, CE, true, State);
742     } else if (FunI == II_calloc) {
743       State = CallocMem(C, CE, State);
744     } else if (FunI == II_free) {
745       State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
746     } else if (FunI == II_strdup) {
747       State = MallocUpdateRefState(C, CE, State);
748     } else if (FunI == II_strndup) {
749       State = MallocUpdateRefState(C, CE, State);
750     }
751     else if (isStandardNewDelete(FD, C.getASTContext())) {
752       // Process direct calls to operator new/new[]/delete/delete[] functions
753       // as distinct from new/new[]/delete/delete[] expressions that are
754       // processed by the checkPostStmt callbacks for CXXNewExpr and
755       // CXXDeleteExpr.
756       OverloadedOperatorKind K = FD->getOverloadedOperator();
757       if (K == OO_New)
758         State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
759                              AF_CXXNew);
760       else if (K == OO_Array_New)
761         State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
762                              AF_CXXNewArray);
763       else if (K == OO_Delete || K == OO_Array_Delete)
764         State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
765       else
766         llvm_unreachable("not a new/delete operator");
767     } else if (FunI == II_if_nameindex) {
768       // Should we model this differently? We can allocate a fixed number of
769       // elements with zeros in the last one.
770       State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
771                            AF_IfNameIndex);
772     } else if (FunI == II_if_freenameindex) {
773       State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
774     }
775   }
776 
777   if (ChecksEnabled[CK_MallocOptimistic] ||
778       ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
779     // Check all the attributes, if there are any.
780     // There can be multiple of these attributes.
781     if (FD->hasAttrs())
782       for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
783         switch (I->getOwnKind()) {
784         case OwnershipAttr::Returns:
785           State = MallocMemReturnsAttr(C, CE, I, State);
786           break;
787         case OwnershipAttr::Takes:
788         case OwnershipAttr::Holds:
789           State = FreeMemAttr(C, CE, I, State);
790           break;
791         }
792       }
793   }
794   C.addTransition(State);
795 }
796 
797 static QualType getDeepPointeeType(QualType T) {
798   QualType Result = T, PointeeType = T->getPointeeType();
799   while (!PointeeType.isNull()) {
800     Result = PointeeType;
801     PointeeType = PointeeType->getPointeeType();
802   }
803   return Result;
804 }
805 
806 static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
807 
808   const CXXConstructExpr *ConstructE = NE->getConstructExpr();
809   if (!ConstructE)
810     return false;
811 
812   if (!NE->getAllocatedType()->getAsCXXRecordDecl())
813     return false;
814 
815   const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
816 
817   // Iterate over the constructor parameters.
818   for (const auto *CtorParam : CtorD->params()) {
819 
820     QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
821     if (CtorParamPointeeT.isNull())
822       continue;
823 
824     CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
825 
826     if (CtorParamPointeeT->getAsCXXRecordDecl())
827       return true;
828   }
829 
830   return false;
831 }
832 
833 void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
834                                   CheckerContext &C) const {
835 
836   if (NE->getNumPlacementArgs())
837     for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
838          E = NE->placement_arg_end(); I != E; ++I)
839       if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
840         checkUseAfterFree(Sym, C, *I);
841 
842   if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
843     return;
844 
845   ParentMap &PM = C.getLocationContext()->getParentMap();
846   if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
847     return;
848 
849   ProgramStateRef State = C.getState();
850   // The return value from operator new is bound to a specified initialization
851   // value (if any) and we don't want to loose this value. So we call
852   // MallocUpdateRefState() instead of MallocMemAux() which breakes the
853   // existing binding.
854   State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
855                                                            : AF_CXXNew);
856   C.addTransition(State);
857 }
858 
859 void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
860                                  CheckerContext &C) const {
861 
862   if (!ChecksEnabled[CK_NewDeleteChecker])
863     if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
864       checkUseAfterFree(Sym, C, DE->getArgument());
865 
866   if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
867     return;
868 
869   ProgramStateRef State = C.getState();
870   bool ReleasedAllocated;
871   State = FreeMemAux(C, DE->getArgument(), DE, State,
872                      /*Hold*/false, ReleasedAllocated);
873 
874   C.addTransition(State);
875 }
876 
877 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
878   // If the first selector piece is one of the names below, assume that the
879   // object takes ownership of the memory, promising to eventually deallocate it
880   // with free().
881   // Ex:  [NSData dataWithBytesNoCopy:bytes length:10];
882   // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
883   StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
884   if (FirstSlot == "dataWithBytesNoCopy" ||
885       FirstSlot == "initWithBytesNoCopy" ||
886       FirstSlot == "initWithCharactersNoCopy")
887     return true;
888 
889   return false;
890 }
891 
892 static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
893   Selector S = Call.getSelector();
894 
895   // FIXME: We should not rely on fully-constrained symbols being folded.
896   for (unsigned i = 1; i < S.getNumArgs(); ++i)
897     if (S.getNameForSlot(i).equals("freeWhenDone"))
898       return !Call.getArgSVal(i).isZeroConstant();
899 
900   return None;
901 }
902 
903 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
904                                          CheckerContext &C) const {
905   if (C.wasInlined)
906     return;
907 
908   if (!isKnownDeallocObjCMethodName(Call))
909     return;
910 
911   if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
912     if (!*FreeWhenDone)
913       return;
914 
915   bool ReleasedAllocatedMemory;
916   ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
917                                      Call.getOriginExpr(), C.getState(),
918                                      /*Hold=*/true, ReleasedAllocatedMemory,
919                                      /*RetNullOnFailure=*/true);
920 
921   C.addTransition(State);
922 }
923 
924 ProgramStateRef
925 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
926                                     const OwnershipAttr *Att,
927                                     ProgramStateRef State) const {
928   if (!State)
929     return nullptr;
930 
931   if (Att->getModule() != II_malloc)
932     return nullptr;
933 
934   OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
935   if (I != E) {
936     return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
937   }
938   return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
939 }
940 
941 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
942                                             const CallExpr *CE,
943                                             const Expr *SizeEx, SVal Init,
944                                             ProgramStateRef State,
945                                             AllocationFamily Family) {
946   if (!State)
947     return nullptr;
948 
949   return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
950                       Init, State, Family);
951 }
952 
953 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
954                                            const CallExpr *CE,
955                                            SVal Size, SVal Init,
956                                            ProgramStateRef State,
957                                            AllocationFamily Family) {
958   if (!State)
959     return nullptr;
960 
961   // We expect the malloc functions to return a pointer.
962   if (!Loc::isLocType(CE->getType()))
963     return nullptr;
964 
965   // Bind the return value to the symbolic value from the heap region.
966   // TODO: We could rewrite post visit to eval call; 'malloc' does not have
967   // side effects other than what we model here.
968   unsigned Count = C.blockCount();
969   SValBuilder &svalBuilder = C.getSValBuilder();
970   const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
971   DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
972       .castAs<DefinedSVal>();
973   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
974 
975   // Fill the region with the initialization value.
976   State = State->bindDefault(RetVal, Init);
977 
978   // Set the region's extent equal to the Size parameter.
979   const SymbolicRegion *R =
980       dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
981   if (!R)
982     return nullptr;
983   if (Optional<DefinedOrUnknownSVal> DefinedSize =
984           Size.getAs<DefinedOrUnknownSVal>()) {
985     SValBuilder &svalBuilder = C.getSValBuilder();
986     DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
987     DefinedOrUnknownSVal extentMatchesSize =
988         svalBuilder.evalEQ(State, Extent, *DefinedSize);
989 
990     State = State->assume(extentMatchesSize, true);
991     assert(State);
992   }
993 
994   return MallocUpdateRefState(C, CE, State, Family);
995 }
996 
997 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
998                                                     const Expr *E,
999                                                     ProgramStateRef State,
1000                                                     AllocationFamily Family) {
1001   if (!State)
1002     return nullptr;
1003 
1004   // Get the return value.
1005   SVal retVal = State->getSVal(E, C.getLocationContext());
1006 
1007   // We expect the malloc functions to return a pointer.
1008   if (!retVal.getAs<Loc>())
1009     return nullptr;
1010 
1011   SymbolRef Sym = retVal.getAsLocSymbol();
1012   assert(Sym);
1013 
1014   // Set the symbol's state to Allocated.
1015   return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1016 }
1017 
1018 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1019                                            const CallExpr *CE,
1020                                            const OwnershipAttr *Att,
1021                                            ProgramStateRef State) const {
1022   if (!State)
1023     return nullptr;
1024 
1025   if (Att->getModule() != II_malloc)
1026     return nullptr;
1027 
1028   bool ReleasedAllocated = false;
1029 
1030   for (const auto &Arg : Att->args()) {
1031     ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
1032                                Att->getOwnKind() == OwnershipAttr::Holds,
1033                                ReleasedAllocated);
1034     if (StateI)
1035       State = StateI;
1036   }
1037   return State;
1038 }
1039 
1040 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1041                                           const CallExpr *CE,
1042                                           ProgramStateRef State,
1043                                           unsigned Num,
1044                                           bool Hold,
1045                                           bool &ReleasedAllocated,
1046                                           bool ReturnsNullOnFailure) const {
1047   if (!State)
1048     return nullptr;
1049 
1050   if (CE->getNumArgs() < (Num + 1))
1051     return nullptr;
1052 
1053   return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
1054                     ReleasedAllocated, ReturnsNullOnFailure);
1055 }
1056 
1057 /// Checks if the previous call to free on the given symbol failed - if free
1058 /// failed, returns true. Also, returns the corresponding return value symbol.
1059 static bool didPreviousFreeFail(ProgramStateRef State,
1060                                 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1061   const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1062   if (Ret) {
1063     assert(*Ret && "We should not store the null return symbol");
1064     ConstraintManager &CMgr = State->getConstraintManager();
1065     ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1066     RetStatusSymbol = *Ret;
1067     return FreeFailed.isConstrainedTrue();
1068   }
1069   return false;
1070 }
1071 
1072 AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1073                                                     const Stmt *S) const {
1074   if (!S)
1075     return AF_None;
1076 
1077   if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1078     const FunctionDecl *FD = C.getCalleeDecl(CE);
1079 
1080     if (!FD)
1081       FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1082 
1083     ASTContext &Ctx = C.getASTContext();
1084 
1085     if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1086       return AF_Malloc;
1087 
1088     if (isStandardNewDelete(FD, Ctx)) {
1089       OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1090       if (Kind == OO_New || Kind == OO_Delete)
1091         return AF_CXXNew;
1092       else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1093         return AF_CXXNewArray;
1094     }
1095 
1096     if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1097       return AF_IfNameIndex;
1098 
1099     return AF_None;
1100   }
1101 
1102   if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1103     return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1104 
1105   if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1106     return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1107 
1108   if (isa<ObjCMessageExpr>(S))
1109     return AF_Malloc;
1110 
1111   return AF_None;
1112 }
1113 
1114 bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1115                                           const Expr *E) const {
1116   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1117     // FIXME: This doesn't handle indirect calls.
1118     const FunctionDecl *FD = CE->getDirectCallee();
1119     if (!FD)
1120       return false;
1121 
1122     os << *FD;
1123     if (!FD->isOverloadedOperator())
1124       os << "()";
1125     return true;
1126   }
1127 
1128   if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1129     if (Msg->isInstanceMessage())
1130       os << "-";
1131     else
1132       os << "+";
1133     Msg->getSelector().print(os);
1134     return true;
1135   }
1136 
1137   if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1138     os << "'"
1139        << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1140        << "'";
1141     return true;
1142   }
1143 
1144   if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1145     os << "'"
1146        << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1147        << "'";
1148     return true;
1149   }
1150 
1151   return false;
1152 }
1153 
1154 void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1155                                            const Expr *E) const {
1156   AllocationFamily Family = getAllocationFamily(C, E);
1157 
1158   switch(Family) {
1159     case AF_Malloc: os << "malloc()"; return;
1160     case AF_CXXNew: os << "'new'"; return;
1161     case AF_CXXNewArray: os << "'new[]'"; return;
1162     case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1163     case AF_None: llvm_unreachable("not a deallocation expression");
1164   }
1165 }
1166 
1167 void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1168                                              AllocationFamily Family) const {
1169   switch(Family) {
1170     case AF_Malloc: os << "free()"; return;
1171     case AF_CXXNew: os << "'delete'"; return;
1172     case AF_CXXNewArray: os << "'delete[]'"; return;
1173     case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1174     case AF_None: llvm_unreachable("suspicious AF_None argument");
1175   }
1176 }
1177 
1178 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1179                                           const Expr *ArgExpr,
1180                                           const Expr *ParentExpr,
1181                                           ProgramStateRef State,
1182                                           bool Hold,
1183                                           bool &ReleasedAllocated,
1184                                           bool ReturnsNullOnFailure) const {
1185 
1186   if (!State)
1187     return nullptr;
1188 
1189   SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
1190   if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1191     return nullptr;
1192   DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1193 
1194   // Check for null dereferences.
1195   if (!location.getAs<Loc>())
1196     return nullptr;
1197 
1198   // The explicit NULL case, no operation is performed.
1199   ProgramStateRef notNullState, nullState;
1200   std::tie(notNullState, nullState) = State->assume(location);
1201   if (nullState && !notNullState)
1202     return nullptr;
1203 
1204   // Unknown values could easily be okay
1205   // Undefined values are handled elsewhere
1206   if (ArgVal.isUnknownOrUndef())
1207     return nullptr;
1208 
1209   const MemRegion *R = ArgVal.getAsRegion();
1210 
1211   // Nonlocs can't be freed, of course.
1212   // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1213   if (!R) {
1214     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1215     return nullptr;
1216   }
1217 
1218   R = R->StripCasts();
1219 
1220   // Blocks might show up as heap data, but should not be free()d
1221   if (isa<BlockDataRegion>(R)) {
1222     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1223     return nullptr;
1224   }
1225 
1226   const MemSpaceRegion *MS = R->getMemorySpace();
1227 
1228   // Parameters, locals, statics, globals, and memory returned by alloca()
1229   // shouldn't be freed.
1230   if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1231     // FIXME: at the time this code was written, malloc() regions were
1232     // represented by conjured symbols, which are all in UnknownSpaceRegion.
1233     // This means that there isn't actually anything from HeapSpaceRegion
1234     // that should be freed, even though we allow it here.
1235     // Of course, free() can work on memory allocated outside the current
1236     // function, so UnknownSpaceRegion is always a possibility.
1237     // False negatives are better than false positives.
1238 
1239     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1240     return nullptr;
1241   }
1242 
1243   const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1244   // Various cases could lead to non-symbol values here.
1245   // For now, ignore them.
1246   if (!SrBase)
1247     return nullptr;
1248 
1249   SymbolRef SymBase = SrBase->getSymbol();
1250   const RefState *RsBase = State->get<RegionState>(SymBase);
1251   SymbolRef PreviousRetStatusSymbol = nullptr;
1252 
1253   if (RsBase) {
1254 
1255     // Check for double free first.
1256     if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1257         !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1258       ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1259                        SymBase, PreviousRetStatusSymbol);
1260       return nullptr;
1261 
1262     // If the pointer is allocated or escaped, but we are now trying to free it,
1263     // check that the call to free is proper.
1264     } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1265 
1266       // Check if an expected deallocation function matches the real one.
1267       bool DeallocMatchesAlloc =
1268         RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1269       if (!DeallocMatchesAlloc) {
1270         ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1271                                 ParentExpr, RsBase, SymBase, Hold);
1272         return nullptr;
1273       }
1274 
1275       // Check if the memory location being freed is the actual location
1276       // allocated, or an offset.
1277       RegionOffset Offset = R->getAsOffset();
1278       if (Offset.isValid() &&
1279           !Offset.hasSymbolicOffset() &&
1280           Offset.getOffset() != 0) {
1281         const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1282         ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1283                          AllocExpr);
1284         return nullptr;
1285       }
1286     }
1287   }
1288 
1289   ReleasedAllocated = (RsBase != nullptr) && RsBase->isAllocated();
1290 
1291   // Clean out the info on previous call to free return info.
1292   State = State->remove<FreeReturnValue>(SymBase);
1293 
1294   // Keep track of the return value. If it is NULL, we will know that free
1295   // failed.
1296   if (ReturnsNullOnFailure) {
1297     SVal RetVal = C.getSVal(ParentExpr);
1298     SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1299     if (RetStatusSymbol) {
1300       C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1301       State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1302     }
1303   }
1304 
1305   AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1306                                    : getAllocationFamily(C, ParentExpr);
1307   // Normal free.
1308   if (Hold)
1309     return State->set<RegionState>(SymBase,
1310                                    RefState::getRelinquished(Family,
1311                                                              ParentExpr));
1312 
1313   return State->set<RegionState>(SymBase,
1314                                  RefState::getReleased(Family, ParentExpr));
1315 }
1316 
1317 Optional<MallocChecker::CheckKind>
1318 MallocChecker::getCheckIfTracked(MallocChecker::CheckKind CK,
1319                                  AllocationFamily Family) const {
1320 
1321   if (CK == CK_NumCheckKinds || !ChecksEnabled[CK])
1322     return Optional<MallocChecker::CheckKind>();
1323 
1324   // C/C++ checkers.
1325   if (CK == CK_MismatchedDeallocatorChecker)
1326     return CK;
1327 
1328   switch (Family) {
1329   case AF_Malloc:
1330   case AF_IfNameIndex: {
1331     // C checkers.
1332     if (CK == CK_MallocOptimistic ||
1333         CK == CK_MallocPessimistic) {
1334       return CK;
1335     }
1336     return Optional<MallocChecker::CheckKind>();
1337   }
1338   case AF_CXXNew:
1339   case AF_CXXNewArray: {
1340     // C++ checkers.
1341     if (CK == CK_NewDeleteChecker ||
1342         CK == CK_NewDeleteLeaksChecker) {
1343       return CK;
1344     }
1345     return Optional<MallocChecker::CheckKind>();
1346   }
1347   case AF_None: {
1348     llvm_unreachable("no family");
1349   }
1350   }
1351   llvm_unreachable("unhandled family");
1352 }
1353 
1354 static MallocChecker::CKVecTy MakeVecFromCK(MallocChecker::CheckKind CK1,
1355                MallocChecker::CheckKind CK2 = MallocChecker::CK_NumCheckKinds,
1356                MallocChecker::CheckKind CK3 = MallocChecker::CK_NumCheckKinds,
1357                MallocChecker::CheckKind CK4 = MallocChecker::CK_NumCheckKinds) {
1358   MallocChecker::CKVecTy CKVec;
1359   CKVec.push_back(CK1);
1360   if (CK2 != MallocChecker::CK_NumCheckKinds) {
1361     CKVec.push_back(CK2);
1362     if (CK3 != MallocChecker::CK_NumCheckKinds) {
1363       CKVec.push_back(CK3);
1364       if (CK4 != MallocChecker::CK_NumCheckKinds)
1365         CKVec.push_back(CK4);
1366     }
1367   }
1368   return CKVec;
1369 }
1370 
1371 Optional<MallocChecker::CheckKind>
1372 MallocChecker::getCheckIfTracked(CKVecTy CKVec, AllocationFamily Family) const {
1373   for (auto CK: CKVec) {
1374     auto RetCK = getCheckIfTracked(CK, Family);
1375     if (RetCK.hasValue())
1376       return RetCK;
1377   }
1378   return Optional<MallocChecker::CheckKind>();
1379 }
1380 
1381 Optional<MallocChecker::CheckKind>
1382 MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
1383                                  const Stmt *AllocDeallocStmt) const {
1384   return getCheckIfTracked(CKVec, getAllocationFamily(C, AllocDeallocStmt));
1385 }
1386 
1387 Optional<MallocChecker::CheckKind>
1388 MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
1389                                  SymbolRef Sym) const {
1390   const RefState *RS = C.getState()->get<RegionState>(Sym);
1391   assert(RS);
1392   return getCheckIfTracked(CKVec, RS->getAllocationFamily());
1393 }
1394 
1395 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1396   if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1397     os << "an integer (" << IntVal->getValue() << ")";
1398   else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1399     os << "a constant address (" << ConstAddr->getValue() << ")";
1400   else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1401     os << "the address of the label '" << Label->getLabel()->getName() << "'";
1402   else
1403     return false;
1404 
1405   return true;
1406 }
1407 
1408 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1409                                     const MemRegion *MR) {
1410   switch (MR->getKind()) {
1411   case MemRegion::FunctionTextRegionKind: {
1412     const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
1413     if (FD)
1414       os << "the address of the function '" << *FD << '\'';
1415     else
1416       os << "the address of a function";
1417     return true;
1418   }
1419   case MemRegion::BlockTextRegionKind:
1420     os << "block text";
1421     return true;
1422   case MemRegion::BlockDataRegionKind:
1423     // FIXME: where the block came from?
1424     os << "a block";
1425     return true;
1426   default: {
1427     const MemSpaceRegion *MS = MR->getMemorySpace();
1428 
1429     if (isa<StackLocalsSpaceRegion>(MS)) {
1430       const VarRegion *VR = dyn_cast<VarRegion>(MR);
1431       const VarDecl *VD;
1432       if (VR)
1433         VD = VR->getDecl();
1434       else
1435         VD = nullptr;
1436 
1437       if (VD)
1438         os << "the address of the local variable '" << VD->getName() << "'";
1439       else
1440         os << "the address of a local stack variable";
1441       return true;
1442     }
1443 
1444     if (isa<StackArgumentsSpaceRegion>(MS)) {
1445       const VarRegion *VR = dyn_cast<VarRegion>(MR);
1446       const VarDecl *VD;
1447       if (VR)
1448         VD = VR->getDecl();
1449       else
1450         VD = nullptr;
1451 
1452       if (VD)
1453         os << "the address of the parameter '" << VD->getName() << "'";
1454       else
1455         os << "the address of a parameter";
1456       return true;
1457     }
1458 
1459     if (isa<GlobalsSpaceRegion>(MS)) {
1460       const VarRegion *VR = dyn_cast<VarRegion>(MR);
1461       const VarDecl *VD;
1462       if (VR)
1463         VD = VR->getDecl();
1464       else
1465         VD = nullptr;
1466 
1467       if (VD) {
1468         if (VD->isStaticLocal())
1469           os << "the address of the static variable '" << VD->getName() << "'";
1470         else
1471           os << "the address of the global variable '" << VD->getName() << "'";
1472       } else
1473         os << "the address of a global variable";
1474       return true;
1475     }
1476 
1477     return false;
1478   }
1479   }
1480 }
1481 
1482 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1483                                   SourceRange Range,
1484                                   const Expr *DeallocExpr) const {
1485 
1486   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1487                                                    CK_MallocPessimistic,
1488                                                    CK_NewDeleteChecker),
1489                                      C, DeallocExpr);
1490   if (!CheckKind.hasValue())
1491     return;
1492 
1493   if (ExplodedNode *N = C.generateSink()) {
1494     if (!BT_BadFree[*CheckKind])
1495       BT_BadFree[*CheckKind].reset(
1496           new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1497 
1498     SmallString<100> buf;
1499     llvm::raw_svector_ostream os(buf);
1500 
1501     const MemRegion *MR = ArgVal.getAsRegion();
1502     while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1503       MR = ER->getSuperRegion();
1504 
1505     if (MR && isa<AllocaRegion>(MR))
1506       os << "Memory allocated by alloca() should not be deallocated";
1507     else {
1508       os << "Argument to ";
1509       if (!printAllocDeallocName(os, C, DeallocExpr))
1510         os << "deallocator";
1511 
1512       os << " is ";
1513       bool Summarized = MR ? SummarizeRegion(os, MR)
1514                            : SummarizeValue(os, ArgVal);
1515       if (Summarized)
1516         os << ", which is not memory allocated by ";
1517       else
1518         os << "not memory allocated by ";
1519 
1520       printExpectedAllocName(os, C, DeallocExpr);
1521     }
1522 
1523     BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
1524     R->markInteresting(MR);
1525     R->addRange(Range);
1526     C.emitReport(R);
1527   }
1528 }
1529 
1530 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1531                                             SourceRange Range,
1532                                             const Expr *DeallocExpr,
1533                                             const RefState *RS,
1534                                             SymbolRef Sym,
1535                                             bool OwnershipTransferred) const {
1536 
1537   if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1538     return;
1539 
1540   if (ExplodedNode *N = C.generateSink()) {
1541     if (!BT_MismatchedDealloc)
1542       BT_MismatchedDealloc.reset(
1543           new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1544                       "Bad deallocator", "Memory Error"));
1545 
1546     SmallString<100> buf;
1547     llvm::raw_svector_ostream os(buf);
1548 
1549     const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1550     SmallString<20> AllocBuf;
1551     llvm::raw_svector_ostream AllocOs(AllocBuf);
1552     SmallString<20> DeallocBuf;
1553     llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1554 
1555     if (OwnershipTransferred) {
1556       if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1557         os << DeallocOs.str() << " cannot";
1558       else
1559         os << "Cannot";
1560 
1561       os << " take ownership of memory";
1562 
1563       if (printAllocDeallocName(AllocOs, C, AllocExpr))
1564         os << " allocated by " << AllocOs.str();
1565     } else {
1566       os << "Memory";
1567       if (printAllocDeallocName(AllocOs, C, AllocExpr))
1568         os << " allocated by " << AllocOs.str();
1569 
1570       os << " should be deallocated by ";
1571         printExpectedDeallocName(os, RS->getAllocationFamily());
1572 
1573       if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1574         os << ", not " << DeallocOs.str();
1575     }
1576 
1577     BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
1578     R->markInteresting(Sym);
1579     R->addRange(Range);
1580     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1581     C.emitReport(R);
1582   }
1583 }
1584 
1585 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1586                                      SourceRange Range, const Expr *DeallocExpr,
1587                                      const Expr *AllocExpr) const {
1588 
1589 
1590   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1591                                                    CK_MallocPessimistic,
1592                                                    CK_NewDeleteChecker),
1593                                      C, AllocExpr);
1594   if (!CheckKind.hasValue())
1595     return;
1596 
1597   ExplodedNode *N = C.generateSink();
1598   if (!N)
1599     return;
1600 
1601   if (!BT_OffsetFree[*CheckKind])
1602     BT_OffsetFree[*CheckKind].reset(
1603         new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
1604 
1605   SmallString<100> buf;
1606   llvm::raw_svector_ostream os(buf);
1607   SmallString<20> AllocNameBuf;
1608   llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1609 
1610   const MemRegion *MR = ArgVal.getAsRegion();
1611   assert(MR && "Only MemRegion based symbols can have offset free errors");
1612 
1613   RegionOffset Offset = MR->getAsOffset();
1614   assert((Offset.isValid() &&
1615           !Offset.hasSymbolicOffset() &&
1616           Offset.getOffset() != 0) &&
1617          "Only symbols with a valid offset can have offset free errors");
1618 
1619   int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1620 
1621   os << "Argument to ";
1622   if (!printAllocDeallocName(os, C, DeallocExpr))
1623     os << "deallocator";
1624   os << " is offset by "
1625      << offsetBytes
1626      << " "
1627      << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1628      << " from the start of ";
1629   if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1630     os << "memory allocated by " << AllocNameOs.str();
1631   else
1632     os << "allocated memory";
1633 
1634   BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
1635   R->markInteresting(MR->getBaseRegion());
1636   R->addRange(Range);
1637   C.emitReport(R);
1638 }
1639 
1640 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1641                                        SymbolRef Sym) const {
1642 
1643   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1644                                                    CK_MallocPessimistic,
1645                                                    CK_NewDeleteChecker),
1646                                      C, Sym);
1647   if (!CheckKind.hasValue())
1648     return;
1649 
1650   if (ExplodedNode *N = C.generateSink()) {
1651     if (!BT_UseFree[*CheckKind])
1652       BT_UseFree[*CheckKind].reset(new BugType(
1653           CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
1654 
1655     BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
1656                                  "Use of memory after it is freed", N);
1657 
1658     R->markInteresting(Sym);
1659     R->addRange(Range);
1660     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1661     C.emitReport(R);
1662   }
1663 }
1664 
1665 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1666                                      bool Released, SymbolRef Sym,
1667                                      SymbolRef PrevSym) const {
1668 
1669   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1670                                                    CK_MallocPessimistic,
1671                                                    CK_NewDeleteChecker),
1672                                      C, Sym);
1673   if (!CheckKind.hasValue())
1674     return;
1675 
1676   if (ExplodedNode *N = C.generateSink()) {
1677     if (!BT_DoubleFree[*CheckKind])
1678       BT_DoubleFree[*CheckKind].reset(
1679           new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
1680 
1681     BugReport *R =
1682         new BugReport(*BT_DoubleFree[*CheckKind],
1683                       (Released ? "Attempt to free released memory"
1684                                 : "Attempt to free non-owned memory"),
1685                       N);
1686     R->addRange(Range);
1687     R->markInteresting(Sym);
1688     if (PrevSym)
1689       R->markInteresting(PrevSym);
1690     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1691     C.emitReport(R);
1692   }
1693 }
1694 
1695 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1696 
1697   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_NewDeleteChecker),
1698                                      C, Sym);
1699   if (!CheckKind.hasValue())
1700     return;
1701 
1702   if (ExplodedNode *N = C.generateSink()) {
1703     if (!BT_DoubleDelete)
1704       BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1705                                         "Double delete", "Memory Error"));
1706 
1707     BugReport *R = new BugReport(*BT_DoubleDelete,
1708                                  "Attempt to delete released memory", N);
1709 
1710     R->markInteresting(Sym);
1711     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1712     C.emitReport(R);
1713   }
1714 }
1715 
1716 ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1717                                           const CallExpr *CE,
1718                                           bool FreesOnFail,
1719                                           ProgramStateRef State) const {
1720   if (!State)
1721     return nullptr;
1722 
1723   if (CE->getNumArgs() < 2)
1724     return nullptr;
1725 
1726   const Expr *arg0Expr = CE->getArg(0);
1727   const LocationContext *LCtx = C.getLocationContext();
1728   SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
1729   if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
1730     return nullptr;
1731   DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
1732 
1733   SValBuilder &svalBuilder = C.getSValBuilder();
1734 
1735   DefinedOrUnknownSVal PtrEQ =
1736     svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
1737 
1738   // Get the size argument. If there is no size arg then give up.
1739   const Expr *Arg1 = CE->getArg(1);
1740   if (!Arg1)
1741     return nullptr;
1742 
1743   // Get the value of the size argument.
1744   SVal Arg1ValG = State->getSVal(Arg1, LCtx);
1745   if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
1746     return nullptr;
1747   DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
1748 
1749   // Compare the size argument to 0.
1750   DefinedOrUnknownSVal SizeZero =
1751     svalBuilder.evalEQ(State, Arg1Val,
1752                        svalBuilder.makeIntValWithPtrWidth(0, false));
1753 
1754   ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1755   std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
1756   ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1757   std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
1758   // We only assume exceptional states if they are definitely true; if the
1759   // state is under-constrained, assume regular realloc behavior.
1760   bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1761   bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1762 
1763   // If the ptr is NULL and the size is not 0, the call is equivalent to
1764   // malloc(size).
1765   if ( PrtIsNull && !SizeIsZero) {
1766     ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
1767                                                UndefinedVal(), StatePtrIsNull);
1768     return stateMalloc;
1769   }
1770 
1771   if (PrtIsNull && SizeIsZero)
1772     return nullptr;
1773 
1774   // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
1775   assert(!PrtIsNull);
1776   SymbolRef FromPtr = arg0Val.getAsSymbol();
1777   SVal RetVal = State->getSVal(CE, LCtx);
1778   SymbolRef ToPtr = RetVal.getAsSymbol();
1779   if (!FromPtr || !ToPtr)
1780     return nullptr;
1781 
1782   bool ReleasedAllocated = false;
1783 
1784   // If the size is 0, free the memory.
1785   if (SizeIsZero)
1786     if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1787                                                false, ReleasedAllocated)){
1788       // The semantics of the return value are:
1789       // If size was equal to 0, either NULL or a pointer suitable to be passed
1790       // to free() is returned. We just free the input pointer and do not add
1791       // any constrains on the output pointer.
1792       return stateFree;
1793     }
1794 
1795   // Default behavior.
1796   if (ProgramStateRef stateFree =
1797         FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
1798 
1799     ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1800                                                 UnknownVal(), stateFree);
1801     if (!stateRealloc)
1802       return nullptr;
1803 
1804     ReallocPairKind Kind = RPToBeFreedAfterFailure;
1805     if (FreesOnFail)
1806       Kind = RPIsFreeOnFailure;
1807     else if (!ReleasedAllocated)
1808       Kind = RPDoNotTrackAfterFailure;
1809 
1810     // Record the info about the reallocated symbol so that we could properly
1811     // process failed reallocation.
1812     stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
1813                                                    ReallocPair(FromPtr, Kind));
1814     // The reallocated symbol should stay alive for as long as the new symbol.
1815     C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
1816     return stateRealloc;
1817   }
1818   return nullptr;
1819 }
1820 
1821 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
1822                                          ProgramStateRef State) {
1823   if (!State)
1824     return nullptr;
1825 
1826   if (CE->getNumArgs() < 2)
1827     return nullptr;
1828 
1829   SValBuilder &svalBuilder = C.getSValBuilder();
1830   const LocationContext *LCtx = C.getLocationContext();
1831   SVal count = State->getSVal(CE->getArg(0), LCtx);
1832   SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1833   SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
1834                                         svalBuilder.getContext().getSizeType());
1835   SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1836 
1837   return MallocMemAux(C, CE, TotalSize, zeroVal, State);
1838 }
1839 
1840 LeakInfo
1841 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1842                                  CheckerContext &C) const {
1843   const LocationContext *LeakContext = N->getLocationContext();
1844   // Walk the ExplodedGraph backwards and find the first node that referred to
1845   // the tracked symbol.
1846   const ExplodedNode *AllocNode = N;
1847   const MemRegion *ReferenceRegion = nullptr;
1848 
1849   while (N) {
1850     ProgramStateRef State = N->getState();
1851     if (!State->get<RegionState>(Sym))
1852       break;
1853 
1854     // Find the most recent expression bound to the symbol in the current
1855     // context.
1856       if (!ReferenceRegion) {
1857         if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1858           SVal Val = State->getSVal(MR);
1859           if (Val.getAsLocSymbol() == Sym) {
1860             const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
1861             // Do not show local variables belonging to a function other than
1862             // where the error is reported.
1863             if (!VR ||
1864                 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1865               ReferenceRegion = MR;
1866           }
1867         }
1868       }
1869 
1870     // Allocation node, is the last node in the current or parent context in
1871     // which the symbol was tracked.
1872     const LocationContext *NContext = N->getLocationContext();
1873     if (NContext == LeakContext ||
1874         NContext->isParentOf(LeakContext))
1875       AllocNode = N;
1876     N = N->pred_empty() ? nullptr : *(N->pred_begin());
1877   }
1878 
1879   return LeakInfo(AllocNode, ReferenceRegion);
1880 }
1881 
1882 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1883                                CheckerContext &C) const {
1884 
1885   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1886                                                    CK_MallocPessimistic,
1887                                                    CK_NewDeleteLeaksChecker),
1888                                      C, Sym);
1889   if (!CheckKind.hasValue())
1890     return;
1891 
1892   assert(N);
1893   if (!BT_Leak[*CheckKind]) {
1894     BT_Leak[*CheckKind].reset(
1895         new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
1896     // Leaks should not be reported if they are post-dominated by a sink:
1897     // (1) Sinks are higher importance bugs.
1898     // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1899     //     with __noreturn functions such as assert() or exit(). We choose not
1900     //     to report leaks on such paths.
1901     BT_Leak[*CheckKind]->setSuppressOnSink(true);
1902   }
1903 
1904   // Most bug reports are cached at the location where they occurred.
1905   // With leaks, we want to unique them by the location where they were
1906   // allocated, and only report a single path.
1907   PathDiagnosticLocation LocUsedForUniqueing;
1908   const ExplodedNode *AllocNode = nullptr;
1909   const MemRegion *Region = nullptr;
1910   std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1911 
1912   ProgramPoint P = AllocNode->getLocation();
1913   const Stmt *AllocationStmt = nullptr;
1914   if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
1915     AllocationStmt = Exit->getCalleeContext()->getCallSite();
1916   else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
1917     AllocationStmt = SP->getStmt();
1918   if (AllocationStmt)
1919     LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1920                                               C.getSourceManager(),
1921                                               AllocNode->getLocationContext());
1922 
1923   SmallString<200> buf;
1924   llvm::raw_svector_ostream os(buf);
1925   if (Region && Region->canPrintPretty()) {
1926     os << "Potential leak of memory pointed to by ";
1927     Region->printPretty(os);
1928   } else {
1929     os << "Potential memory leak";
1930   }
1931 
1932   BugReport *R =
1933       new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1934                     AllocNode->getLocationContext()->getDecl());
1935   R->markInteresting(Sym);
1936   R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
1937   C.emitReport(R);
1938 }
1939 
1940 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1941                                      CheckerContext &C) const
1942 {
1943   if (!SymReaper.hasDeadSymbols())
1944     return;
1945 
1946   ProgramStateRef state = C.getState();
1947   RegionStateTy RS = state->get<RegionState>();
1948   RegionStateTy::Factory &F = state->get_context<RegionState>();
1949 
1950   SmallVector<SymbolRef, 2> Errors;
1951   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1952     if (SymReaper.isDead(I->first)) {
1953       if (I->second.isAllocated())
1954         Errors.push_back(I->first);
1955       // Remove the dead symbol from the map.
1956       RS = F.remove(RS, I->first);
1957 
1958     }
1959   }
1960 
1961   // Cleanup the Realloc Pairs Map.
1962   ReallocPairsTy RP = state->get<ReallocPairs>();
1963   for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
1964     if (SymReaper.isDead(I->first) ||
1965         SymReaper.isDead(I->second.ReallocatedSym)) {
1966       state = state->remove<ReallocPairs>(I->first);
1967     }
1968   }
1969 
1970   // Cleanup the FreeReturnValue Map.
1971   FreeReturnValueTy FR = state->get<FreeReturnValue>();
1972   for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1973     if (SymReaper.isDead(I->first) ||
1974         SymReaper.isDead(I->second)) {
1975       state = state->remove<FreeReturnValue>(I->first);
1976     }
1977   }
1978 
1979   // Generate leak node.
1980   ExplodedNode *N = C.getPredecessor();
1981   if (!Errors.empty()) {
1982     static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
1983     N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
1984     for (SmallVectorImpl<SymbolRef>::iterator
1985            I = Errors.begin(), E = Errors.end(); I != E; ++I) {
1986       reportLeak(*I, N, C);
1987     }
1988   }
1989 
1990   C.addTransition(state->set<RegionState>(RS), N);
1991 }
1992 
1993 void MallocChecker::checkPreCall(const CallEvent &Call,
1994                                  CheckerContext &C) const {
1995 
1996   if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
1997     SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
1998     if (!Sym || checkDoubleDelete(Sym, C))
1999       return;
2000   }
2001 
2002   // We will check for double free in the post visit.
2003   if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2004     const FunctionDecl *FD = FC->getDecl();
2005     if (!FD)
2006       return;
2007 
2008     ASTContext &Ctx = C.getASTContext();
2009     if ((ChecksEnabled[CK_MallocOptimistic] ||
2010          ChecksEnabled[CK_MallocPessimistic]) &&
2011         (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2012          isCMemFunction(FD, Ctx, AF_IfNameIndex,
2013                         MemoryOperationKind::MOK_Free)))
2014       return;
2015 
2016     if (ChecksEnabled[CK_NewDeleteChecker] &&
2017         isStandardNewDelete(FD, Ctx))
2018       return;
2019   }
2020 
2021   // Check if the callee of a method is deleted.
2022   if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2023     SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2024     if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2025       return;
2026   }
2027 
2028   // Check arguments for being used after free.
2029   for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2030     SVal ArgSVal = Call.getArgSVal(I);
2031     if (ArgSVal.getAs<Loc>()) {
2032       SymbolRef Sym = ArgSVal.getAsSymbol();
2033       if (!Sym)
2034         continue;
2035       if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2036         return;
2037     }
2038   }
2039 }
2040 
2041 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2042   const Expr *E = S->getRetValue();
2043   if (!E)
2044     return;
2045 
2046   // Check if we are returning a symbol.
2047   ProgramStateRef State = C.getState();
2048   SVal RetVal = State->getSVal(E, C.getLocationContext());
2049   SymbolRef Sym = RetVal.getAsSymbol();
2050   if (!Sym)
2051     // If we are returning a field of the allocated struct or an array element,
2052     // the callee could still free the memory.
2053     // TODO: This logic should be a part of generic symbol escape callback.
2054     if (const MemRegion *MR = RetVal.getAsRegion())
2055       if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2056         if (const SymbolicRegion *BMR =
2057               dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2058           Sym = BMR->getSymbol();
2059 
2060   // Check if we are returning freed memory.
2061   if (Sym)
2062     checkUseAfterFree(Sym, C, E);
2063 }
2064 
2065 // TODO: Blocks should be either inlined or should call invalidate regions
2066 // upon invocation. After that's in place, special casing here will not be
2067 // needed.
2068 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2069                                   CheckerContext &C) const {
2070 
2071   // Scan the BlockDecRefExprs for any object the retain count checker
2072   // may be tracking.
2073   if (!BE->getBlockDecl()->hasCaptures())
2074     return;
2075 
2076   ProgramStateRef state = C.getState();
2077   const BlockDataRegion *R =
2078     cast<BlockDataRegion>(state->getSVal(BE,
2079                                          C.getLocationContext()).getAsRegion());
2080 
2081   BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2082                                             E = R->referenced_vars_end();
2083 
2084   if (I == E)
2085     return;
2086 
2087   SmallVector<const MemRegion*, 10> Regions;
2088   const LocationContext *LC = C.getLocationContext();
2089   MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2090 
2091   for ( ; I != E; ++I) {
2092     const VarRegion *VR = I.getCapturedRegion();
2093     if (VR->getSuperRegion() == R) {
2094       VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2095     }
2096     Regions.push_back(VR);
2097   }
2098 
2099   state =
2100     state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2101                                     Regions.data() + Regions.size()).getState();
2102   C.addTransition(state);
2103 }
2104 
2105 bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2106   assert(Sym);
2107   const RefState *RS = C.getState()->get<RegionState>(Sym);
2108   return (RS && RS->isReleased());
2109 }
2110 
2111 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2112                                       const Stmt *S) const {
2113 
2114   if (isReleased(Sym, C)) {
2115     ReportUseAfterFree(C, S->getSourceRange(), Sym);
2116     return true;
2117   }
2118 
2119   return false;
2120 }
2121 
2122 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2123 
2124   if (isReleased(Sym, C)) {
2125     ReportDoubleDelete(C, Sym);
2126     return true;
2127   }
2128   return false;
2129 }
2130 
2131 // Check if the location is a freed symbolic region.
2132 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2133                                   CheckerContext &C) const {
2134   SymbolRef Sym = l.getLocSymbolInBase();
2135   if (Sym)
2136     checkUseAfterFree(Sym, C, S);
2137 }
2138 
2139 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2140 // it - assuming that allocation failed on this path.
2141 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2142                                               SVal Cond,
2143                                               bool Assumption) const {
2144   RegionStateTy RS = state->get<RegionState>();
2145   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2146     // If the symbol is assumed to be NULL, remove it from consideration.
2147     ConstraintManager &CMgr = state->getConstraintManager();
2148     ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2149     if (AllocFailed.isConstrainedTrue())
2150       state = state->remove<RegionState>(I.getKey());
2151   }
2152 
2153   // Realloc returns 0 when reallocation fails, which means that we should
2154   // restore the state of the pointer being reallocated.
2155   ReallocPairsTy RP = state->get<ReallocPairs>();
2156   for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2157     // If the symbol is assumed to be NULL, remove it from consideration.
2158     ConstraintManager &CMgr = state->getConstraintManager();
2159     ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2160     if (!AllocFailed.isConstrainedTrue())
2161       continue;
2162 
2163     SymbolRef ReallocSym = I.getData().ReallocatedSym;
2164     if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2165       if (RS->isReleased()) {
2166         if (I.getData().Kind == RPToBeFreedAfterFailure)
2167           state = state->set<RegionState>(ReallocSym,
2168               RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2169         else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2170           state = state->remove<RegionState>(ReallocSym);
2171         else
2172           assert(I.getData().Kind == RPIsFreeOnFailure);
2173       }
2174     }
2175     state = state->remove<ReallocPairs>(I.getKey());
2176   }
2177 
2178   return state;
2179 }
2180 
2181 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2182                                               const CallEvent *Call,
2183                                               ProgramStateRef State,
2184                                               SymbolRef &EscapingSymbol) const {
2185   assert(Call);
2186   EscapingSymbol = nullptr;
2187 
2188   // For now, assume that any C++ or block call can free memory.
2189   // TODO: If we want to be more optimistic here, we'll need to make sure that
2190   // regions escape to C++ containers. They seem to do that even now, but for
2191   // mysterious reasons.
2192   if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2193     return true;
2194 
2195   // Check Objective-C messages by selector name.
2196   if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2197     // If it's not a framework call, or if it takes a callback, assume it
2198     // can free memory.
2199     if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
2200       return true;
2201 
2202     // If it's a method we know about, handle it explicitly post-call.
2203     // This should happen before the "freeWhenDone" check below.
2204     if (isKnownDeallocObjCMethodName(*Msg))
2205       return false;
2206 
2207     // If there's a "freeWhenDone" parameter, but the method isn't one we know
2208     // about, we can't be sure that the object will use free() to deallocate the
2209     // memory, so we can't model it explicitly. The best we can do is use it to
2210     // decide whether the pointer escapes.
2211     if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2212       return *FreeWhenDone;
2213 
2214     // If the first selector piece ends with "NoCopy", and there is no
2215     // "freeWhenDone" parameter set to zero, we know ownership is being
2216     // transferred. Again, though, we can't be sure that the object will use
2217     // free() to deallocate the memory, so we can't model it explicitly.
2218     StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2219     if (FirstSlot.endswith("NoCopy"))
2220       return true;
2221 
2222     // If the first selector starts with addPointer, insertPointer,
2223     // or replacePointer, assume we are dealing with NSPointerArray or similar.
2224     // This is similar to C++ containers (vector); we still might want to check
2225     // that the pointers get freed by following the container itself.
2226     if (FirstSlot.startswith("addPointer") ||
2227         FirstSlot.startswith("insertPointer") ||
2228         FirstSlot.startswith("replacePointer") ||
2229         FirstSlot.equals("valueWithPointer")) {
2230       return true;
2231     }
2232 
2233     // We should escape receiver on call to 'init'. This is especially relevant
2234     // to the receiver, as the corresponding symbol is usually not referenced
2235     // after the call.
2236     if (Msg->getMethodFamily() == OMF_init) {
2237       EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2238       return true;
2239     }
2240 
2241     // Otherwise, assume that the method does not free memory.
2242     // Most framework methods do not free memory.
2243     return false;
2244   }
2245 
2246   // At this point the only thing left to handle is straight function calls.
2247   const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2248   if (!FD)
2249     return true;
2250 
2251   ASTContext &ASTC = State->getStateManager().getContext();
2252 
2253   // If it's one of the allocation functions we can reason about, we model
2254   // its behavior explicitly.
2255   if (isMemFunction(FD, ASTC))
2256     return false;
2257 
2258   // If it's not a system call, assume it frees memory.
2259   if (!Call->isInSystemHeader())
2260     return true;
2261 
2262   // White list the system functions whose arguments escape.
2263   const IdentifierInfo *II = FD->getIdentifier();
2264   if (!II)
2265     return true;
2266   StringRef FName = II->getName();
2267 
2268   // White list the 'XXXNoCopy' CoreFoundation functions.
2269   // We specifically check these before
2270   if (FName.endswith("NoCopy")) {
2271     // Look for the deallocator argument. We know that the memory ownership
2272     // is not transferred only if the deallocator argument is
2273     // 'kCFAllocatorNull'.
2274     for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2275       const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2276       if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2277         StringRef DeallocatorName = DE->getFoundDecl()->getName();
2278         if (DeallocatorName == "kCFAllocatorNull")
2279           return false;
2280       }
2281     }
2282     return true;
2283   }
2284 
2285   // Associating streams with malloced buffers. The pointer can escape if
2286   // 'closefn' is specified (and if that function does free memory),
2287   // but it will not if closefn is not specified.
2288   // Currently, we do not inspect the 'closefn' function (PR12101).
2289   if (FName == "funopen")
2290     if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2291       return false;
2292 
2293   // Do not warn on pointers passed to 'setbuf' when used with std streams,
2294   // these leaks might be intentional when setting the buffer for stdio.
2295   // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2296   if (FName == "setbuf" || FName =="setbuffer" ||
2297       FName == "setlinebuf" || FName == "setvbuf") {
2298     if (Call->getNumArgs() >= 1) {
2299       const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2300       if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2301         if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2302           if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2303             return true;
2304     }
2305   }
2306 
2307   // A bunch of other functions which either take ownership of a pointer or
2308   // wrap the result up in a struct or object, meaning it can be freed later.
2309   // (See RetainCountChecker.) Not all the parameters here are invalidated,
2310   // but the Malloc checker cannot differentiate between them. The right way
2311   // of doing this would be to implement a pointer escapes callback.
2312   if (FName == "CGBitmapContextCreate" ||
2313       FName == "CGBitmapContextCreateWithData" ||
2314       FName == "CVPixelBufferCreateWithBytes" ||
2315       FName == "CVPixelBufferCreateWithPlanarBytes" ||
2316       FName == "OSAtomicEnqueue") {
2317     return true;
2318   }
2319 
2320   // Handle cases where we know a buffer's /address/ can escape.
2321   // Note that the above checks handle some special cases where we know that
2322   // even though the address escapes, it's still our responsibility to free the
2323   // buffer.
2324   if (Call->argumentsMayEscape())
2325     return true;
2326 
2327   // Otherwise, assume that the function does not free memory.
2328   // Most system calls do not free the memory.
2329   return false;
2330 }
2331 
2332 static bool retTrue(const RefState *RS) {
2333   return true;
2334 }
2335 
2336 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2337   return (RS->getAllocationFamily() == AF_CXXNewArray ||
2338           RS->getAllocationFamily() == AF_CXXNew);
2339 }
2340 
2341 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2342                                              const InvalidatedSymbols &Escaped,
2343                                              const CallEvent *Call,
2344                                              PointerEscapeKind Kind) const {
2345   return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2346 }
2347 
2348 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2349                                               const InvalidatedSymbols &Escaped,
2350                                               const CallEvent *Call,
2351                                               PointerEscapeKind Kind) const {
2352   return checkPointerEscapeAux(State, Escaped, Call, Kind,
2353                                &checkIfNewOrNewArrayFamily);
2354 }
2355 
2356 ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2357                                               const InvalidatedSymbols &Escaped,
2358                                               const CallEvent *Call,
2359                                               PointerEscapeKind Kind,
2360                                   bool(*CheckRefState)(const RefState*)) const {
2361   // If we know that the call does not free memory, or we want to process the
2362   // call later, keep tracking the top level arguments.
2363   SymbolRef EscapingSymbol = nullptr;
2364   if (Kind == PSK_DirectEscapeOnCall &&
2365       !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2366                                                     EscapingSymbol) &&
2367       !EscapingSymbol) {
2368     return State;
2369   }
2370 
2371   for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2372        E = Escaped.end();
2373        I != E; ++I) {
2374     SymbolRef sym = *I;
2375 
2376     if (EscapingSymbol && EscapingSymbol != sym)
2377       continue;
2378 
2379     if (const RefState *RS = State->get<RegionState>(sym)) {
2380       if (RS->isAllocated() && CheckRefState(RS)) {
2381         State = State->remove<RegionState>(sym);
2382         State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2383       }
2384     }
2385   }
2386   return State;
2387 }
2388 
2389 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2390                                          ProgramStateRef prevState) {
2391   ReallocPairsTy currMap = currState->get<ReallocPairs>();
2392   ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2393 
2394   for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2395        I != E; ++I) {
2396     SymbolRef sym = I.getKey();
2397     if (!currMap.lookup(sym))
2398       return sym;
2399   }
2400 
2401   return nullptr;
2402 }
2403 
2404 PathDiagnosticPiece *
2405 MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2406                                            const ExplodedNode *PrevN,
2407                                            BugReporterContext &BRC,
2408                                            BugReport &BR) {
2409   ProgramStateRef state = N->getState();
2410   ProgramStateRef statePrev = PrevN->getState();
2411 
2412   const RefState *RS = state->get<RegionState>(Sym);
2413   const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2414   if (!RS)
2415     return nullptr;
2416 
2417   const Stmt *S = nullptr;
2418   const char *Msg = nullptr;
2419   StackHintGeneratorForSymbol *StackHint = nullptr;
2420 
2421   // Retrieve the associated statement.
2422   ProgramPoint ProgLoc = N->getLocation();
2423   if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
2424     S = SP->getStmt();
2425   } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
2426     S = Exit->getCalleeContext()->getCallSite();
2427   } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
2428     // If an assumption was made on a branch, it should be caught
2429     // here by looking at the state transition.
2430     S = Edge->getSrc()->getTerminator();
2431   }
2432 
2433   if (!S)
2434     return nullptr;
2435 
2436   // FIXME: We will eventually need to handle non-statement-based events
2437   // (__attribute__((cleanup))).
2438 
2439   // Find out if this is an interesting point and what is the kind.
2440   if (Mode == Normal) {
2441     if (isAllocated(RS, RSPrev, S)) {
2442       Msg = "Memory is allocated";
2443       StackHint = new StackHintGeneratorForSymbol(Sym,
2444                                                   "Returned allocated memory");
2445     } else if (isReleased(RS, RSPrev, S)) {
2446       Msg = "Memory is released";
2447       StackHint = new StackHintGeneratorForSymbol(Sym,
2448                                              "Returning; memory was released");
2449     } else if (isRelinquished(RS, RSPrev, S)) {
2450       Msg = "Memory ownership is transferred";
2451       StackHint = new StackHintGeneratorForSymbol(Sym, "");
2452     } else if (isReallocFailedCheck(RS, RSPrev, S)) {
2453       Mode = ReallocationFailed;
2454       Msg = "Reallocation failed";
2455       StackHint = new StackHintGeneratorForReallocationFailed(Sym,
2456                                                        "Reallocation failed");
2457 
2458       if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2459         // Is it possible to fail two reallocs WITHOUT testing in between?
2460         assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2461           "We only support one failed realloc at a time.");
2462         BR.markInteresting(sym);
2463         FailedReallocSymbol = sym;
2464       }
2465     }
2466 
2467   // We are in a special mode if a reallocation failed later in the path.
2468   } else if (Mode == ReallocationFailed) {
2469     assert(FailedReallocSymbol && "No symbol to look for.");
2470 
2471     // Is this is the first appearance of the reallocated symbol?
2472     if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
2473       // We're at the reallocation point.
2474       Msg = "Attempt to reallocate memory";
2475       StackHint = new StackHintGeneratorForSymbol(Sym,
2476                                                  "Returned reallocated memory");
2477       FailedReallocSymbol = nullptr;
2478       Mode = Normal;
2479     }
2480   }
2481 
2482   if (!Msg)
2483     return nullptr;
2484   assert(StackHint);
2485 
2486   // Generate the extra diagnostic.
2487   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2488                              N->getLocationContext());
2489   return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
2490 }
2491 
2492 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2493                                const char *NL, const char *Sep) const {
2494 
2495   RegionStateTy RS = State->get<RegionState>();
2496 
2497   if (!RS.isEmpty()) {
2498     Out << Sep << "MallocChecker :" << NL;
2499     for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2500       const RefState *RefS = State->get<RegionState>(I.getKey());
2501       AllocationFamily Family = RefS->getAllocationFamily();
2502       auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
2503                                                        CK_MallocPessimistic,
2504                                                        CK_NewDeleteChecker),
2505                                          Family);
2506       I.getKey()->dumpToStream(Out);
2507       Out << " : ";
2508       I.getData().dump(Out);
2509       if (CheckKind.hasValue())
2510         Out << " (" << CheckNames[*CheckKind].getName() << ")";
2511       Out << NL;
2512     }
2513   }
2514 }
2515 
2516 void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2517   registerCStringCheckerBasic(mgr);
2518   MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2519   checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2520   checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2521       mgr.getCurrentCheckName();
2522   // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2523   // checker.
2524   if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
2525     checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
2526 }
2527 
2528 #define REGISTER_CHECKER(name)                                                 \
2529   void ento::register##name(CheckerManager &mgr) {                             \
2530     registerCStringCheckerBasic(mgr);                                          \
2531     MallocChecker *checker = mgr.registerChecker<MallocChecker>();             \
2532     checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
2533     checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2534   }
2535 
2536 REGISTER_CHECKER(MallocPessimistic)
2537 REGISTER_CHECKER(MallocOptimistic)
2538 REGISTER_CHECKER(NewDeleteChecker)
2539 REGISTER_CHECKER(MismatchedDeallocatorChecker)
2540