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