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