xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (revision c38d7952b2ac8fe73ee82f11019b12b07a739520)
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_MallocPessimistic,
174     CK_MallocOptimistic,
175     CK_NewDeleteChecker,
176     CK_NewDeleteLeaksChecker,
177     CK_MismatchedDeallocatorChecker,
178     CK_NumCheckKinds
179   };
180 
181   enum class MemoryOperationKind {
182     MOK_Allocate,
183     MOK_Free,
184     MOK_Any
185   };
186 
187   DefaultBool ChecksEnabled[CK_NumCheckKinds];
188   CheckName CheckNames[CK_NumCheckKinds];
189   typedef llvm::SmallVector<CheckKind, CK_NumCheckKinds> CKVecTy;
190 
191   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
192   void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
193   void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
194   void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
195   void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
196   void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
197   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
198   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
199   ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
200                             bool Assumption) const;
201   void checkLocation(SVal l, bool isLoad, const Stmt *S,
202                      CheckerContext &C) const;
203 
204   ProgramStateRef checkPointerEscape(ProgramStateRef State,
205                                     const InvalidatedSymbols &Escaped,
206                                     const CallEvent *Call,
207                                     PointerEscapeKind Kind) const;
208   ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
209                                           const InvalidatedSymbols &Escaped,
210                                           const CallEvent *Call,
211                                           PointerEscapeKind Kind) const;
212 
213   void printState(raw_ostream &Out, ProgramStateRef State,
214                   const char *NL, const char *Sep) const override;
215 
216 private:
217   mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
218   mutable std::unique_ptr<BugType> BT_DoubleDelete;
219   mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
220   mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
221   mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
222   mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
223   mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
224   mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
225   mutable IdentifierInfo *II_alloca, *II_malloc, *II_free, *II_realloc,
226                          *II_calloc, *II_valloc, *II_reallocf, *II_strndup,
227                          *II_strdup, *II_kmalloc, *II_if_nameindex,
228                          *II_if_freenameindex;
229   mutable Optional<uint64_t> KernelZeroFlagVal;
230 
231   void initIdentifierInfo(ASTContext &C) const;
232 
233   /// \brief Determine family of a deallocation expression.
234   AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
235 
236   /// \brief Print names of allocators and deallocators.
237   ///
238   /// \returns true on success.
239   bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
240                              const Expr *E) const;
241 
242   /// \brief Print expected name of an allocator based on the deallocator's
243   /// family derived from the DeallocExpr.
244   void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
245                               const Expr *DeallocExpr) const;
246   /// \brief Print expected name of a deallocator based on the allocator's
247   /// family.
248   void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
249 
250   ///@{
251   /// Check if this is one of the functions which can allocate/reallocate memory
252   /// pointed to by one of its arguments.
253   bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
254   bool isCMemFunction(const FunctionDecl *FD,
255                       ASTContext &C,
256                       AllocationFamily Family,
257                       MemoryOperationKind MemKind) const;
258   bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
259   ///@}
260   ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
261                                        const CallExpr *CE,
262                                        const OwnershipAttr* Att,
263                                        ProgramStateRef State) const;
264   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
265                                       const Expr *SizeEx, SVal Init,
266                                       ProgramStateRef State,
267                                       AllocationFamily Family = AF_Malloc);
268   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
269                                       SVal SizeEx, SVal Init,
270                                       ProgramStateRef State,
271                                       AllocationFamily Family = AF_Malloc);
272 
273   // Check if this malloc() for special flags. At present that means M_ZERO or
274   // __GFP_ZERO (in which case, treat it like calloc).
275   llvm::Optional<ProgramStateRef>
276   performKernelMalloc(const CallExpr *CE, CheckerContext &C,
277                       const ProgramStateRef &State) const;
278 
279   /// Update the RefState to reflect the new memory allocation.
280   static ProgramStateRef
281   MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
282                        AllocationFamily Family = AF_Malloc);
283 
284   ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
285                               const OwnershipAttr* Att,
286                               ProgramStateRef State) const;
287   ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
288                              ProgramStateRef state, unsigned Num,
289                              bool Hold,
290                              bool &ReleasedAllocated,
291                              bool ReturnsNullOnFailure = false) const;
292   ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
293                              const Expr *ParentExpr,
294                              ProgramStateRef State,
295                              bool Hold,
296                              bool &ReleasedAllocated,
297                              bool ReturnsNullOnFailure = false) const;
298 
299   ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
300                              bool FreesMemOnFailure,
301                              ProgramStateRef State) const;
302   static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
303                                    ProgramStateRef State);
304 
305   ///\brief Check if the memory associated with this symbol was released.
306   bool isReleased(SymbolRef Sym, CheckerContext &C) const;
307 
308   bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
309 
310   bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
311 
312   /// Check if the function is known free memory, or if it is
313   /// "interesting" and should be modeled explicitly.
314   ///
315   /// \param [out] EscapingSymbol A function might not free memory in general,
316   ///   but could be known to free a particular symbol. In this case, false is
317   ///   returned and the single escaping symbol is returned through the out
318   ///   parameter.
319   ///
320   /// We assume that pointers do not escape through calls to system functions
321   /// not handled by this checker.
322   bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
323                                    ProgramStateRef State,
324                                    SymbolRef &EscapingSymbol) const;
325 
326   // Implementation of the checkPointerEscape callabcks.
327   ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
328                                   const InvalidatedSymbols &Escaped,
329                                   const CallEvent *Call,
330                                   PointerEscapeKind Kind,
331                                   bool(*CheckRefState)(const RefState*)) const;
332 
333   ///@{
334   /// Tells if a given family/call/symbol is tracked by the current checker.
335   /// Looks through incoming CheckKind(s) and returns the kind of the checker
336   /// responsible for this family/call/symbol.
337   Optional<CheckKind> getCheckIfTracked(CheckKind CK,
338                                         AllocationFamily Family) const;
339   Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec,
340                                         AllocationFamily Family) const;
341   Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
342                                         const Stmt *AllocDeallocStmt) const;
343   Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
344                                         SymbolRef Sym) const;
345   ///@}
346   static bool SummarizeValue(raw_ostream &os, SVal V);
347   static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
348   void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
349                      const Expr *DeallocExpr) const;
350   void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
351                         SourceRange Range) const;
352   void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
353                                const Expr *DeallocExpr, const RefState *RS,
354                                SymbolRef Sym, bool OwnershipTransferred) const;
355   void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
356                         const Expr *DeallocExpr,
357                         const Expr *AllocExpr = nullptr) const;
358   void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
359                           SymbolRef Sym) const;
360   void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
361                         SymbolRef Sym, SymbolRef PrevSym) const;
362 
363   void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
364 
365   /// Find the location of the allocation for Sym on the path leading to the
366   /// exploded node N.
367   LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
368                              CheckerContext &C) const;
369 
370   void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
371 
372   /// The bug visitor which allows us to print extra diagnostics along the
373   /// BugReport path. For example, showing the allocation site of the leaked
374   /// region.
375   class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
376   protected:
377     enum NotificationMode {
378       Normal,
379       ReallocationFailed
380     };
381 
382     // The allocated region symbol tracked by the main analysis.
383     SymbolRef Sym;
384 
385     // The mode we are in, i.e. what kind of diagnostics will be emitted.
386     NotificationMode Mode;
387 
388     // A symbol from when the primary region should have been reallocated.
389     SymbolRef FailedReallocSymbol;
390 
391     bool IsLeak;
392 
393   public:
394     MallocBugVisitor(SymbolRef S, bool isLeak = false)
395        : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
396 
397     virtual ~MallocBugVisitor() {}
398 
399     void Profile(llvm::FoldingSetNodeID &ID) const override {
400       static int X = 0;
401       ID.AddPointer(&X);
402       ID.AddPointer(Sym);
403     }
404 
405     inline bool isAllocated(const RefState *S, const RefState *SPrev,
406                             const Stmt *Stmt) {
407       // Did not track -> allocated. Other state (released) -> allocated.
408       return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
409               (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
410     }
411 
412     inline bool isReleased(const RefState *S, const RefState *SPrev,
413                            const Stmt *Stmt) {
414       // Did not track -> released. Other state (allocated) -> released.
415       return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
416               (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
417     }
418 
419     inline bool isRelinquished(const RefState *S, const RefState *SPrev,
420                                const Stmt *Stmt) {
421       // Did not track -> relinquished. Other state (allocated) -> relinquished.
422       return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
423                                               isa<ObjCPropertyRefExpr>(Stmt)) &&
424               (S && S->isRelinquished()) &&
425               (!SPrev || !SPrev->isRelinquished()));
426     }
427 
428     inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
429                                      const Stmt *Stmt) {
430       // If the expression is not a call, and the state change is
431       // released -> allocated, it must be the realloc return value
432       // check. If we have to handle more cases here, it might be cleaner just
433       // to track this extra bit in the state itself.
434       return ((!Stmt || !isa<CallExpr>(Stmt)) &&
435               (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
436     }
437 
438     PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
439                                    const ExplodedNode *PrevN,
440                                    BugReporterContext &BRC,
441                                    BugReport &BR) override;
442 
443     std::unique_ptr<PathDiagnosticPiece>
444     getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
445                BugReport &BR) override {
446       if (!IsLeak)
447         return nullptr;
448 
449       PathDiagnosticLocation L =
450         PathDiagnosticLocation::createEndOfPath(EndPathNode,
451                                                 BRC.getSourceManager());
452       // Do not add the statement itself as a range in case of leak.
453       return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
454                                                          false);
455     }
456 
457   private:
458     class StackHintGeneratorForReallocationFailed
459         : public StackHintGeneratorForSymbol {
460     public:
461       StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
462         : StackHintGeneratorForSymbol(S, M) {}
463 
464       std::string getMessageForArg(const Expr *ArgE,
465                                    unsigned ArgIndex) override {
466         // Printed parameters start at 1, not 0.
467         ++ArgIndex;
468 
469         SmallString<200> buf;
470         llvm::raw_svector_ostream os(buf);
471 
472         os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
473            << " parameter failed";
474 
475         return os.str();
476       }
477 
478       std::string getMessageForReturn(const CallExpr *CallExpr) override {
479         return "Reallocation of returned value failed";
480       }
481     };
482   };
483 };
484 } // end anonymous namespace
485 
486 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
487 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
488 
489 // A map from the freed symbol to the symbol representing the return value of
490 // the free function.
491 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
492 
493 namespace {
494 class StopTrackingCallback : public SymbolVisitor {
495   ProgramStateRef state;
496 public:
497   StopTrackingCallback(ProgramStateRef st) : state(st) {}
498   ProgramStateRef getState() const { return state; }
499 
500   bool VisitSymbol(SymbolRef sym) override {
501     state = state->remove<RegionState>(sym);
502     return true;
503   }
504 };
505 } // end anonymous namespace
506 
507 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
508   if (II_malloc)
509     return;
510   II_alloca = &Ctx.Idents.get("alloca");
511   II_malloc = &Ctx.Idents.get("malloc");
512   II_free = &Ctx.Idents.get("free");
513   II_realloc = &Ctx.Idents.get("realloc");
514   II_reallocf = &Ctx.Idents.get("reallocf");
515   II_calloc = &Ctx.Idents.get("calloc");
516   II_valloc = &Ctx.Idents.get("valloc");
517   II_strdup = &Ctx.Idents.get("strdup");
518   II_strndup = &Ctx.Idents.get("strndup");
519   II_kmalloc = &Ctx.Idents.get("kmalloc");
520   II_if_nameindex = &Ctx.Idents.get("if_nameindex");
521   II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
522 }
523 
524 bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
525   if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
526     return true;
527 
528   if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
529     return true;
530 
531   if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
532     return true;
533 
534   if (isStandardNewDelete(FD, C))
535     return true;
536 
537   return false;
538 }
539 
540 bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
541                                    ASTContext &C,
542                                    AllocationFamily Family,
543                                    MemoryOperationKind MemKind) const {
544   if (!FD)
545     return false;
546 
547   bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
548                     MemKind == MemoryOperationKind::MOK_Free);
549   bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
550                      MemKind == MemoryOperationKind::MOK_Allocate);
551 
552   if (FD->getKind() == Decl::Function) {
553     const IdentifierInfo *FunI = FD->getIdentifier();
554     initIdentifierInfo(C);
555 
556     if (Family == AF_Malloc && CheckFree) {
557       if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
558         return true;
559     }
560 
561     if (Family == AF_Malloc && CheckAlloc) {
562       if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
563           FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
564           FunI == II_strndup || FunI == II_kmalloc)
565         return true;
566     }
567 
568     if (Family == AF_IfNameIndex && CheckFree) {
569       if (FunI == II_if_freenameindex)
570         return true;
571     }
572 
573     if (Family == AF_IfNameIndex && CheckAlloc) {
574       if (FunI == II_if_nameindex)
575         return true;
576     }
577 
578     if (Family == AF_Alloca && CheckAlloc) {
579       if (FunI == II_alloca)
580         return true;
581     }
582   }
583 
584   if (Family != AF_Malloc)
585     return false;
586 
587   if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs()) {
588     for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
589       OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
590       if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
591         if (CheckFree)
592           return true;
593       } else if (OwnKind == OwnershipAttr::Returns) {
594         if (CheckAlloc)
595           return true;
596       }
597     }
598   }
599 
600   return false;
601 }
602 
603 // Tells if the callee is one of the following:
604 // 1) A global non-placement new/delete operator function.
605 // 2) A global placement operator function with the single placement argument
606 //    of type std::nothrow_t.
607 bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
608                                         ASTContext &C) const {
609   if (!FD)
610     return false;
611 
612   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
613   if (Kind != OO_New && Kind != OO_Array_New &&
614       Kind != OO_Delete && Kind != OO_Array_Delete)
615     return false;
616 
617   // Skip all operator new/delete methods.
618   if (isa<CXXMethodDecl>(FD))
619     return false;
620 
621   // Return true if tested operator is a standard placement nothrow operator.
622   if (FD->getNumParams() == 2) {
623     QualType T = FD->getParamDecl(1)->getType();
624     if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
625       return II->getName().equals("nothrow_t");
626   }
627 
628   // Skip placement operators.
629   if (FD->getNumParams() != 1 || FD->isVariadic())
630     return false;
631 
632   // One of the standard new/new[]/delete/delete[] non-placement operators.
633   return true;
634 }
635 
636 llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
637   const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
638   // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
639   //
640   // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
641   //
642   // One of the possible flags is M_ZERO, which means 'give me back an
643   // allocation which is already zeroed', like calloc.
644 
645   // 2-argument kmalloc(), as used in the Linux kernel:
646   //
647   // void *kmalloc(size_t size, gfp_t flags);
648   //
649   // Has the similar flag value __GFP_ZERO.
650 
651   // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
652   // code could be shared.
653 
654   ASTContext &Ctx = C.getASTContext();
655   llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
656 
657   if (!KernelZeroFlagVal.hasValue()) {
658     if (OS == llvm::Triple::FreeBSD)
659       KernelZeroFlagVal = 0x0100;
660     else if (OS == llvm::Triple::NetBSD)
661       KernelZeroFlagVal = 0x0002;
662     else if (OS == llvm::Triple::OpenBSD)
663       KernelZeroFlagVal = 0x0008;
664     else if (OS == llvm::Triple::Linux)
665       // __GFP_ZERO
666       KernelZeroFlagVal = 0x8000;
667     else
668       // FIXME: We need a more general way of getting the M_ZERO value.
669       // See also: O_CREAT in UnixAPIChecker.cpp.
670 
671       // Fall back to normal malloc behavior on platforms where we don't
672       // know M_ZERO.
673       return None;
674   }
675 
676   // We treat the last argument as the flags argument, and callers fall-back to
677   // normal malloc on a None return. This works for the FreeBSD kernel malloc
678   // as well as Linux kmalloc.
679   if (CE->getNumArgs() < 2)
680     return None;
681 
682   const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
683   const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
684   if (!V.getAs<NonLoc>()) {
685     // The case where 'V' can be a location can only be due to a bad header,
686     // so in this case bail out.
687     return None;
688   }
689 
690   NonLoc Flags = V.castAs<NonLoc>();
691   NonLoc ZeroFlag = C.getSValBuilder()
692       .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
693       .castAs<NonLoc>();
694   SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
695                                                       Flags, ZeroFlag,
696                                                       FlagsEx->getType());
697   if (MaskedFlagsUC.isUnknownOrUndef())
698     return None;
699   DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
700 
701   // Check if maskedFlags is non-zero.
702   ProgramStateRef TrueState, FalseState;
703   std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
704 
705   // If M_ZERO is set, treat this like calloc (initialized).
706   if (TrueState && !FalseState) {
707     SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
708     return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
709   }
710 
711   return None;
712 }
713 
714 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
715   if (C.wasInlined)
716     return;
717 
718   const FunctionDecl *FD = C.getCalleeDecl(CE);
719   if (!FD)
720     return;
721 
722   ProgramStateRef State = C.getState();
723   bool ReleasedAllocatedMemory = false;
724 
725   if (FD->getKind() == Decl::Function) {
726     initIdentifierInfo(C.getASTContext());
727     IdentifierInfo *FunI = FD->getIdentifier();
728 
729     if (FunI == II_malloc) {
730       if (CE->getNumArgs() < 1)
731         return;
732       if (CE->getNumArgs() < 3) {
733         State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
734       } else if (CE->getNumArgs() == 3) {
735         llvm::Optional<ProgramStateRef> MaybeState =
736           performKernelMalloc(CE, C, State);
737         if (MaybeState.hasValue())
738           State = MaybeState.getValue();
739         else
740           State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
741       }
742     } else if (FunI == II_kmalloc) {
743       llvm::Optional<ProgramStateRef> MaybeState =
744         performKernelMalloc(CE, C, State);
745       if (MaybeState.hasValue())
746         State = MaybeState.getValue();
747       else
748         State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
749     } else if (FunI == II_valloc) {
750       if (CE->getNumArgs() < 1)
751         return;
752       State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
753     } else if (FunI == II_realloc) {
754       State = ReallocMem(C, CE, false, State);
755     } else if (FunI == II_reallocf) {
756       State = ReallocMem(C, CE, true, State);
757     } else if (FunI == II_calloc) {
758       State = CallocMem(C, CE, State);
759     } else if (FunI == II_free) {
760       State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
761     } else if (FunI == II_strdup) {
762       State = MallocUpdateRefState(C, CE, State);
763     } else if (FunI == II_strndup) {
764       State = MallocUpdateRefState(C, CE, State);
765     } else if (FunI == II_alloca) {
766       State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
767                            AF_Alloca);
768     } else if (isStandardNewDelete(FD, C.getASTContext())) {
769       // Process direct calls to operator new/new[]/delete/delete[] functions
770       // as distinct from new/new[]/delete/delete[] expressions that are
771       // processed by the checkPostStmt callbacks for CXXNewExpr and
772       // CXXDeleteExpr.
773       OverloadedOperatorKind K = FD->getOverloadedOperator();
774       if (K == OO_New)
775         State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
776                              AF_CXXNew);
777       else if (K == OO_Array_New)
778         State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
779                              AF_CXXNewArray);
780       else if (K == OO_Delete || K == OO_Array_Delete)
781         State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
782       else
783         llvm_unreachable("not a new/delete operator");
784     } else if (FunI == II_if_nameindex) {
785       // Should we model this differently? We can allocate a fixed number of
786       // elements with zeros in the last one.
787       State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
788                            AF_IfNameIndex);
789     } else if (FunI == II_if_freenameindex) {
790       State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
791     }
792   }
793 
794   if (ChecksEnabled[CK_MallocOptimistic] ||
795       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_MallocOptimistic ||
1366         CK == CK_MallocPessimistic) {
1367       return CK;
1368     }
1369     return Optional<MallocChecker::CheckKind>();
1370   }
1371   case AF_CXXNew:
1372   case AF_CXXNewArray: {
1373     // C++ checkers.
1374     if (CK == CK_NewDeleteChecker ||
1375         CK == CK_NewDeleteLeaksChecker) {
1376       return CK;
1377     }
1378     return Optional<MallocChecker::CheckKind>();
1379   }
1380   case AF_None: {
1381     llvm_unreachable("no family");
1382   }
1383   }
1384   llvm_unreachable("unhandled family");
1385 }
1386 
1387 static MallocChecker::CKVecTy MakeVecFromCK(MallocChecker::CheckKind CK1,
1388                MallocChecker::CheckKind CK2 = MallocChecker::CK_NumCheckKinds,
1389                MallocChecker::CheckKind CK3 = MallocChecker::CK_NumCheckKinds,
1390                MallocChecker::CheckKind CK4 = MallocChecker::CK_NumCheckKinds) {
1391   MallocChecker::CKVecTy CKVec;
1392   CKVec.push_back(CK1);
1393   if (CK2 != MallocChecker::CK_NumCheckKinds) {
1394     CKVec.push_back(CK2);
1395     if (CK3 != MallocChecker::CK_NumCheckKinds) {
1396       CKVec.push_back(CK3);
1397       if (CK4 != MallocChecker::CK_NumCheckKinds)
1398         CKVec.push_back(CK4);
1399     }
1400   }
1401   return CKVec;
1402 }
1403 
1404 Optional<MallocChecker::CheckKind>
1405 MallocChecker::getCheckIfTracked(CKVecTy CKVec, AllocationFamily Family) const {
1406   for (auto CK: CKVec) {
1407     auto RetCK = getCheckIfTracked(CK, Family);
1408     if (RetCK.hasValue())
1409       return RetCK;
1410   }
1411   return Optional<MallocChecker::CheckKind>();
1412 }
1413 
1414 Optional<MallocChecker::CheckKind>
1415 MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
1416                                  const Stmt *AllocDeallocStmt) const {
1417   return getCheckIfTracked(CKVec, getAllocationFamily(C, AllocDeallocStmt));
1418 }
1419 
1420 Optional<MallocChecker::CheckKind>
1421 MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
1422                                  SymbolRef Sym) const {
1423   const RefState *RS = C.getState()->get<RegionState>(Sym);
1424   assert(RS);
1425   return getCheckIfTracked(CKVec, RS->getAllocationFamily());
1426 }
1427 
1428 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1429   if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1430     os << "an integer (" << IntVal->getValue() << ")";
1431   else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1432     os << "a constant address (" << ConstAddr->getValue() << ")";
1433   else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1434     os << "the address of the label '" << Label->getLabel()->getName() << "'";
1435   else
1436     return false;
1437 
1438   return true;
1439 }
1440 
1441 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1442                                     const MemRegion *MR) {
1443   switch (MR->getKind()) {
1444   case MemRegion::FunctionTextRegionKind: {
1445     const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
1446     if (FD)
1447       os << "the address of the function '" << *FD << '\'';
1448     else
1449       os << "the address of a function";
1450     return true;
1451   }
1452   case MemRegion::BlockTextRegionKind:
1453     os << "block text";
1454     return true;
1455   case MemRegion::BlockDataRegionKind:
1456     // FIXME: where the block came from?
1457     os << "a block";
1458     return true;
1459   default: {
1460     const MemSpaceRegion *MS = MR->getMemorySpace();
1461 
1462     if (isa<StackLocalsSpaceRegion>(MS)) {
1463       const VarRegion *VR = dyn_cast<VarRegion>(MR);
1464       const VarDecl *VD;
1465       if (VR)
1466         VD = VR->getDecl();
1467       else
1468         VD = nullptr;
1469 
1470       if (VD)
1471         os << "the address of the local variable '" << VD->getName() << "'";
1472       else
1473         os << "the address of a local stack variable";
1474       return true;
1475     }
1476 
1477     if (isa<StackArgumentsSpaceRegion>(MS)) {
1478       const VarRegion *VR = dyn_cast<VarRegion>(MR);
1479       const VarDecl *VD;
1480       if (VR)
1481         VD = VR->getDecl();
1482       else
1483         VD = nullptr;
1484 
1485       if (VD)
1486         os << "the address of the parameter '" << VD->getName() << "'";
1487       else
1488         os << "the address of a parameter";
1489       return true;
1490     }
1491 
1492     if (isa<GlobalsSpaceRegion>(MS)) {
1493       const VarRegion *VR = dyn_cast<VarRegion>(MR);
1494       const VarDecl *VD;
1495       if (VR)
1496         VD = VR->getDecl();
1497       else
1498         VD = nullptr;
1499 
1500       if (VD) {
1501         if (VD->isStaticLocal())
1502           os << "the address of the static variable '" << VD->getName() << "'";
1503         else
1504           os << "the address of the global variable '" << VD->getName() << "'";
1505       } else
1506         os << "the address of a global variable";
1507       return true;
1508     }
1509 
1510     return false;
1511   }
1512   }
1513 }
1514 
1515 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1516                                   SourceRange Range,
1517                                   const Expr *DeallocExpr) const {
1518 
1519   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1520                                                    CK_MallocPessimistic,
1521                                                    CK_NewDeleteChecker),
1522                                      C, DeallocExpr);
1523   if (!CheckKind.hasValue())
1524     return;
1525 
1526   if (ExplodedNode *N = C.generateSink()) {
1527     if (!BT_BadFree[*CheckKind])
1528       BT_BadFree[*CheckKind].reset(
1529           new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1530 
1531     SmallString<100> buf;
1532     llvm::raw_svector_ostream os(buf);
1533 
1534     const MemRegion *MR = ArgVal.getAsRegion();
1535     while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1536       MR = ER->getSuperRegion();
1537 
1538     os << "Argument to ";
1539     if (!printAllocDeallocName(os, C, DeallocExpr))
1540       os << "deallocator";
1541 
1542     os << " is ";
1543     bool Summarized = MR ? SummarizeRegion(os, MR)
1544                          : SummarizeValue(os, ArgVal);
1545     if (Summarized)
1546       os << ", which is not memory allocated by ";
1547     else
1548       os << "not memory allocated by ";
1549 
1550     printExpectedAllocName(os, C, DeallocExpr);
1551 
1552     BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
1553     R->markInteresting(MR);
1554     R->addRange(Range);
1555     C.emitReport(R);
1556   }
1557 }
1558 
1559 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1560                                      SourceRange Range) const {
1561 
1562   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1563                                                CK_MallocPessimistic,
1564                                                CK_MismatchedDeallocatorChecker),
1565                                      AF_Alloca);
1566   if (!CheckKind.hasValue())
1567     return;
1568 
1569   if (ExplodedNode *N = C.generateSink()) {
1570     if (!BT_FreeAlloca[*CheckKind])
1571       BT_FreeAlloca[*CheckKind].reset(
1572           new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1573 
1574     BugReport *R = new BugReport(*BT_FreeAlloca[*CheckKind],
1575                  "Memory allocated by alloca() should not be deallocated", N);
1576     R->markInteresting(ArgVal.getAsRegion());
1577     R->addRange(Range);
1578     C.emitReport(R);
1579   }
1580 }
1581 
1582 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1583                                             SourceRange Range,
1584                                             const Expr *DeallocExpr,
1585                                             const RefState *RS,
1586                                             SymbolRef Sym,
1587                                             bool OwnershipTransferred) const {
1588 
1589   if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1590     return;
1591 
1592   if (ExplodedNode *N = C.generateSink()) {
1593     if (!BT_MismatchedDealloc)
1594       BT_MismatchedDealloc.reset(
1595           new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1596                       "Bad deallocator", "Memory Error"));
1597 
1598     SmallString<100> buf;
1599     llvm::raw_svector_ostream os(buf);
1600 
1601     const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1602     SmallString<20> AllocBuf;
1603     llvm::raw_svector_ostream AllocOs(AllocBuf);
1604     SmallString<20> DeallocBuf;
1605     llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1606 
1607     if (OwnershipTransferred) {
1608       if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1609         os << DeallocOs.str() << " cannot";
1610       else
1611         os << "Cannot";
1612 
1613       os << " take ownership of memory";
1614 
1615       if (printAllocDeallocName(AllocOs, C, AllocExpr))
1616         os << " allocated by " << AllocOs.str();
1617     } else {
1618       os << "Memory";
1619       if (printAllocDeallocName(AllocOs, C, AllocExpr))
1620         os << " allocated by " << AllocOs.str();
1621 
1622       os << " should be deallocated by ";
1623         printExpectedDeallocName(os, RS->getAllocationFamily());
1624 
1625       if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1626         os << ", not " << DeallocOs.str();
1627     }
1628 
1629     BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
1630     R->markInteresting(Sym);
1631     R->addRange(Range);
1632     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1633     C.emitReport(R);
1634   }
1635 }
1636 
1637 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1638                                      SourceRange Range, const Expr *DeallocExpr,
1639                                      const Expr *AllocExpr) const {
1640 
1641 
1642   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1643                                                    CK_MallocPessimistic,
1644                                                    CK_NewDeleteChecker),
1645                                      C, AllocExpr);
1646   if (!CheckKind.hasValue())
1647     return;
1648 
1649   ExplodedNode *N = C.generateSink();
1650   if (!N)
1651     return;
1652 
1653   if (!BT_OffsetFree[*CheckKind])
1654     BT_OffsetFree[*CheckKind].reset(
1655         new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
1656 
1657   SmallString<100> buf;
1658   llvm::raw_svector_ostream os(buf);
1659   SmallString<20> AllocNameBuf;
1660   llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1661 
1662   const MemRegion *MR = ArgVal.getAsRegion();
1663   assert(MR && "Only MemRegion based symbols can have offset free errors");
1664 
1665   RegionOffset Offset = MR->getAsOffset();
1666   assert((Offset.isValid() &&
1667           !Offset.hasSymbolicOffset() &&
1668           Offset.getOffset() != 0) &&
1669          "Only symbols with a valid offset can have offset free errors");
1670 
1671   int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1672 
1673   os << "Argument to ";
1674   if (!printAllocDeallocName(os, C, DeallocExpr))
1675     os << "deallocator";
1676   os << " is offset by "
1677      << offsetBytes
1678      << " "
1679      << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1680      << " from the start of ";
1681   if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1682     os << "memory allocated by " << AllocNameOs.str();
1683   else
1684     os << "allocated memory";
1685 
1686   BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
1687   R->markInteresting(MR->getBaseRegion());
1688   R->addRange(Range);
1689   C.emitReport(R);
1690 }
1691 
1692 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1693                                        SymbolRef Sym) const {
1694 
1695   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1696                                                    CK_MallocPessimistic,
1697                                                    CK_NewDeleteChecker),
1698                                      C, Sym);
1699   if (!CheckKind.hasValue())
1700     return;
1701 
1702   if (ExplodedNode *N = C.generateSink()) {
1703     if (!BT_UseFree[*CheckKind])
1704       BT_UseFree[*CheckKind].reset(new BugType(
1705           CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
1706 
1707     BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
1708                                  "Use of memory after it is freed", N);
1709 
1710     R->markInteresting(Sym);
1711     R->addRange(Range);
1712     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1713     C.emitReport(R);
1714   }
1715 }
1716 
1717 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1718                                      bool Released, SymbolRef Sym,
1719                                      SymbolRef PrevSym) const {
1720 
1721   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1722                                                    CK_MallocPessimistic,
1723                                                    CK_NewDeleteChecker),
1724                                      C, Sym);
1725   if (!CheckKind.hasValue())
1726     return;
1727 
1728   if (ExplodedNode *N = C.generateSink()) {
1729     if (!BT_DoubleFree[*CheckKind])
1730       BT_DoubleFree[*CheckKind].reset(
1731           new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
1732 
1733     BugReport *R =
1734         new BugReport(*BT_DoubleFree[*CheckKind],
1735                       (Released ? "Attempt to free released memory"
1736                                 : "Attempt to free non-owned memory"),
1737                       N);
1738     R->addRange(Range);
1739     R->markInteresting(Sym);
1740     if (PrevSym)
1741       R->markInteresting(PrevSym);
1742     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1743     C.emitReport(R);
1744   }
1745 }
1746 
1747 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1748 
1749   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_NewDeleteChecker),
1750                                      C, Sym);
1751   if (!CheckKind.hasValue())
1752     return;
1753 
1754   if (ExplodedNode *N = C.generateSink()) {
1755     if (!BT_DoubleDelete)
1756       BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1757                                         "Double delete", "Memory Error"));
1758 
1759     BugReport *R = new BugReport(*BT_DoubleDelete,
1760                                  "Attempt to delete released memory", N);
1761 
1762     R->markInteresting(Sym);
1763     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1764     C.emitReport(R);
1765   }
1766 }
1767 
1768 ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1769                                           const CallExpr *CE,
1770                                           bool FreesOnFail,
1771                                           ProgramStateRef State) const {
1772   if (!State)
1773     return nullptr;
1774 
1775   if (CE->getNumArgs() < 2)
1776     return nullptr;
1777 
1778   const Expr *arg0Expr = CE->getArg(0);
1779   const LocationContext *LCtx = C.getLocationContext();
1780   SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
1781   if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
1782     return nullptr;
1783   DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
1784 
1785   SValBuilder &svalBuilder = C.getSValBuilder();
1786 
1787   DefinedOrUnknownSVal PtrEQ =
1788     svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
1789 
1790   // Get the size argument. If there is no size arg then give up.
1791   const Expr *Arg1 = CE->getArg(1);
1792   if (!Arg1)
1793     return nullptr;
1794 
1795   // Get the value of the size argument.
1796   SVal Arg1ValG = State->getSVal(Arg1, LCtx);
1797   if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
1798     return nullptr;
1799   DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
1800 
1801   // Compare the size argument to 0.
1802   DefinedOrUnknownSVal SizeZero =
1803     svalBuilder.evalEQ(State, Arg1Val,
1804                        svalBuilder.makeIntValWithPtrWidth(0, false));
1805 
1806   ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1807   std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
1808   ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1809   std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
1810   // We only assume exceptional states if they are definitely true; if the
1811   // state is under-constrained, assume regular realloc behavior.
1812   bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1813   bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1814 
1815   // If the ptr is NULL and the size is not 0, the call is equivalent to
1816   // malloc(size).
1817   if ( PrtIsNull && !SizeIsZero) {
1818     ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
1819                                                UndefinedVal(), StatePtrIsNull);
1820     return stateMalloc;
1821   }
1822 
1823   if (PrtIsNull && SizeIsZero)
1824     return nullptr;
1825 
1826   // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
1827   assert(!PrtIsNull);
1828   SymbolRef FromPtr = arg0Val.getAsSymbol();
1829   SVal RetVal = State->getSVal(CE, LCtx);
1830   SymbolRef ToPtr = RetVal.getAsSymbol();
1831   if (!FromPtr || !ToPtr)
1832     return nullptr;
1833 
1834   bool ReleasedAllocated = false;
1835 
1836   // If the size is 0, free the memory.
1837   if (SizeIsZero)
1838     if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1839                                                false, ReleasedAllocated)){
1840       // The semantics of the return value are:
1841       // If size was equal to 0, either NULL or a pointer suitable to be passed
1842       // to free() is returned. We just free the input pointer and do not add
1843       // any constrains on the output pointer.
1844       return stateFree;
1845     }
1846 
1847   // Default behavior.
1848   if (ProgramStateRef stateFree =
1849         FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
1850 
1851     ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1852                                                 UnknownVal(), stateFree);
1853     if (!stateRealloc)
1854       return nullptr;
1855 
1856     ReallocPairKind Kind = RPToBeFreedAfterFailure;
1857     if (FreesOnFail)
1858       Kind = RPIsFreeOnFailure;
1859     else if (!ReleasedAllocated)
1860       Kind = RPDoNotTrackAfterFailure;
1861 
1862     // Record the info about the reallocated symbol so that we could properly
1863     // process failed reallocation.
1864     stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
1865                                                    ReallocPair(FromPtr, Kind));
1866     // The reallocated symbol should stay alive for as long as the new symbol.
1867     C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
1868     return stateRealloc;
1869   }
1870   return nullptr;
1871 }
1872 
1873 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
1874                                          ProgramStateRef State) {
1875   if (!State)
1876     return nullptr;
1877 
1878   if (CE->getNumArgs() < 2)
1879     return nullptr;
1880 
1881   SValBuilder &svalBuilder = C.getSValBuilder();
1882   const LocationContext *LCtx = C.getLocationContext();
1883   SVal count = State->getSVal(CE->getArg(0), LCtx);
1884   SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1885   SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
1886                                         svalBuilder.getContext().getSizeType());
1887   SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1888 
1889   return MallocMemAux(C, CE, TotalSize, zeroVal, State);
1890 }
1891 
1892 LeakInfo
1893 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1894                                  CheckerContext &C) const {
1895   const LocationContext *LeakContext = N->getLocationContext();
1896   // Walk the ExplodedGraph backwards and find the first node that referred to
1897   // the tracked symbol.
1898   const ExplodedNode *AllocNode = N;
1899   const MemRegion *ReferenceRegion = nullptr;
1900 
1901   while (N) {
1902     ProgramStateRef State = N->getState();
1903     if (!State->get<RegionState>(Sym))
1904       break;
1905 
1906     // Find the most recent expression bound to the symbol in the current
1907     // context.
1908       if (!ReferenceRegion) {
1909         if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1910           SVal Val = State->getSVal(MR);
1911           if (Val.getAsLocSymbol() == Sym) {
1912             const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
1913             // Do not show local variables belonging to a function other than
1914             // where the error is reported.
1915             if (!VR ||
1916                 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1917               ReferenceRegion = MR;
1918           }
1919         }
1920       }
1921 
1922     // Allocation node, is the last node in the current or parent context in
1923     // which the symbol was tracked.
1924     const LocationContext *NContext = N->getLocationContext();
1925     if (NContext == LeakContext ||
1926         NContext->isParentOf(LeakContext))
1927       AllocNode = N;
1928     N = N->pred_empty() ? nullptr : *(N->pred_begin());
1929   }
1930 
1931   return LeakInfo(AllocNode, ReferenceRegion);
1932 }
1933 
1934 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1935                                CheckerContext &C) const {
1936 
1937   auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1938                                                    CK_MallocPessimistic,
1939                                                    CK_NewDeleteLeaksChecker),
1940                                      C, Sym);
1941   if (!CheckKind.hasValue())
1942     return;
1943 
1944   assert(N);
1945   if (!BT_Leak[*CheckKind]) {
1946     BT_Leak[*CheckKind].reset(
1947         new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
1948     // Leaks should not be reported if they are post-dominated by a sink:
1949     // (1) Sinks are higher importance bugs.
1950     // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1951     //     with __noreturn functions such as assert() or exit(). We choose not
1952     //     to report leaks on such paths.
1953     BT_Leak[*CheckKind]->setSuppressOnSink(true);
1954   }
1955 
1956   // Most bug reports are cached at the location where they occurred.
1957   // With leaks, we want to unique them by the location where they were
1958   // allocated, and only report a single path.
1959   PathDiagnosticLocation LocUsedForUniqueing;
1960   const ExplodedNode *AllocNode = nullptr;
1961   const MemRegion *Region = nullptr;
1962   std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1963 
1964   ProgramPoint P = AllocNode->getLocation();
1965   const Stmt *AllocationStmt = nullptr;
1966   if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
1967     AllocationStmt = Exit->getCalleeContext()->getCallSite();
1968   else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
1969     AllocationStmt = SP->getStmt();
1970   if (AllocationStmt)
1971     LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1972                                               C.getSourceManager(),
1973                                               AllocNode->getLocationContext());
1974 
1975   SmallString<200> buf;
1976   llvm::raw_svector_ostream os(buf);
1977   if (Region && Region->canPrintPretty()) {
1978     os << "Potential leak of memory pointed to by ";
1979     Region->printPretty(os);
1980   } else {
1981     os << "Potential memory leak";
1982   }
1983 
1984   BugReport *R =
1985       new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1986                     AllocNode->getLocationContext()->getDecl());
1987   R->markInteresting(Sym);
1988   R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
1989   C.emitReport(R);
1990 }
1991 
1992 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1993                                      CheckerContext &C) const
1994 {
1995   if (!SymReaper.hasDeadSymbols())
1996     return;
1997 
1998   ProgramStateRef state = C.getState();
1999   RegionStateTy RS = state->get<RegionState>();
2000   RegionStateTy::Factory &F = state->get_context<RegionState>();
2001 
2002   SmallVector<SymbolRef, 2> Errors;
2003   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2004     if (SymReaper.isDead(I->first)) {
2005       if (I->second.isAllocated())
2006         Errors.push_back(I->first);
2007       // Remove the dead symbol from the map.
2008       RS = F.remove(RS, I->first);
2009 
2010     }
2011   }
2012 
2013   // Cleanup the Realloc Pairs Map.
2014   ReallocPairsTy RP = state->get<ReallocPairs>();
2015   for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2016     if (SymReaper.isDead(I->first) ||
2017         SymReaper.isDead(I->second.ReallocatedSym)) {
2018       state = state->remove<ReallocPairs>(I->first);
2019     }
2020   }
2021 
2022   // Cleanup the FreeReturnValue Map.
2023   FreeReturnValueTy FR = state->get<FreeReturnValue>();
2024   for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2025     if (SymReaper.isDead(I->first) ||
2026         SymReaper.isDead(I->second)) {
2027       state = state->remove<FreeReturnValue>(I->first);
2028     }
2029   }
2030 
2031   // Generate leak node.
2032   ExplodedNode *N = C.getPredecessor();
2033   if (!Errors.empty()) {
2034     static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2035     N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
2036     for (SmallVectorImpl<SymbolRef>::iterator
2037            I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2038       reportLeak(*I, N, C);
2039     }
2040   }
2041 
2042   C.addTransition(state->set<RegionState>(RS), N);
2043 }
2044 
2045 void MallocChecker::checkPreCall(const CallEvent &Call,
2046                                  CheckerContext &C) const {
2047 
2048   if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2049     SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2050     if (!Sym || checkDoubleDelete(Sym, C))
2051       return;
2052   }
2053 
2054   // We will check for double free in the post visit.
2055   if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2056     const FunctionDecl *FD = FC->getDecl();
2057     if (!FD)
2058       return;
2059 
2060     ASTContext &Ctx = C.getASTContext();
2061     if ((ChecksEnabled[CK_MallocOptimistic] ||
2062          ChecksEnabled[CK_MallocPessimistic]) &&
2063         (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2064          isCMemFunction(FD, Ctx, AF_IfNameIndex,
2065                         MemoryOperationKind::MOK_Free)))
2066       return;
2067 
2068     if (ChecksEnabled[CK_NewDeleteChecker] &&
2069         isStandardNewDelete(FD, Ctx))
2070       return;
2071   }
2072 
2073   // Check if the callee of a method is deleted.
2074   if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2075     SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2076     if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2077       return;
2078   }
2079 
2080   // Check arguments for being used after free.
2081   for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2082     SVal ArgSVal = Call.getArgSVal(I);
2083     if (ArgSVal.getAs<Loc>()) {
2084       SymbolRef Sym = ArgSVal.getAsSymbol();
2085       if (!Sym)
2086         continue;
2087       if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2088         return;
2089     }
2090   }
2091 }
2092 
2093 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2094   const Expr *E = S->getRetValue();
2095   if (!E)
2096     return;
2097 
2098   // Check if we are returning a symbol.
2099   ProgramStateRef State = C.getState();
2100   SVal RetVal = State->getSVal(E, C.getLocationContext());
2101   SymbolRef Sym = RetVal.getAsSymbol();
2102   if (!Sym)
2103     // If we are returning a field of the allocated struct or an array element,
2104     // the callee could still free the memory.
2105     // TODO: This logic should be a part of generic symbol escape callback.
2106     if (const MemRegion *MR = RetVal.getAsRegion())
2107       if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2108         if (const SymbolicRegion *BMR =
2109               dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2110           Sym = BMR->getSymbol();
2111 
2112   // Check if we are returning freed memory.
2113   if (Sym)
2114     checkUseAfterFree(Sym, C, E);
2115 }
2116 
2117 // TODO: Blocks should be either inlined or should call invalidate regions
2118 // upon invocation. After that's in place, special casing here will not be
2119 // needed.
2120 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2121                                   CheckerContext &C) const {
2122 
2123   // Scan the BlockDecRefExprs for any object the retain count checker
2124   // may be tracking.
2125   if (!BE->getBlockDecl()->hasCaptures())
2126     return;
2127 
2128   ProgramStateRef state = C.getState();
2129   const BlockDataRegion *R =
2130     cast<BlockDataRegion>(state->getSVal(BE,
2131                                          C.getLocationContext()).getAsRegion());
2132 
2133   BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2134                                             E = R->referenced_vars_end();
2135 
2136   if (I == E)
2137     return;
2138 
2139   SmallVector<const MemRegion*, 10> Regions;
2140   const LocationContext *LC = C.getLocationContext();
2141   MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2142 
2143   for ( ; I != E; ++I) {
2144     const VarRegion *VR = I.getCapturedRegion();
2145     if (VR->getSuperRegion() == R) {
2146       VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2147     }
2148     Regions.push_back(VR);
2149   }
2150 
2151   state =
2152     state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2153                                     Regions.data() + Regions.size()).getState();
2154   C.addTransition(state);
2155 }
2156 
2157 bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2158   assert(Sym);
2159   const RefState *RS = C.getState()->get<RegionState>(Sym);
2160   return (RS && RS->isReleased());
2161 }
2162 
2163 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2164                                       const Stmt *S) const {
2165 
2166   if (isReleased(Sym, C)) {
2167     ReportUseAfterFree(C, S->getSourceRange(), Sym);
2168     return true;
2169   }
2170 
2171   return false;
2172 }
2173 
2174 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2175 
2176   if (isReleased(Sym, C)) {
2177     ReportDoubleDelete(C, Sym);
2178     return true;
2179   }
2180   return false;
2181 }
2182 
2183 // Check if the location is a freed symbolic region.
2184 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2185                                   CheckerContext &C) const {
2186   SymbolRef Sym = l.getLocSymbolInBase();
2187   if (Sym)
2188     checkUseAfterFree(Sym, C, S);
2189 }
2190 
2191 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2192 // it - assuming that allocation failed on this path.
2193 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2194                                               SVal Cond,
2195                                               bool Assumption) const {
2196   RegionStateTy RS = state->get<RegionState>();
2197   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2198     // If the symbol is assumed to be NULL, remove it from consideration.
2199     ConstraintManager &CMgr = state->getConstraintManager();
2200     ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2201     if (AllocFailed.isConstrainedTrue())
2202       state = state->remove<RegionState>(I.getKey());
2203   }
2204 
2205   // Realloc returns 0 when reallocation fails, which means that we should
2206   // restore the state of the pointer being reallocated.
2207   ReallocPairsTy RP = state->get<ReallocPairs>();
2208   for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2209     // If the symbol is assumed to be NULL, remove it from consideration.
2210     ConstraintManager &CMgr = state->getConstraintManager();
2211     ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2212     if (!AllocFailed.isConstrainedTrue())
2213       continue;
2214 
2215     SymbolRef ReallocSym = I.getData().ReallocatedSym;
2216     if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2217       if (RS->isReleased()) {
2218         if (I.getData().Kind == RPToBeFreedAfterFailure)
2219           state = state->set<RegionState>(ReallocSym,
2220               RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2221         else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2222           state = state->remove<RegionState>(ReallocSym);
2223         else
2224           assert(I.getData().Kind == RPIsFreeOnFailure);
2225       }
2226     }
2227     state = state->remove<ReallocPairs>(I.getKey());
2228   }
2229 
2230   return state;
2231 }
2232 
2233 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2234                                               const CallEvent *Call,
2235                                               ProgramStateRef State,
2236                                               SymbolRef &EscapingSymbol) const {
2237   assert(Call);
2238   EscapingSymbol = nullptr;
2239 
2240   // For now, assume that any C++ or block call can free memory.
2241   // TODO: If we want to be more optimistic here, we'll need to make sure that
2242   // regions escape to C++ containers. They seem to do that even now, but for
2243   // mysterious reasons.
2244   if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2245     return true;
2246 
2247   // Check Objective-C messages by selector name.
2248   if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2249     // If it's not a framework call, or if it takes a callback, assume it
2250     // can free memory.
2251     if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
2252       return true;
2253 
2254     // If it's a method we know about, handle it explicitly post-call.
2255     // This should happen before the "freeWhenDone" check below.
2256     if (isKnownDeallocObjCMethodName(*Msg))
2257       return false;
2258 
2259     // If there's a "freeWhenDone" parameter, but the method isn't one we know
2260     // about, we can't be sure that the object will use free() to deallocate the
2261     // memory, so we can't model it explicitly. The best we can do is use it to
2262     // decide whether the pointer escapes.
2263     if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2264       return *FreeWhenDone;
2265 
2266     // If the first selector piece ends with "NoCopy", and there is no
2267     // "freeWhenDone" parameter set to zero, we know ownership is being
2268     // transferred. Again, though, we can't be sure that the object will use
2269     // free() to deallocate the memory, so we can't model it explicitly.
2270     StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2271     if (FirstSlot.endswith("NoCopy"))
2272       return true;
2273 
2274     // If the first selector starts with addPointer, insertPointer,
2275     // or replacePointer, assume we are dealing with NSPointerArray or similar.
2276     // This is similar to C++ containers (vector); we still might want to check
2277     // that the pointers get freed by following the container itself.
2278     if (FirstSlot.startswith("addPointer") ||
2279         FirstSlot.startswith("insertPointer") ||
2280         FirstSlot.startswith("replacePointer") ||
2281         FirstSlot.equals("valueWithPointer")) {
2282       return true;
2283     }
2284 
2285     // We should escape receiver on call to 'init'. This is especially relevant
2286     // to the receiver, as the corresponding symbol is usually not referenced
2287     // after the call.
2288     if (Msg->getMethodFamily() == OMF_init) {
2289       EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2290       return true;
2291     }
2292 
2293     // Otherwise, assume that the method does not free memory.
2294     // Most framework methods do not free memory.
2295     return false;
2296   }
2297 
2298   // At this point the only thing left to handle is straight function calls.
2299   const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2300   if (!FD)
2301     return true;
2302 
2303   ASTContext &ASTC = State->getStateManager().getContext();
2304 
2305   // If it's one of the allocation functions we can reason about, we model
2306   // its behavior explicitly.
2307   if (isMemFunction(FD, ASTC))
2308     return false;
2309 
2310   // If it's not a system call, assume it frees memory.
2311   if (!Call->isInSystemHeader())
2312     return true;
2313 
2314   // White list the system functions whose arguments escape.
2315   const IdentifierInfo *II = FD->getIdentifier();
2316   if (!II)
2317     return true;
2318   StringRef FName = II->getName();
2319 
2320   // White list the 'XXXNoCopy' CoreFoundation functions.
2321   // We specifically check these before
2322   if (FName.endswith("NoCopy")) {
2323     // Look for the deallocator argument. We know that the memory ownership
2324     // is not transferred only if the deallocator argument is
2325     // 'kCFAllocatorNull'.
2326     for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2327       const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2328       if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2329         StringRef DeallocatorName = DE->getFoundDecl()->getName();
2330         if (DeallocatorName == "kCFAllocatorNull")
2331           return false;
2332       }
2333     }
2334     return true;
2335   }
2336 
2337   // Associating streams with malloced buffers. The pointer can escape if
2338   // 'closefn' is specified (and if that function does free memory),
2339   // but it will not if closefn is not specified.
2340   // Currently, we do not inspect the 'closefn' function (PR12101).
2341   if (FName == "funopen")
2342     if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2343       return false;
2344 
2345   // Do not warn on pointers passed to 'setbuf' when used with std streams,
2346   // these leaks might be intentional when setting the buffer for stdio.
2347   // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2348   if (FName == "setbuf" || FName =="setbuffer" ||
2349       FName == "setlinebuf" || FName == "setvbuf") {
2350     if (Call->getNumArgs() >= 1) {
2351       const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2352       if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2353         if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2354           if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2355             return true;
2356     }
2357   }
2358 
2359   // A bunch of other functions which either take ownership of a pointer or
2360   // wrap the result up in a struct or object, meaning it can be freed later.
2361   // (See RetainCountChecker.) Not all the parameters here are invalidated,
2362   // but the Malloc checker cannot differentiate between them. The right way
2363   // of doing this would be to implement a pointer escapes callback.
2364   if (FName == "CGBitmapContextCreate" ||
2365       FName == "CGBitmapContextCreateWithData" ||
2366       FName == "CVPixelBufferCreateWithBytes" ||
2367       FName == "CVPixelBufferCreateWithPlanarBytes" ||
2368       FName == "OSAtomicEnqueue") {
2369     return true;
2370   }
2371 
2372   // Handle cases where we know a buffer's /address/ can escape.
2373   // Note that the above checks handle some special cases where we know that
2374   // even though the address escapes, it's still our responsibility to free the
2375   // buffer.
2376   if (Call->argumentsMayEscape())
2377     return true;
2378 
2379   // Otherwise, assume that the function does not free memory.
2380   // Most system calls do not free the memory.
2381   return false;
2382 }
2383 
2384 static bool retTrue(const RefState *RS) {
2385   return true;
2386 }
2387 
2388 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2389   return (RS->getAllocationFamily() == AF_CXXNewArray ||
2390           RS->getAllocationFamily() == AF_CXXNew);
2391 }
2392 
2393 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2394                                              const InvalidatedSymbols &Escaped,
2395                                              const CallEvent *Call,
2396                                              PointerEscapeKind Kind) const {
2397   return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2398 }
2399 
2400 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2401                                               const InvalidatedSymbols &Escaped,
2402                                               const CallEvent *Call,
2403                                               PointerEscapeKind Kind) const {
2404   return checkPointerEscapeAux(State, Escaped, Call, Kind,
2405                                &checkIfNewOrNewArrayFamily);
2406 }
2407 
2408 ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2409                                               const InvalidatedSymbols &Escaped,
2410                                               const CallEvent *Call,
2411                                               PointerEscapeKind Kind,
2412                                   bool(*CheckRefState)(const RefState*)) const {
2413   // If we know that the call does not free memory, or we want to process the
2414   // call later, keep tracking the top level arguments.
2415   SymbolRef EscapingSymbol = nullptr;
2416   if (Kind == PSK_DirectEscapeOnCall &&
2417       !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2418                                                     EscapingSymbol) &&
2419       !EscapingSymbol) {
2420     return State;
2421   }
2422 
2423   for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2424        E = Escaped.end();
2425        I != E; ++I) {
2426     SymbolRef sym = *I;
2427 
2428     if (EscapingSymbol && EscapingSymbol != sym)
2429       continue;
2430 
2431     if (const RefState *RS = State->get<RegionState>(sym)) {
2432       if (RS->isAllocated() && CheckRefState(RS)) {
2433         State = State->remove<RegionState>(sym);
2434         State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2435       }
2436     }
2437   }
2438   return State;
2439 }
2440 
2441 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2442                                          ProgramStateRef prevState) {
2443   ReallocPairsTy currMap = currState->get<ReallocPairs>();
2444   ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2445 
2446   for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2447        I != E; ++I) {
2448     SymbolRef sym = I.getKey();
2449     if (!currMap.lookup(sym))
2450       return sym;
2451   }
2452 
2453   return nullptr;
2454 }
2455 
2456 PathDiagnosticPiece *
2457 MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2458                                            const ExplodedNode *PrevN,
2459                                            BugReporterContext &BRC,
2460                                            BugReport &BR) {
2461   ProgramStateRef state = N->getState();
2462   ProgramStateRef statePrev = PrevN->getState();
2463 
2464   const RefState *RS = state->get<RegionState>(Sym);
2465   const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2466   if (!RS)
2467     return nullptr;
2468 
2469   const Stmt *S = nullptr;
2470   const char *Msg = nullptr;
2471   StackHintGeneratorForSymbol *StackHint = nullptr;
2472 
2473   // Retrieve the associated statement.
2474   ProgramPoint ProgLoc = N->getLocation();
2475   if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
2476     S = SP->getStmt();
2477   } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
2478     S = Exit->getCalleeContext()->getCallSite();
2479   } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
2480     // If an assumption was made on a branch, it should be caught
2481     // here by looking at the state transition.
2482     S = Edge->getSrc()->getTerminator();
2483   }
2484 
2485   if (!S)
2486     return nullptr;
2487 
2488   // FIXME: We will eventually need to handle non-statement-based events
2489   // (__attribute__((cleanup))).
2490 
2491   // Find out if this is an interesting point and what is the kind.
2492   if (Mode == Normal) {
2493     if (isAllocated(RS, RSPrev, S)) {
2494       Msg = "Memory is allocated";
2495       StackHint = new StackHintGeneratorForSymbol(Sym,
2496                                                   "Returned allocated memory");
2497     } else if (isReleased(RS, RSPrev, S)) {
2498       Msg = "Memory is released";
2499       StackHint = new StackHintGeneratorForSymbol(Sym,
2500                                              "Returning; memory was released");
2501     } else if (isRelinquished(RS, RSPrev, S)) {
2502       Msg = "Memory ownership is transferred";
2503       StackHint = new StackHintGeneratorForSymbol(Sym, "");
2504     } else if (isReallocFailedCheck(RS, RSPrev, S)) {
2505       Mode = ReallocationFailed;
2506       Msg = "Reallocation failed";
2507       StackHint = new StackHintGeneratorForReallocationFailed(Sym,
2508                                                        "Reallocation failed");
2509 
2510       if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2511         // Is it possible to fail two reallocs WITHOUT testing in between?
2512         assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2513           "We only support one failed realloc at a time.");
2514         BR.markInteresting(sym);
2515         FailedReallocSymbol = sym;
2516       }
2517     }
2518 
2519   // We are in a special mode if a reallocation failed later in the path.
2520   } else if (Mode == ReallocationFailed) {
2521     assert(FailedReallocSymbol && "No symbol to look for.");
2522 
2523     // Is this is the first appearance of the reallocated symbol?
2524     if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
2525       // We're at the reallocation point.
2526       Msg = "Attempt to reallocate memory";
2527       StackHint = new StackHintGeneratorForSymbol(Sym,
2528                                                  "Returned reallocated memory");
2529       FailedReallocSymbol = nullptr;
2530       Mode = Normal;
2531     }
2532   }
2533 
2534   if (!Msg)
2535     return nullptr;
2536   assert(StackHint);
2537 
2538   // Generate the extra diagnostic.
2539   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2540                              N->getLocationContext());
2541   return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
2542 }
2543 
2544 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2545                                const char *NL, const char *Sep) const {
2546 
2547   RegionStateTy RS = State->get<RegionState>();
2548 
2549   if (!RS.isEmpty()) {
2550     Out << Sep << "MallocChecker :" << NL;
2551     for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2552       const RefState *RefS = State->get<RegionState>(I.getKey());
2553       AllocationFamily Family = RefS->getAllocationFamily();
2554       auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
2555                                                        CK_MallocPessimistic,
2556                                                        CK_NewDeleteChecker),
2557                                          Family);
2558       I.getKey()->dumpToStream(Out);
2559       Out << " : ";
2560       I.getData().dump(Out);
2561       if (CheckKind.hasValue())
2562         Out << " (" << CheckNames[*CheckKind].getName() << ")";
2563       Out << NL;
2564     }
2565   }
2566 }
2567 
2568 void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2569   registerCStringCheckerBasic(mgr);
2570   MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2571   checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2572   checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2573       mgr.getCurrentCheckName();
2574   // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2575   // checker.
2576   if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
2577     checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
2578 }
2579 
2580 #define REGISTER_CHECKER(name)                                                 \
2581   void ento::register##name(CheckerManager &mgr) {                             \
2582     registerCStringCheckerBasic(mgr);                                          \
2583     MallocChecker *checker = mgr.registerChecker<MallocChecker>();             \
2584     checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
2585     checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2586   }
2587 
2588 REGISTER_CHECKER(MallocPessimistic)
2589 REGISTER_CHECKER(MallocOptimistic)
2590 REGISTER_CHECKER(NewDeleteChecker)
2591 REGISTER_CHECKER(MismatchedDeallocatorChecker)
2592