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