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