xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (revision 1e809b4c4c526d22c8f892d870856265f940e65a)
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/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "llvm/ADT/ImmutableMap.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include <climits>
30 
31 using namespace clang;
32 using namespace ento;
33 
34 namespace {
35 
36 class RefState {
37   enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
38               Relinquished } K;
39   const Stmt *S;
40 
41 public:
42   RefState(Kind k, const Stmt *s) : K(k), S(s) {}
43 
44   bool isAllocated() const { return K == AllocateUnchecked; }
45   bool isReleased() const { return K == Released; }
46 
47   const Stmt *getStmt() const { return S; }
48 
49   bool operator==(const RefState &X) const {
50     return K == X.K && S == X.S;
51   }
52 
53   static RefState getAllocateUnchecked(const Stmt *s) {
54     return RefState(AllocateUnchecked, s);
55   }
56   static RefState getAllocateFailed() {
57     return RefState(AllocateFailed, 0);
58   }
59   static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
60   static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
61   static RefState getRelinquished(const Stmt *s) {
62     return RefState(Relinquished, s);
63   }
64 
65   void Profile(llvm::FoldingSetNodeID &ID) const {
66     ID.AddInteger(K);
67     ID.AddPointer(S);
68   }
69 };
70 
71 struct ReallocPair {
72   SymbolRef ReallocatedSym;
73   bool IsFreeOnFailure;
74   ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
75   void Profile(llvm::FoldingSetNodeID &ID) const {
76     ID.AddInteger(IsFreeOnFailure);
77     ID.AddPointer(ReallocatedSym);
78   }
79   bool operator==(const ReallocPair &X) const {
80     return ReallocatedSym == X.ReallocatedSym &&
81            IsFreeOnFailure == X.IsFreeOnFailure;
82   }
83 };
84 
85 class MallocChecker : public Checker<check::DeadSymbols,
86                                      check::EndPath,
87                                      check::PreStmt<ReturnStmt>,
88                                      check::PreStmt<CallExpr>,
89                                      check::PostStmt<CallExpr>,
90                                      check::Location,
91                                      check::Bind,
92                                      eval::Assume,
93                                      check::RegionChanges>
94 {
95   mutable OwningPtr<BugType> BT_DoubleFree;
96   mutable OwningPtr<BugType> BT_Leak;
97   mutable OwningPtr<BugType> BT_UseFree;
98   mutable OwningPtr<BugType> BT_BadFree;
99   mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
100                          *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
101 
102 public:
103   MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
104                     II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
105 
106   /// In pessimistic mode, the checker assumes that it does not know which
107   /// functions might free the memory.
108   struct ChecksFilter {
109     DefaultBool CMallocPessimistic;
110     DefaultBool CMallocOptimistic;
111   };
112 
113   ChecksFilter Filter;
114 
115   void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
116   void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
117   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
118   void checkEndPath(CheckerContext &C) const;
119   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
120   ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
121                             bool Assumption) const;
122   void checkLocation(SVal l, bool isLoad, const Stmt *S,
123                      CheckerContext &C) const;
124   void checkBind(SVal location, SVal val, const Stmt*S,
125                  CheckerContext &C) const;
126   ProgramStateRef
127   checkRegionChanges(ProgramStateRef state,
128                      const StoreManager::InvalidatedSymbols *invalidated,
129                      ArrayRef<const MemRegion *> ExplicitRegions,
130                      ArrayRef<const MemRegion *> Regions,
131                      const CallOrObjCMessage *Call) const;
132   bool wantsRegionChangeUpdate(ProgramStateRef state) const {
133     return true;
134   }
135 
136 private:
137   void initIdentifierInfo(ASTContext &C) const;
138 
139   /// Check if this is one of the functions which can allocate/reallocate memory
140   /// pointed to by one of its arguments.
141   bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
142 
143   static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
144                                               const CallExpr *CE,
145                                               const OwnershipAttr* Att);
146   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
147                                      const Expr *SizeEx, SVal Init,
148                                      ProgramStateRef state) {
149     return MallocMemAux(C, CE,
150                         state->getSVal(SizeEx, C.getLocationContext()),
151                         Init, state);
152   }
153 
154   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
155                                      SVal SizeEx, SVal Init,
156                                      ProgramStateRef state);
157 
158   /// Update the RefState to reflect the new memory allocation.
159   static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
160                                               const CallExpr *CE,
161                                               ProgramStateRef state);
162 
163   ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
164                               const OwnershipAttr* Att) const;
165   ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
166                                  ProgramStateRef state, unsigned Num,
167                                  bool Hold) const;
168 
169   ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
170                              bool FreesMemOnFailure) const;
171   static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
172 
173   bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
174   bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
175                          const Stmt *S = 0) const;
176 
177   /// Check if the function is not known to us. So, for example, we could
178   /// conservatively assume it can free/reallocate it's pointer arguments.
179   bool doesNotFreeMemory(const CallOrObjCMessage *Call,
180                          ProgramStateRef State) const;
181 
182   static bool SummarizeValue(raw_ostream &os, SVal V);
183   static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
184   void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
185 
186   /// Find the location of the allocation for Sym on the path leading to the
187   /// exploded node N.
188   const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
189                                 CheckerContext &C) const;
190 
191   void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
192 
193   /// The bug visitor which allows us to print extra diagnostics along the
194   /// BugReport path. For example, showing the allocation site of the leaked
195   /// region.
196   class MallocBugVisitor : public BugReporterVisitor {
197   protected:
198     enum NotificationMode {
199       Normal,
200       Complete,
201       ReallocationFailed
202     };
203 
204     // The allocated region symbol tracked by the main analysis.
205     SymbolRef Sym;
206     NotificationMode Mode;
207 
208   public:
209     MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
210     virtual ~MallocBugVisitor() {}
211 
212     void Profile(llvm::FoldingSetNodeID &ID) const {
213       static int X = 0;
214       ID.AddPointer(&X);
215       ID.AddPointer(Sym);
216     }
217 
218     inline bool isAllocated(const RefState *S, const RefState *SPrev,
219                             const Stmt *Stmt) {
220       // Did not track -> allocated. Other state (released) -> allocated.
221       return (Stmt && isa<CallExpr>(Stmt) &&
222               (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
223     }
224 
225     inline bool isReleased(const RefState *S, const RefState *SPrev,
226                            const Stmt *Stmt) {
227       // Did not track -> released. Other state (allocated) -> released.
228       return (Stmt && isa<CallExpr>(Stmt) &&
229               (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
230     }
231 
232     inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
233                                      const Stmt *Stmt) {
234       // If the expression is not a call, and the state change is
235       // released -> allocated, it must be the realloc return value
236       // check. If we have to handle more cases here, it might be cleaner just
237       // to track this extra bit in the state itself.
238       return ((!Stmt || !isa<CallExpr>(Stmt)) &&
239               (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
240     }
241 
242     PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
243                                    const ExplodedNode *PrevN,
244                                    BugReporterContext &BRC,
245                                    BugReport &BR);
246   };
247 };
248 } // end anonymous namespace
249 
250 typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
251 typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
252 class RegionState {};
253 class ReallocPairs {};
254 namespace clang {
255 namespace ento {
256   template <>
257   struct ProgramStateTrait<RegionState>
258     : public ProgramStatePartialTrait<RegionStateTy> {
259     static void *GDMIndex() { static int x; return &x; }
260   };
261 
262   template <>
263   struct ProgramStateTrait<ReallocPairs>
264     : public ProgramStatePartialTrait<ReallocMap> {
265     static void *GDMIndex() { static int x; return &x; }
266   };
267 }
268 }
269 
270 namespace {
271 class StopTrackingCallback : public SymbolVisitor {
272   ProgramStateRef state;
273 public:
274   StopTrackingCallback(ProgramStateRef st) : state(st) {}
275   ProgramStateRef getState() const { return state; }
276 
277   bool VisitSymbol(SymbolRef sym) {
278     state = state->remove<RegionState>(sym);
279     return true;
280   }
281 };
282 } // end anonymous namespace
283 
284 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
285   if (!II_malloc)
286     II_malloc = &Ctx.Idents.get("malloc");
287   if (!II_free)
288     II_free = &Ctx.Idents.get("free");
289   if (!II_realloc)
290     II_realloc = &Ctx.Idents.get("realloc");
291   if (!II_reallocf)
292     II_reallocf = &Ctx.Idents.get("reallocf");
293   if (!II_calloc)
294     II_calloc = &Ctx.Idents.get("calloc");
295   if (!II_valloc)
296     II_valloc = &Ctx.Idents.get("valloc");
297   if (!II_strdup)
298     II_strdup = &Ctx.Idents.get("strdup");
299   if (!II_strndup)
300     II_strndup = &Ctx.Idents.get("strndup");
301 }
302 
303 bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
304   if (!FD)
305     return false;
306   IdentifierInfo *FunI = FD->getIdentifier();
307   if (!FunI)
308     return false;
309 
310   initIdentifierInfo(C);
311 
312   if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
313       FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
314       FunI == II_strdup || FunI == II_strndup)
315     return true;
316 
317   if (Filter.CMallocOptimistic && FD->hasAttrs() &&
318       FD->specific_attr_begin<OwnershipAttr>() !=
319           FD->specific_attr_end<OwnershipAttr>())
320     return true;
321 
322 
323   return false;
324 }
325 
326 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
327   const FunctionDecl *FD = C.getCalleeDecl(CE);
328   if (!FD)
329     return;
330 
331   initIdentifierInfo(C.getASTContext());
332   IdentifierInfo *FunI = FD->getIdentifier();
333   if (!FunI)
334     return;
335 
336   ProgramStateRef State = C.getState();
337   if (FunI == II_malloc || FunI == II_valloc) {
338     State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
339   } else if (FunI == II_realloc) {
340     State = ReallocMem(C, CE, false);
341   } else if (FunI == II_reallocf) {
342     State = ReallocMem(C, CE, true);
343   } else if (FunI == II_calloc) {
344     State = CallocMem(C, CE);
345   } else if (FunI == II_free) {
346     State = FreeMemAux(C, CE, C.getState(), 0, false);
347   } else if (FunI == II_strdup) {
348     State = MallocUpdateRefState(C, CE, State);
349   } else if (FunI == II_strndup) {
350     State = MallocUpdateRefState(C, CE, State);
351   } else if (Filter.CMallocOptimistic) {
352     // Check all the attributes, if there are any.
353     // There can be multiple of these attributes.
354     if (FD->hasAttrs())
355       for (specific_attr_iterator<OwnershipAttr>
356           i = FD->specific_attr_begin<OwnershipAttr>(),
357           e = FD->specific_attr_end<OwnershipAttr>();
358           i != e; ++i) {
359         switch ((*i)->getOwnKind()) {
360         case OwnershipAttr::Returns:
361           State = MallocMemReturnsAttr(C, CE, *i);
362           break;
363         case OwnershipAttr::Takes:
364         case OwnershipAttr::Holds:
365           State = FreeMemAttr(C, CE, *i);
366           break;
367         }
368       }
369   }
370   C.addTransition(State);
371 }
372 
373 ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
374                                                     const CallExpr *CE,
375                                                     const OwnershipAttr* Att) {
376   if (Att->getModule() != "malloc")
377     return 0;
378 
379   OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
380   if (I != E) {
381     return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
382   }
383   return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
384 }
385 
386 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
387                                            const CallExpr *CE,
388                                            SVal Size, SVal Init,
389                                            ProgramStateRef state) {
390   // Get the return value.
391   SVal retVal = state->getSVal(CE, C.getLocationContext());
392 
393   // We expect the malloc functions to return a pointer.
394   if (!isa<Loc>(retVal))
395     return 0;
396 
397   // Fill the region with the initialization value.
398   state = state->bindDefault(retVal, Init);
399 
400   // Set the region's extent equal to the Size parameter.
401   const SymbolicRegion *R =
402       dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
403   if (!R)
404     return 0;
405   if (isa<DefinedOrUnknownSVal>(Size)) {
406     SValBuilder &svalBuilder = C.getSValBuilder();
407     DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
408     DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
409     DefinedOrUnknownSVal extentMatchesSize =
410         svalBuilder.evalEQ(state, Extent, DefinedSize);
411 
412     state = state->assume(extentMatchesSize, true);
413     assert(state);
414   }
415 
416   return MallocUpdateRefState(C, CE, state);
417 }
418 
419 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
420                                                     const CallExpr *CE,
421                                                     ProgramStateRef state) {
422   // Get the return value.
423   SVal retVal = state->getSVal(CE, C.getLocationContext());
424 
425   // We expect the malloc functions to return a pointer.
426   if (!isa<Loc>(retVal))
427     return 0;
428 
429   SymbolRef Sym = retVal.getAsLocSymbol();
430   assert(Sym);
431 
432   // Set the symbol's state to Allocated.
433   return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
434 
435 }
436 
437 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
438                                            const CallExpr *CE,
439                                            const OwnershipAttr* Att) const {
440   if (Att->getModule() != "malloc")
441     return 0;
442 
443   ProgramStateRef State = C.getState();
444 
445   for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
446        I != E; ++I) {
447     ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
448                                Att->getOwnKind() == OwnershipAttr::Holds);
449     if (StateI)
450       State = StateI;
451   }
452   return State;
453 }
454 
455 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
456                                           const CallExpr *CE,
457                                           ProgramStateRef state,
458                                           unsigned Num,
459                                           bool Hold) const {
460   const Expr *ArgExpr = CE->getArg(Num);
461   SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
462   if (!isa<DefinedOrUnknownSVal>(ArgVal))
463     return 0;
464   DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
465 
466   // Check for null dereferences.
467   if (!isa<Loc>(location))
468     return 0;
469 
470   // The explicit NULL case, no operation is performed.
471   ProgramStateRef notNullState, nullState;
472   llvm::tie(notNullState, nullState) = state->assume(location);
473   if (nullState && !notNullState)
474     return 0;
475 
476   // Unknown values could easily be okay
477   // Undefined values are handled elsewhere
478   if (ArgVal.isUnknownOrUndef())
479     return 0;
480 
481   const MemRegion *R = ArgVal.getAsRegion();
482 
483   // Nonlocs can't be freed, of course.
484   // Non-region locations (labels and fixed addresses) also shouldn't be freed.
485   if (!R) {
486     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
487     return 0;
488   }
489 
490   R = R->StripCasts();
491 
492   // Blocks might show up as heap data, but should not be free()d
493   if (isa<BlockDataRegion>(R)) {
494     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
495     return 0;
496   }
497 
498   const MemSpaceRegion *MS = R->getMemorySpace();
499 
500   // Parameters, locals, statics, and globals shouldn't be freed.
501   if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
502     // FIXME: at the time this code was written, malloc() regions were
503     // represented by conjured symbols, which are all in UnknownSpaceRegion.
504     // This means that there isn't actually anything from HeapSpaceRegion
505     // that should be freed, even though we allow it here.
506     // Of course, free() can work on memory allocated outside the current
507     // function, so UnknownSpaceRegion is always a possibility.
508     // False negatives are better than false positives.
509 
510     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
511     return 0;
512   }
513 
514   const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
515   // Various cases could lead to non-symbol values here.
516   // For now, ignore them.
517   if (!SR)
518     return 0;
519 
520   SymbolRef Sym = SR->getSymbol();
521   const RefState *RS = state->get<RegionState>(Sym);
522 
523   // If the symbol has not been tracked, return. This is possible when free() is
524   // called on a pointer that does not get its pointee directly from malloc().
525   // Full support of this requires inter-procedural analysis.
526   if (!RS)
527     return 0;
528 
529   // Check double free.
530   if (RS->isReleased()) {
531     if (ExplodedNode *N = C.generateSink()) {
532       if (!BT_DoubleFree)
533         BT_DoubleFree.reset(
534           new BugType("Double free", "Memory Error"));
535       BugReport *R = new BugReport(*BT_DoubleFree,
536                         "Attempt to free released memory", N);
537       R->addRange(ArgExpr->getSourceRange());
538       R->markInteresting(Sym);
539       R->addVisitor(new MallocBugVisitor(Sym));
540       C.EmitReport(R);
541     }
542     return 0;
543   }
544 
545   // Normal free.
546   if (Hold)
547     return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
548   return state->set<RegionState>(Sym, RefState::getReleased(CE));
549 }
550 
551 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
552   if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
553     os << "an integer (" << IntVal->getValue() << ")";
554   else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
555     os << "a constant address (" << ConstAddr->getValue() << ")";
556   else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
557     os << "the address of the label '" << Label->getLabel()->getName() << "'";
558   else
559     return false;
560 
561   return true;
562 }
563 
564 bool MallocChecker::SummarizeRegion(raw_ostream &os,
565                                     const MemRegion *MR) {
566   switch (MR->getKind()) {
567   case MemRegion::FunctionTextRegionKind: {
568     const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
569     if (FD)
570       os << "the address of the function '" << *FD << '\'';
571     else
572       os << "the address of a function";
573     return true;
574   }
575   case MemRegion::BlockTextRegionKind:
576     os << "block text";
577     return true;
578   case MemRegion::BlockDataRegionKind:
579     // FIXME: where the block came from?
580     os << "a block";
581     return true;
582   default: {
583     const MemSpaceRegion *MS = MR->getMemorySpace();
584 
585     if (isa<StackLocalsSpaceRegion>(MS)) {
586       const VarRegion *VR = dyn_cast<VarRegion>(MR);
587       const VarDecl *VD;
588       if (VR)
589         VD = VR->getDecl();
590       else
591         VD = NULL;
592 
593       if (VD)
594         os << "the address of the local variable '" << VD->getName() << "'";
595       else
596         os << "the address of a local stack variable";
597       return true;
598     }
599 
600     if (isa<StackArgumentsSpaceRegion>(MS)) {
601       const VarRegion *VR = dyn_cast<VarRegion>(MR);
602       const VarDecl *VD;
603       if (VR)
604         VD = VR->getDecl();
605       else
606         VD = NULL;
607 
608       if (VD)
609         os << "the address of the parameter '" << VD->getName() << "'";
610       else
611         os << "the address of a parameter";
612       return true;
613     }
614 
615     if (isa<GlobalsSpaceRegion>(MS)) {
616       const VarRegion *VR = dyn_cast<VarRegion>(MR);
617       const VarDecl *VD;
618       if (VR)
619         VD = VR->getDecl();
620       else
621         VD = NULL;
622 
623       if (VD) {
624         if (VD->isStaticLocal())
625           os << "the address of the static variable '" << VD->getName() << "'";
626         else
627           os << "the address of the global variable '" << VD->getName() << "'";
628       } else
629         os << "the address of a global variable";
630       return true;
631     }
632 
633     return false;
634   }
635   }
636 }
637 
638 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
639                                   SourceRange range) const {
640   if (ExplodedNode *N = C.generateSink()) {
641     if (!BT_BadFree)
642       BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
643 
644     SmallString<100> buf;
645     llvm::raw_svector_ostream os(buf);
646 
647     const MemRegion *MR = ArgVal.getAsRegion();
648     if (MR) {
649       while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
650         MR = ER->getSuperRegion();
651 
652       // Special case for alloca()
653       if (isa<AllocaRegion>(MR))
654         os << "Argument to free() was allocated by alloca(), not malloc()";
655       else {
656         os << "Argument to free() is ";
657         if (SummarizeRegion(os, MR))
658           os << ", which is not memory allocated by malloc()";
659         else
660           os << "not memory allocated by malloc()";
661       }
662     } else {
663       os << "Argument to free() is ";
664       if (SummarizeValue(os, ArgVal))
665         os << ", which is not memory allocated by malloc()";
666       else
667         os << "not memory allocated by malloc()";
668     }
669 
670     BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
671     R->markInteresting(MR);
672     R->addRange(range);
673     C.EmitReport(R);
674   }
675 }
676 
677 ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
678                                           const CallExpr *CE,
679                                           bool FreesOnFail) const {
680   ProgramStateRef state = C.getState();
681   const Expr *arg0Expr = CE->getArg(0);
682   const LocationContext *LCtx = C.getLocationContext();
683   SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
684   if (!isa<DefinedOrUnknownSVal>(Arg0Val))
685     return 0;
686   DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
687 
688   SValBuilder &svalBuilder = C.getSValBuilder();
689 
690   DefinedOrUnknownSVal PtrEQ =
691     svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
692 
693   // Get the size argument. If there is no size arg then give up.
694   const Expr *Arg1 = CE->getArg(1);
695   if (!Arg1)
696     return 0;
697 
698   // Get the value of the size argument.
699   SVal Arg1ValG = state->getSVal(Arg1, LCtx);
700   if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
701     return 0;
702   DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
703 
704   // Compare the size argument to 0.
705   DefinedOrUnknownSVal SizeZero =
706     svalBuilder.evalEQ(state, Arg1Val,
707                        svalBuilder.makeIntValWithPtrWidth(0, false));
708 
709   ProgramStateRef StatePtrIsNull, StatePtrNotNull;
710   llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
711   ProgramStateRef StateSizeIsZero, StateSizeNotZero;
712   llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
713   // We only assume exceptional states if they are definitely true; if the
714   // state is under-constrained, assume regular realloc behavior.
715   bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
716   bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
717 
718   // If the ptr is NULL and the size is not 0, the call is equivalent to
719   // malloc(size).
720   if ( PrtIsNull && !SizeIsZero) {
721     ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
722                                                UndefinedVal(), StatePtrIsNull);
723     return stateMalloc;
724   }
725 
726   if (PrtIsNull && SizeIsZero)
727     return 0;
728 
729   // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
730   assert(!PrtIsNull);
731   SymbolRef FromPtr = arg0Val.getAsSymbol();
732   SVal RetVal = state->getSVal(CE, LCtx);
733   SymbolRef ToPtr = RetVal.getAsSymbol();
734   if (!FromPtr || !ToPtr)
735     return 0;
736 
737   // If the size is 0, free the memory.
738   if (SizeIsZero)
739     if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
740       // The semantics of the return value are:
741       // If size was equal to 0, either NULL or a pointer suitable to be passed
742       // to free() is returned.
743       stateFree = stateFree->set<ReallocPairs>(ToPtr,
744                                             ReallocPair(FromPtr, FreesOnFail));
745       C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
746       return stateFree;
747     }
748 
749   // Default behavior.
750   if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
751     // FIXME: We should copy the content of the original buffer.
752     ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
753                                                 UnknownVal(), stateFree);
754     if (!stateRealloc)
755       return 0;
756     stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
757                                             ReallocPair(FromPtr, FreesOnFail));
758     C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
759     return stateRealloc;
760   }
761   return 0;
762 }
763 
764 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
765   ProgramStateRef state = C.getState();
766   SValBuilder &svalBuilder = C.getSValBuilder();
767   const LocationContext *LCtx = C.getLocationContext();
768   SVal count = state->getSVal(CE->getArg(0), LCtx);
769   SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
770   SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
771                                         svalBuilder.getContext().getSizeType());
772   SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
773 
774   return MallocMemAux(C, CE, TotalSize, zeroVal, state);
775 }
776 
777 const Stmt *
778 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
779                                  CheckerContext &C) const {
780   const LocationContext *LeakContext = N->getLocationContext();
781   // Walk the ExplodedGraph backwards and find the first node that referred to
782   // the tracked symbol.
783   const ExplodedNode *AllocNode = N;
784 
785   while (N) {
786     if (!N->getState()->get<RegionState>(Sym))
787       break;
788     // Allocation node, is the last node in the current context in which the
789     // symbol was tracked.
790     if (N->getLocationContext() == LeakContext)
791       AllocNode = N;
792     N = N->pred_empty() ? NULL : *(N->pred_begin());
793   }
794 
795   ProgramPoint P = AllocNode->getLocation();
796   if (!isa<StmtPoint>(P))
797     return 0;
798 
799   return cast<StmtPoint>(P).getStmt();
800 }
801 
802 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
803                                CheckerContext &C) const {
804   assert(N);
805   if (!BT_Leak) {
806     BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
807     // Leaks should not be reported if they are post-dominated by a sink:
808     // (1) Sinks are higher importance bugs.
809     // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
810     //     with __noreturn functions such as assert() or exit(). We choose not
811     //     to report leaks on such paths.
812     BT_Leak->setSuppressOnSink(true);
813   }
814 
815   // Most bug reports are cached at the location where they occurred.
816   // With leaks, we want to unique them by the location where they were
817   // allocated, and only report a single path.
818   PathDiagnosticLocation LocUsedForUniqueing;
819   if (const Stmt *AllocStmt = getAllocationSite(N, Sym, C))
820     LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
821                             C.getSourceManager(), N->getLocationContext());
822 
823   BugReport *R = new BugReport(*BT_Leak,
824     "Memory is never released; potential memory leak", N, LocUsedForUniqueing);
825   R->markInteresting(Sym);
826   R->addVisitor(new MallocBugVisitor(Sym));
827   C.EmitReport(R);
828 }
829 
830 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
831                                      CheckerContext &C) const
832 {
833   if (!SymReaper.hasDeadSymbols())
834     return;
835 
836   ProgramStateRef state = C.getState();
837   RegionStateTy RS = state->get<RegionState>();
838   RegionStateTy::Factory &F = state->get_context<RegionState>();
839 
840   bool generateReport = false;
841   llvm::SmallVector<SymbolRef, 2> Errors;
842   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
843     if (SymReaper.isDead(I->first)) {
844       if (I->second.isAllocated()) {
845         generateReport = true;
846         Errors.push_back(I->first);
847       }
848       // Remove the dead symbol from the map.
849       RS = F.remove(RS, I->first);
850 
851     }
852   }
853 
854   // Cleanup the Realloc Pairs Map.
855   ReallocMap RP = state->get<ReallocPairs>();
856   for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
857     if (SymReaper.isDead(I->first) ||
858         SymReaper.isDead(I->second.ReallocatedSym)) {
859       state = state->remove<ReallocPairs>(I->first);
860     }
861   }
862 
863   // Generate leak node.
864   static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
865   ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
866 
867   if (generateReport) {
868     for (llvm::SmallVector<SymbolRef, 2>::iterator
869          I = Errors.begin(), E = Errors.end(); I != E; ++I) {
870       reportLeak(*I, N, C);
871     }
872   }
873   C.addTransition(state->set<RegionState>(RS), N);
874 }
875 
876 void MallocChecker::checkEndPath(CheckerContext &C) const {
877   ProgramStateRef state = C.getState();
878   RegionStateTy M = state->get<RegionState>();
879 
880   // If inside inlined call, skip it.
881   if (C.getLocationContext()->getParent() != 0)
882     return;
883 
884   for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
885     RefState RS = I->second;
886     if (RS.isAllocated()) {
887       ExplodedNode *N = C.addTransition(state);
888       if (N)
889         reportLeak(I->first, N, C);
890     }
891   }
892 }
893 
894 bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
895                                 CheckerContext &C) const {
896   ProgramStateRef state = C.getState();
897   const RefState *RS = state->get<RegionState>(Sym);
898   if (!RS)
899     return false;
900 
901   if (RS->isAllocated()) {
902     state = state->set<RegionState>(Sym, RefState::getEscaped(S));
903     C.addTransition(state);
904     return true;
905   }
906   return false;
907 }
908 
909 void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
910   if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
911     return;
912 
913   // Check use after free, when a freed pointer is passed to a call.
914   ProgramStateRef State = C.getState();
915   for (CallExpr::const_arg_iterator I = CE->arg_begin(),
916                                     E = CE->arg_end(); I != E; ++I) {
917     const Expr *A = *I;
918     if (A->getType().getTypePtr()->isAnyPointerType()) {
919       SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
920       if (!Sym)
921         continue;
922       if (checkUseAfterFree(Sym, C, A))
923         return;
924     }
925   }
926 }
927 
928 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
929   const Expr *E = S->getRetValue();
930   if (!E)
931     return;
932 
933   // Check if we are returning a symbol.
934   SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
935   SymbolRef Sym = RetVal.getAsSymbol();
936   if (!Sym)
937     // If we are returning a field of the allocated struct or an array element,
938     // the callee could still free the memory.
939     // TODO: This logic should be a part of generic symbol escape callback.
940     if (const MemRegion *MR = RetVal.getAsRegion())
941       if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
942         if (const SymbolicRegion *BMR =
943               dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
944           Sym = BMR->getSymbol();
945   if (!Sym)
946     return;
947 
948   // Check if we are returning freed memory.
949   if (checkUseAfterFree(Sym, C, E))
950     return;
951 
952   // If this function body is not inlined, check if the symbol is escaping.
953   if (C.getLocationContext()->getParent() == 0)
954     checkEscape(Sym, E, C);
955 }
956 
957 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
958                                       const Stmt *S) const {
959   assert(Sym);
960   const RefState *RS = C.getState()->get<RegionState>(Sym);
961   if (RS && RS->isReleased()) {
962     if (ExplodedNode *N = C.generateSink()) {
963       if (!BT_UseFree)
964         BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
965 
966       BugReport *R = new BugReport(*BT_UseFree,
967                                    "Use of memory after it is freed",N);
968       if (S)
969         R->addRange(S->getSourceRange());
970       R->markInteresting(Sym);
971       R->addVisitor(new MallocBugVisitor(Sym));
972       C.EmitReport(R);
973       return true;
974     }
975   }
976   return false;
977 }
978 
979 // Check if the location is a freed symbolic region.
980 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
981                                   CheckerContext &C) const {
982   SymbolRef Sym = l.getLocSymbolInBase();
983   if (Sym)
984     checkUseAfterFree(Sym, C);
985 }
986 
987 //===----------------------------------------------------------------------===//
988 // Check various ways a symbol can be invalidated.
989 // TODO: This logic (the next 3 functions) is copied/similar to the
990 // RetainRelease checker. We might want to factor this out.
991 //===----------------------------------------------------------------------===//
992 
993 // Stop tracking symbols when a value escapes as a result of checkBind.
994 // A value escapes in three possible cases:
995 // (1) we are binding to something that is not a memory region.
996 // (2) we are binding to a memregion that does not have stack storage
997 // (3) we are binding to a memregion with stack storage that the store
998 //     does not understand.
999 void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1000                               CheckerContext &C) const {
1001   // Are we storing to something that causes the value to "escape"?
1002   bool escapes = true;
1003   ProgramStateRef state = C.getState();
1004 
1005   if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1006     escapes = !regionLoc->getRegion()->hasStackStorage();
1007 
1008     if (!escapes) {
1009       // To test (3), generate a new state with the binding added.  If it is
1010       // the same state, then it escapes (since the store cannot represent
1011       // the binding).
1012       escapes = (state == (state->bindLoc(*regionLoc, val)));
1013     }
1014     if (!escapes) {
1015       // Case 4: We do not currently model what happens when a symbol is
1016       // assigned to a struct field, so be conservative here and let the symbol
1017       // go. TODO: This could definitely be improved upon.
1018       escapes = !isa<VarRegion>(regionLoc->getRegion());
1019     }
1020   }
1021 
1022   // If our store can represent the binding and we aren't storing to something
1023   // that doesn't have local storage then just return and have the simulation
1024   // state continue as is.
1025   if (!escapes)
1026       return;
1027 
1028   // Otherwise, find all symbols referenced by 'val' that we are tracking
1029   // and stop tracking them.
1030   state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1031   C.addTransition(state);
1032 }
1033 
1034 // If a symbolic region is assumed to NULL (or another constant), stop tracking
1035 // it - assuming that allocation failed on this path.
1036 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1037                                               SVal Cond,
1038                                               bool Assumption) const {
1039   RegionStateTy RS = state->get<RegionState>();
1040   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1041     // If the symbol is assumed to NULL or another constant, this will
1042     // return an APSInt*.
1043     if (state->getSymVal(I.getKey()))
1044       state = state->remove<RegionState>(I.getKey());
1045   }
1046 
1047   // Realloc returns 0 when reallocation fails, which means that we should
1048   // restore the state of the pointer being reallocated.
1049   ReallocMap RP = state->get<ReallocPairs>();
1050   for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
1051     // If the symbol is assumed to NULL or another constant, this will
1052     // return an APSInt*.
1053     if (state->getSymVal(I.getKey())) {
1054       SymbolRef ReallocSym = I.getData().ReallocatedSym;
1055       const RefState *RS = state->get<RegionState>(ReallocSym);
1056       if (RS) {
1057         if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1058           state = state->set<RegionState>(ReallocSym,
1059                              RefState::getAllocateUnchecked(RS->getStmt()));
1060       }
1061       state = state->remove<ReallocPairs>(I.getKey());
1062     }
1063   }
1064 
1065   return state;
1066 }
1067 
1068 // Check if the function is known to us. So, for example, we could
1069 // conservatively assume it can free/reallocate it's pointer arguments.
1070 // (We assume that the pointers cannot escape through calls to system
1071 // functions not handled by this checker.)
1072 bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1073                                       ProgramStateRef State) const {
1074   if (!Call)
1075     return false;
1076 
1077   // For now, assume that any C++ call can free memory.
1078   // TODO: If we want to be more optimistic here, we'll need to make sure that
1079   // regions escape to C++ containers. They seem to do that even now, but for
1080   // mysterious reasons.
1081   if (Call->isCXXCall())
1082     return false;
1083 
1084   const Decl *D = Call->getDecl();
1085   if (!D)
1086     return false;
1087 
1088   ASTContext &ASTC = State->getStateManager().getContext();
1089 
1090   // If it's one of the allocation functions we can reason about, we model
1091   // its behavior explicitly.
1092   if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1093     return true;
1094   }
1095 
1096   // If it's not a system call, assume it frees memory.
1097   SourceManager &SM = ASTC.getSourceManager();
1098   if (!SM.isInSystemHeader(D->getLocation()))
1099     return false;
1100 
1101   // Process C/ObjC functions.
1102   if (const FunctionDecl *FD  = dyn_cast<FunctionDecl>(D)) {
1103     // White list the system functions whose arguments escape.
1104     const IdentifierInfo *II = FD->getIdentifier();
1105     if (!II)
1106       return true;
1107     StringRef FName = II->getName();
1108 
1109     // White list thread local storage.
1110     if (FName.equals("pthread_setspecific"))
1111       return false;
1112 
1113     // White list the 'XXXNoCopy' ObjC functions.
1114     if (FName.endswith("NoCopy")) {
1115       // Look for the deallocator argument. We know that the memory ownership
1116       // is not transfered only if the deallocator argument is
1117       // 'kCFAllocatorNull'.
1118       for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1119         const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1120         if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1121           StringRef DeallocatorName = DE->getFoundDecl()->getName();
1122           if (DeallocatorName == "kCFAllocatorNull")
1123             return true;
1124         }
1125       }
1126       return false;
1127     }
1128 
1129     // PR12101
1130     // Many CoreFoundation and CoreGraphics might allow a tracked object
1131     // to escape.
1132     if (Call->isCFCGAllowingEscape(FName))
1133       return false;
1134 
1135     // Associating streams with malloced buffers. The pointer can escape if
1136     // 'closefn' is specified (and if that function does free memory).
1137     // Currently, we do not inspect the 'closefn' function (PR12101).
1138     if (FName == "funopen")
1139       if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1140         return false;
1141 
1142     // Do not warn on pointers passed to 'setbuf' when used with std streams,
1143     // these leaks might be intentional when setting the buffer for stdio.
1144     // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1145     if (FName == "setbuf" || FName =="setbuffer" ||
1146         FName == "setlinebuf" || FName == "setvbuf") {
1147       if (Call->getNumArgs() >= 1)
1148         if (const DeclRefExpr *Arg =
1149               dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1150           if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1151               if (D->getCanonicalDecl()->getName().find("std")
1152                                                    != StringRef::npos)
1153                 return false;
1154     }
1155 
1156     // A bunch of other functions, which take ownership of a pointer (See retain
1157     // release checker). Not all the parameters here are invalidated, but the
1158     // Malloc checker cannot differentiate between them. The right way of doing
1159     // this would be to implement a pointer escapes callback.
1160     if (FName == "CVPixelBufferCreateWithBytes" ||
1161         FName == "CGBitmapContextCreateWithData" ||
1162         FName == "CVPixelBufferCreateWithPlanarBytes") {
1163       return false;
1164     }
1165 
1166     // Otherwise, assume that the function does not free memory.
1167     // Most system calls, do not free the memory.
1168     return true;
1169 
1170   // Process ObjC functions.
1171   } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1172     Selector S = ObjCD->getSelector();
1173 
1174     // White list the ObjC functions which do free memory.
1175     // - Anything containing 'freeWhenDone' param set to 1.
1176     //   Ex: dataWithBytesNoCopy:length:freeWhenDone.
1177     for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1178       if (S.getNameForSlot(i).equals("freeWhenDone")) {
1179         if (Call->getArgSVal(i).isConstant(1))
1180           return false;
1181         else
1182           return true;
1183       }
1184     }
1185 
1186     // If the first selector ends with NoCopy, assume that the ownership is
1187     // transfered as well.
1188     // Ex:  [NSData dataWithBytesNoCopy:bytes length:10];
1189     if (S.getNameForSlot(0).endswith("NoCopy")) {
1190       return false;
1191     }
1192 
1193     // Otherwise, assume that the function does not free memory.
1194     // Most system calls, do not free the memory.
1195     return true;
1196   }
1197 
1198   // Otherwise, assume that the function can free memory.
1199   return false;
1200 
1201 }
1202 
1203 // If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1204 // escapes, when we are tracking p), do not track the symbol as we cannot reason
1205 // about it anymore.
1206 ProgramStateRef
1207 MallocChecker::checkRegionChanges(ProgramStateRef State,
1208                             const StoreManager::InvalidatedSymbols *invalidated,
1209                                     ArrayRef<const MemRegion *> ExplicitRegions,
1210                                     ArrayRef<const MemRegion *> Regions,
1211                                     const CallOrObjCMessage *Call) const {
1212   if (!invalidated || invalidated->empty())
1213     return State;
1214   llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
1215 
1216   // If it's a call which might free or reallocate memory, we assume that all
1217   // regions (explicit and implicit) escaped.
1218 
1219   // Otherwise, whitelist explicit pointers; we still can track them.
1220   if (!Call || doesNotFreeMemory(Call, State)) {
1221     for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1222         E = ExplicitRegions.end(); I != E; ++I) {
1223       if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1224         WhitelistedSymbols.insert(R->getSymbol());
1225     }
1226   }
1227 
1228   for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1229        E = invalidated->end(); I!=E; ++I) {
1230     SymbolRef sym = *I;
1231     if (WhitelistedSymbols.count(sym))
1232       continue;
1233     // The symbol escaped.
1234     if (const RefState *RS = State->get<RegionState>(sym))
1235       State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
1236   }
1237   return State;
1238 }
1239 
1240 PathDiagnosticPiece *
1241 MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1242                                            const ExplodedNode *PrevN,
1243                                            BugReporterContext &BRC,
1244                                            BugReport &BR) {
1245   const RefState *RS = N->getState()->get<RegionState>(Sym);
1246   const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1247   if (!RS && !RSPrev)
1248     return 0;
1249 
1250   const Stmt *S = 0;
1251   const char *Msg = 0;
1252 
1253   // Retrieve the associated statement.
1254   ProgramPoint ProgLoc = N->getLocation();
1255   if (isa<StmtPoint>(ProgLoc))
1256     S = cast<StmtPoint>(ProgLoc).getStmt();
1257   // If an assumption was made on a branch, it should be caught
1258   // here by looking at the state transition.
1259   if (isa<BlockEdge>(ProgLoc)) {
1260     const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1261     S = srcBlk->getTerminator();
1262   }
1263   if (!S)
1264     return 0;
1265 
1266   // Find out if this is an interesting point and what is the kind.
1267   if (Mode == Normal) {
1268     if (isAllocated(RS, RSPrev, S))
1269       Msg = "Memory is allocated";
1270     else if (isReleased(RS, RSPrev, S))
1271       Msg = "Memory is released";
1272     else if (isReallocFailedCheck(RS, RSPrev, S)) {
1273       Mode = ReallocationFailed;
1274       Msg = "Reallocation failed";
1275     }
1276 
1277   // We are in a special mode if a reallocation failed later in the path.
1278   } else if (Mode == ReallocationFailed) {
1279     // Generate a special diagnostic for the first realloc we find.
1280     if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1281       return 0;
1282 
1283     // Check that the name of the function is realloc.
1284     const CallExpr *CE = dyn_cast<CallExpr>(S);
1285     if (!CE)
1286       return 0;
1287     const FunctionDecl *funDecl = CE->getDirectCallee();
1288     if (!funDecl)
1289       return 0;
1290     StringRef FunName = funDecl->getName();
1291     if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1292       return 0;
1293     Msg = "Attempt to reallocate memory";
1294     Mode = Normal;
1295   }
1296 
1297   if (!Msg)
1298     return 0;
1299 
1300   // Generate the extra diagnostic.
1301   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1302                              N->getLocationContext());
1303   return new PathDiagnosticEventPiece(Pos, Msg);
1304 }
1305 
1306 
1307 #define REGISTER_CHECKER(name) \
1308 void ento::register##name(CheckerManager &mgr) {\
1309   registerCStringCheckerBasic(mgr); \
1310   mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
1311 }
1312 
1313 REGISTER_CHECKER(MallocPessimistic)
1314 REGISTER_CHECKER(MallocOptimistic)
1315