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