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