xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (revision cd37bf4ec8e2043dc589a592df5c97144b5dee3b)
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 "clang/StaticAnalyzer/Core/Checker.h"
17 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
23 #include "llvm/ADT/ImmutableMap.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/STLExtras.h"
26 using namespace clang;
27 using namespace ento;
28 
29 namespace {
30 
31 class RefState {
32   enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
33               Relinquished } K;
34   const Stmt *S;
35 
36 public:
37   RefState(Kind k, const Stmt *s) : K(k), S(s) {}
38 
39   bool isAllocated() const { return K == AllocateUnchecked; }
40   //bool isFailed() const { return K == AllocateFailed; }
41   bool isReleased() const { return K == Released; }
42   //bool isEscaped() const { return K == Escaped; }
43   //bool isRelinquished() const { return K == Relinquished; }
44 
45   bool operator==(const RefState &X) const {
46     return K == X.K && S == X.S;
47   }
48 
49   static RefState getAllocateUnchecked(const Stmt *s) {
50     return RefState(AllocateUnchecked, s);
51   }
52   static RefState getAllocateFailed() {
53     return RefState(AllocateFailed, 0);
54   }
55   static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
56   static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
57   static RefState getRelinquished(const Stmt *s) {
58     return RefState(Relinquished, s);
59   }
60 
61   void Profile(llvm::FoldingSetNodeID &ID) const {
62     ID.AddInteger(K);
63     ID.AddPointer(S);
64   }
65 };
66 
67 class RegionState {};
68 
69 class MallocChecker : public Checker<check::DeadSymbols,
70                                      check::EndPath,
71                                      check::PreStmt<ReturnStmt>,
72                                      check::PostStmt<CallExpr>,
73                                      check::Location,
74                                      check::Bind,
75                                      eval::Assume>
76 {
77   mutable OwningPtr<BuiltinBug> BT_DoubleFree;
78   mutable OwningPtr<BuiltinBug> BT_Leak;
79   mutable OwningPtr<BuiltinBug> BT_UseFree;
80   mutable OwningPtr<BuiltinBug> BT_UseRelinquished;
81   mutable OwningPtr<BuiltinBug> BT_BadFree;
82   mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
83 
84 public:
85   MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
86 
87   /// In pessimistic mode, the checker assumes that it does not know which
88   /// functions might free the memory.
89   struct ChecksFilter {
90     DefaultBool CMallocPessimistic;
91     DefaultBool CMallocOptimistic;
92   };
93 
94   ChecksFilter Filter;
95 
96   void initIdentifierInfo(CheckerContext &C) const;
97 
98   void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
99   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
100   void checkEndPath(CheckerContext &C) const;
101   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
102   ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
103                             bool Assumption) const;
104   void checkLocation(SVal l, bool isLoad, const Stmt *S,
105                      CheckerContext &C) const;
106   void checkBind(SVal location, SVal val, const Stmt*S,
107                  CheckerContext &C) const;
108 
109 private:
110   static void MallocMem(CheckerContext &C, const CallExpr *CE);
111   static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
112                                    const OwnershipAttr* Att);
113   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
114                                      const Expr *SizeEx, SVal Init,
115                                      ProgramStateRef state) {
116     return MallocMemAux(C, CE,
117                         state->getSVal(SizeEx, C.getLocationContext()),
118                         Init, state);
119   }
120   static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
121                                      SVal SizeEx, SVal Init,
122                                      ProgramStateRef state);
123 
124   void FreeMem(CheckerContext &C, const CallExpr *CE) const;
125   void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
126                    const OwnershipAttr* Att) const;
127   ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
128                                  ProgramStateRef state, unsigned Num,
129                                  bool Hold) const;
130 
131   void ReallocMem(CheckerContext &C, const CallExpr *CE) const;
132   static void CallocMem(CheckerContext &C, const CallExpr *CE);
133 
134   static bool SummarizeValue(raw_ostream &os, SVal V);
135   static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
136   void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
137 };
138 } // end anonymous namespace
139 
140 typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
141 
142 namespace clang {
143 namespace ento {
144   template <>
145   struct ProgramStateTrait<RegionState>
146     : public ProgramStatePartialTrait<RegionStateTy> {
147     static void *GDMIndex() { static int x; return &x; }
148   };
149 }
150 }
151 
152 void MallocChecker::initIdentifierInfo(CheckerContext &C) const {
153   ASTContext &Ctx = C.getASTContext();
154   if (!II_malloc)
155     II_malloc = &Ctx.Idents.get("malloc");
156   if (!II_free)
157     II_free = &Ctx.Idents.get("free");
158   if (!II_realloc)
159     II_realloc = &Ctx.Idents.get("realloc");
160   if (!II_calloc)
161     II_calloc = &Ctx.Idents.get("calloc");
162 }
163 
164 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
165   const FunctionDecl *FD = C.getCalleeDecl(CE);
166   if (!FD)
167     return;
168   initIdentifierInfo(C);
169 
170   if (FD->getIdentifier() == II_malloc) {
171     MallocMem(C, CE);
172     return;
173   }
174   if (FD->getIdentifier() == II_realloc) {
175     ReallocMem(C, CE);
176     return;
177   }
178 
179   if (FD->getIdentifier() == II_calloc) {
180     CallocMem(C, CE);
181     return;
182   }
183 
184   if (FD->getIdentifier() == II_free) {
185     FreeMem(C, CE);
186     return;
187   }
188 
189   // Check all the attributes, if there are any.
190   // There can be multiple of these attributes.
191   if (FD->hasAttrs()) {
192     for (specific_attr_iterator<OwnershipAttr>
193                   i = FD->specific_attr_begin<OwnershipAttr>(),
194                   e = FD->specific_attr_end<OwnershipAttr>();
195          i != e; ++i) {
196       switch ((*i)->getOwnKind()) {
197       case OwnershipAttr::Returns: {
198         MallocMemReturnsAttr(C, CE, *i);
199         break;
200       }
201       case OwnershipAttr::Takes:
202       case OwnershipAttr::Holds: {
203         FreeMemAttr(C, CE, *i);
204         break;
205       }
206       }
207     }
208   }
209 }
210 
211 void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
212   ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
213                                       C.getState());
214   C.addTransition(state);
215 }
216 
217 void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
218                                          const OwnershipAttr* Att) {
219   if (Att->getModule() != "malloc")
220     return;
221 
222   OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
223   if (I != E) {
224     ProgramStateRef state =
225         MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
226     C.addTransition(state);
227     return;
228   }
229   ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
230                                         C.getState());
231   C.addTransition(state);
232 }
233 
234 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
235                                            const CallExpr *CE,
236                                            SVal Size, SVal Init,
237                                            ProgramStateRef state) {
238   SValBuilder &svalBuilder = C.getSValBuilder();
239 
240   // Get the return value.
241   SVal retVal = state->getSVal(CE, C.getLocationContext());
242 
243   // Fill the region with the initialization value.
244   state = state->bindDefault(retVal, Init);
245 
246   // Set the region's extent equal to the Size parameter.
247   const SymbolicRegion *R = cast<SymbolicRegion>(retVal.getAsRegion());
248   DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
249   DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
250   DefinedOrUnknownSVal extentMatchesSize =
251     svalBuilder.evalEQ(state, Extent, DefinedSize);
252 
253   state = state->assume(extentMatchesSize, true);
254   assert(state);
255 
256   SymbolRef Sym = retVal.getAsLocSymbol();
257   assert(Sym);
258 
259   // Set the symbol's state to Allocated.
260   return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
261 }
262 
263 void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
264   ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
265 
266   if (state)
267     C.addTransition(state);
268 }
269 
270 void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
271                                 const OwnershipAttr* Att) const {
272   if (Att->getModule() != "malloc")
273     return;
274 
275   for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
276        I != E; ++I) {
277     ProgramStateRef state =
278       FreeMemAux(C, CE, C.getState(), *I,
279                  Att->getOwnKind() == OwnershipAttr::Holds);
280     if (state)
281       C.addTransition(state);
282   }
283 }
284 
285 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
286                                               const CallExpr *CE,
287                                               ProgramStateRef state,
288                                               unsigned Num,
289                                               bool Hold) const {
290   const Expr *ArgExpr = CE->getArg(Num);
291   SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
292 
293   DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
294 
295   // Check for null dereferences.
296   if (!isa<Loc>(location))
297     return 0;
298 
299   // FIXME: Technically using 'Assume' here can result in a path
300   //  bifurcation.  In such cases we need to return two states, not just one.
301   ProgramStateRef notNullState, nullState;
302   llvm::tie(notNullState, nullState) = state->assume(location);
303 
304   // The explicit NULL case, no operation is performed.
305   if (nullState && !notNullState)
306     return 0;
307 
308   assert(notNullState);
309 
310   // Unknown values could easily be okay
311   // Undefined values are handled elsewhere
312   if (ArgVal.isUnknownOrUndef())
313     return 0;
314 
315   const MemRegion *R = ArgVal.getAsRegion();
316 
317   // Nonlocs can't be freed, of course.
318   // Non-region locations (labels and fixed addresses) also shouldn't be freed.
319   if (!R) {
320     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
321     return 0;
322   }
323 
324   R = R->StripCasts();
325 
326   // Blocks might show up as heap data, but should not be free()d
327   if (isa<BlockDataRegion>(R)) {
328     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
329     return 0;
330   }
331 
332   const MemSpaceRegion *MS = R->getMemorySpace();
333 
334   // TODO: Pessimize this. should be behinds a flag!
335   // Parameters, locals, statics, and globals shouldn't be freed.
336   if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
337     // FIXME: at the time this code was written, malloc() regions were
338     // represented by conjured symbols, which are all in UnknownSpaceRegion.
339     // This means that there isn't actually anything from HeapSpaceRegion
340     // that should be freed, even though we allow it here.
341     // Of course, free() can work on memory allocated outside the current
342     // function, so UnknownSpaceRegion is always a possibility.
343     // False negatives are better than false positives.
344 
345     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
346     return 0;
347   }
348 
349   const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
350   // Various cases could lead to non-symbol values here.
351   // For now, ignore them.
352   if (!SR)
353     return 0;
354 
355   SymbolRef Sym = SR->getSymbol();
356   const RefState *RS = state->get<RegionState>(Sym);
357 
358   // If the symbol has not been tracked, return. This is possible when free() is
359   // called on a pointer that does not get its pointee directly from malloc().
360   // Full support of this requires inter-procedural analysis.
361   if (!RS)
362     return 0;
363 
364   // Check double free.
365   if (RS->isReleased()) {
366     if (ExplodedNode *N = C.generateSink()) {
367       if (!BT_DoubleFree)
368         BT_DoubleFree.reset(
369           new BuiltinBug("Double free",
370                          "Try to free a memory block that has been released"));
371       // FIXME: should find where it's freed last time.
372       BugReport *R = new BugReport(*BT_DoubleFree,
373                                    BT_DoubleFree->getDescription(), N);
374       C.EmitReport(R);
375     }
376     return 0;
377   }
378 
379   // Normal free.
380   if (Hold)
381     return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
382   return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
383 }
384 
385 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
386   if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
387     os << "an integer (" << IntVal->getValue() << ")";
388   else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
389     os << "a constant address (" << ConstAddr->getValue() << ")";
390   else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
391     os << "the address of the label '" << Label->getLabel()->getName() << "'";
392   else
393     return false;
394 
395   return true;
396 }
397 
398 bool MallocChecker::SummarizeRegion(raw_ostream &os,
399                                     const MemRegion *MR) {
400   switch (MR->getKind()) {
401   case MemRegion::FunctionTextRegionKind: {
402     const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
403     if (FD)
404       os << "the address of the function '" << *FD << '\'';
405     else
406       os << "the address of a function";
407     return true;
408   }
409   case MemRegion::BlockTextRegionKind:
410     os << "block text";
411     return true;
412   case MemRegion::BlockDataRegionKind:
413     // FIXME: where the block came from?
414     os << "a block";
415     return true;
416   default: {
417     const MemSpaceRegion *MS = MR->getMemorySpace();
418 
419     if (isa<StackLocalsSpaceRegion>(MS)) {
420       const VarRegion *VR = dyn_cast<VarRegion>(MR);
421       const VarDecl *VD;
422       if (VR)
423         VD = VR->getDecl();
424       else
425         VD = NULL;
426 
427       if (VD)
428         os << "the address of the local variable '" << VD->getName() << "'";
429       else
430         os << "the address of a local stack variable";
431       return true;
432     }
433 
434     if (isa<StackArgumentsSpaceRegion>(MS)) {
435       const VarRegion *VR = dyn_cast<VarRegion>(MR);
436       const VarDecl *VD;
437       if (VR)
438         VD = VR->getDecl();
439       else
440         VD = NULL;
441 
442       if (VD)
443         os << "the address of the parameter '" << VD->getName() << "'";
444       else
445         os << "the address of a parameter";
446       return true;
447     }
448 
449     if (isa<GlobalsSpaceRegion>(MS)) {
450       const VarRegion *VR = dyn_cast<VarRegion>(MR);
451       const VarDecl *VD;
452       if (VR)
453         VD = VR->getDecl();
454       else
455         VD = NULL;
456 
457       if (VD) {
458         if (VD->isStaticLocal())
459           os << "the address of the static variable '" << VD->getName() << "'";
460         else
461           os << "the address of the global variable '" << VD->getName() << "'";
462       } else
463         os << "the address of a global variable";
464       return true;
465     }
466 
467     return false;
468   }
469   }
470 }
471 
472 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
473                                   SourceRange range) const {
474   if (ExplodedNode *N = C.generateSink()) {
475     if (!BT_BadFree)
476       BT_BadFree.reset(new BuiltinBug("Bad free"));
477 
478     SmallString<100> buf;
479     llvm::raw_svector_ostream os(buf);
480 
481     const MemRegion *MR = ArgVal.getAsRegion();
482     if (MR) {
483       while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
484         MR = ER->getSuperRegion();
485 
486       // Special case for alloca()
487       if (isa<AllocaRegion>(MR))
488         os << "Argument to free() was allocated by alloca(), not malloc()";
489       else {
490         os << "Argument to free() is ";
491         if (SummarizeRegion(os, MR))
492           os << ", which is not memory allocated by malloc()";
493         else
494           os << "not memory allocated by malloc()";
495       }
496     } else {
497       os << "Argument to free() is ";
498       if (SummarizeValue(os, ArgVal))
499         os << ", which is not memory allocated by malloc()";
500       else
501         os << "not memory allocated by malloc()";
502     }
503 
504     BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
505     R->addRange(range);
506     C.EmitReport(R);
507   }
508 }
509 
510 void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
511   ProgramStateRef state = C.getState();
512   const Expr *arg0Expr = CE->getArg(0);
513   const LocationContext *LCtx = C.getLocationContext();
514   DefinedOrUnknownSVal arg0Val
515     = cast<DefinedOrUnknownSVal>(state->getSVal(arg0Expr, LCtx));
516 
517   SValBuilder &svalBuilder = C.getSValBuilder();
518 
519   DefinedOrUnknownSVal PtrEQ =
520     svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
521 
522   // Get the size argument. If there is no size arg then give up.
523   const Expr *Arg1 = CE->getArg(1);
524   if (!Arg1)
525     return;
526 
527   // Get the value of the size argument.
528   DefinedOrUnknownSVal Arg1Val =
529     cast<DefinedOrUnknownSVal>(state->getSVal(Arg1, LCtx));
530 
531   // Compare the size argument to 0.
532   DefinedOrUnknownSVal SizeZero =
533     svalBuilder.evalEQ(state, Arg1Val,
534                        svalBuilder.makeIntValWithPtrWidth(0, false));
535 
536   // If the ptr is NULL and the size is not 0, the call is equivalent to
537   // malloc(size).
538   ProgramStateRef stateEqual = state->assume(PtrEQ, true);
539   if (stateEqual && state->assume(SizeZero, false)) {
540     // Hack: set the NULL symbolic region to released to suppress false warning.
541     // In the future we should add more states for allocated regions, e.g.,
542     // CheckedNull, CheckedNonNull.
543 
544     SymbolRef Sym = arg0Val.getAsLocSymbol();
545     if (Sym)
546       stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
547 
548     ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
549                                               UndefinedVal(), stateEqual);
550     C.addTransition(stateMalloc);
551   }
552 
553   if (ProgramStateRef stateNotEqual = state->assume(PtrEQ, false)) {
554     // If the size is 0, free the memory.
555     if (ProgramStateRef stateSizeZero =
556           stateNotEqual->assume(SizeZero, true))
557       if (ProgramStateRef stateFree =
558           FreeMemAux(C, CE, stateSizeZero, 0, false)) {
559 
560         // Bind the return value to NULL because it is now free.
561         C.addTransition(stateFree->BindExpr(CE, LCtx,
562                                             svalBuilder.makeNull(), true));
563       }
564     if (ProgramStateRef stateSizeNotZero =
565           stateNotEqual->assume(SizeZero,false))
566       if (ProgramStateRef stateFree = FreeMemAux(C, CE, stateSizeNotZero,
567                                                 0, false)) {
568         // FIXME: We should copy the content of the original buffer.
569         ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
570                                                    UnknownVal(), stateFree);
571         C.addTransition(stateRealloc);
572       }
573   }
574 }
575 
576 void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
577   ProgramStateRef state = C.getState();
578   SValBuilder &svalBuilder = C.getSValBuilder();
579   const LocationContext *LCtx = C.getLocationContext();
580   SVal count = state->getSVal(CE->getArg(0), LCtx);
581   SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
582   SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
583                                         svalBuilder.getContext().getSizeType());
584   SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
585 
586   C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
587 }
588 
589 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
590                                      CheckerContext &C) const
591 {
592   if (!SymReaper.hasDeadSymbols())
593     return;
594 
595   ProgramStateRef state = C.getState();
596   RegionStateTy RS = state->get<RegionState>();
597   RegionStateTy::Factory &F = state->get_context<RegionState>();
598 
599   bool generateReport = false;
600 
601   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
602     if (SymReaper.isDead(I->first)) {
603       if (I->second.isAllocated())
604         generateReport = true;
605 
606       // Remove the dead symbol from the map.
607       RS = F.remove(RS, I->first);
608 
609     }
610   }
611 
612   ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
613 
614   // FIXME: This does not handle when we have multiple leaks at a single
615   // place.
616   if (N && generateReport) {
617     if (!BT_Leak)
618       BT_Leak.reset(new BuiltinBug("Memory leak",
619               "Allocated memory never released. Potential memory leak."));
620     // FIXME: where it is allocated.
621     BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
622     C.EmitReport(R);
623   }
624 }
625 
626 void MallocChecker::checkEndPath(CheckerContext &Ctx) const {
627   ProgramStateRef state = Ctx.getState();
628   RegionStateTy M = state->get<RegionState>();
629 
630   for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
631     RefState RS = I->second;
632     if (RS.isAllocated()) {
633       ExplodedNode *N = Ctx.addTransition(state);
634       if (N) {
635         if (!BT_Leak)
636           BT_Leak.reset(new BuiltinBug("Memory leak",
637                     "Allocated memory never released. Potential memory leak."));
638         BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
639         Ctx.EmitReport(R);
640       }
641     }
642   }
643 }
644 
645 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
646   const Expr *retExpr = S->getRetValue();
647   if (!retExpr)
648     return;
649 
650   ProgramStateRef state = C.getState();
651 
652   SymbolRef Sym = state->getSVal(retExpr, C.getLocationContext()).getAsSymbol();
653   if (!Sym)
654     return;
655 
656   const RefState *RS = state->get<RegionState>(Sym);
657   if (!RS)
658     return;
659 
660   // FIXME: check other cases.
661   if (RS->isAllocated())
662     state = state->set<RegionState>(Sym, RefState::getEscaped(S));
663 
664   C.addTransition(state);
665 }
666 
667 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
668                                               SVal Cond,
669                                               bool Assumption) const {
670   // If a symblic region is assumed to NULL, set its state to AllocateFailed.
671   // FIXME: should also check symbols assumed to non-null.
672 
673   RegionStateTy RS = state->get<RegionState>();
674 
675   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
676     // If the symbol is assumed to NULL, this will return an APSInt*.
677     if (state->getSymVal(I.getKey()))
678       state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
679   }
680 
681   return state;
682 }
683 
684 // Check if the location is a freed symbolic region.
685 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
686                                   CheckerContext &C) const {
687   SymbolRef Sym = l.getLocSymbolInBase();
688   if (Sym) {
689     const RefState *RS = C.getState()->get<RegionState>(Sym);
690     if (RS && RS->isReleased()) {
691       if (ExplodedNode *N = C.addTransition()) {
692         if (!BT_UseFree)
693           BT_UseFree.reset(new BuiltinBug("Use dynamically allocated memory "
694                                           "after it is freed."));
695 
696         BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
697                                      N);
698         C.EmitReport(R);
699       }
700     }
701   }
702 }
703 
704 void MallocChecker::checkBind(SVal location, SVal val,
705                               const Stmt *BindS, CheckerContext &C) const {
706   // The PreVisitBind implements the same algorithm as already used by the
707   // Objective C ownership checker: if the pointer escaped from this scope by
708   // assignment, let it go.  However, assigning to fields of a stack-storage
709   // structure does not transfer ownership.
710 
711   ProgramStateRef state = C.getState();
712   DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
713 
714   // Check for null dereferences.
715   if (!isa<Loc>(l))
716     return;
717 
718   // Before checking if the state is null, check if 'val' has a RefState.
719   // Only then should we check for null and bifurcate the state.
720   SymbolRef Sym = val.getLocSymbolInBase();
721   if (Sym) {
722     if (const RefState *RS = state->get<RegionState>(Sym)) {
723       // If ptr is NULL, no operation is performed.
724       ProgramStateRef notNullState, nullState;
725       llvm::tie(notNullState, nullState) = state->assume(l);
726 
727       // Generate a transition for 'nullState' to record the assumption
728       // that the state was null.
729       if (nullState)
730         C.addTransition(nullState);
731 
732       if (!notNullState)
733         return;
734 
735       if (RS->isAllocated()) {
736         // Something we presently own is being assigned somewhere.
737         const MemRegion *AR = location.getAsRegion();
738         if (!AR)
739           return;
740         AR = AR->StripCasts()->getBaseRegion();
741         do {
742           // If it is on the stack, we still own it.
743           if (AR->hasStackNonParametersStorage())
744             break;
745 
746           // If the state can't represent this binding, we still own it.
747           if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
748                                                      UnknownVal())))
749             break;
750 
751           // We no longer own this pointer.
752           notNullState =
753             notNullState->set<RegionState>(Sym,
754                                         RefState::getRelinquished(BindS));
755         }
756         while (false);
757       }
758       C.addTransition(notNullState);
759     }
760   }
761 }
762 
763 #define REGISTER_CHECKER(name) \
764 void ento::register##name(CheckerManager &mgr) {\
765   mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
766 }
767 
768 REGISTER_CHECKER(MallocPessimistic)
769 REGISTER_CHECKER(MallocOptimistic)
770