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