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