MallocChecker.cpp revision e3659a78a96da3b9a5a90fa84c96078a84f0f3e3
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"
24using namespace clang;
25using namespace ento;
26
27namespace {
28
29class RefState {
30  enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
31              Relinquished } K;
32  const Stmt *S;
33
34public:
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
65class RegionState {};
66
67class 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
82public:
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  const ProgramState *evalAssume(const ProgramState *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
96private:
97  static void MallocMem(CheckerContext &C, const CallExpr *CE);
98  static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
99                                   const OwnershipAttr* Att);
100  static const ProgramState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
101                                     const Expr *SizeEx, SVal Init,
102                                     const ProgramState *state) {
103    return MallocMemAux(C, CE, state->getSVal(SizeEx), Init, state);
104  }
105  static const ProgramState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
106                                     SVal SizeEx, SVal Init,
107                                     const ProgramState *state);
108
109  void FreeMem(CheckerContext &C, const CallExpr *CE) const;
110  void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
111                   const OwnershipAttr* Att) const;
112  const ProgramState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
113                                 const ProgramState *state, unsigned Num,
114                                 bool Hold) const;
115
116  void ReallocMem(CheckerContext &C, const CallExpr *CE) const;
117  static void CallocMem(CheckerContext &C, const CallExpr *CE);
118
119  static bool SummarizeValue(raw_ostream &os, SVal V);
120  static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
121  void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
122};
123} // end anonymous namespace
124
125typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
126
127namespace clang {
128namespace ento {
129  template <>
130  struct ProgramStateTrait<RegionState>
131    : public ProgramStatePartialTrait<RegionStateTy> {
132    static void *GDMIndex() { static int x; return &x; }
133  };
134}
135}
136
137bool MallocChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
138  const FunctionDecl *FD = C.getCalleeDecl(CE);
139  if (!FD)
140    return false;
141
142  ASTContext &Ctx = C.getASTContext();
143  if (!II_malloc)
144    II_malloc = &Ctx.Idents.get("malloc");
145  if (!II_free)
146    II_free = &Ctx.Idents.get("free");
147  if (!II_realloc)
148    II_realloc = &Ctx.Idents.get("realloc");
149  if (!II_calloc)
150    II_calloc = &Ctx.Idents.get("calloc");
151
152  if (FD->getIdentifier() == II_malloc) {
153    MallocMem(C, CE);
154    return true;
155  }
156
157  if (FD->getIdentifier() == II_free) {
158    FreeMem(C, CE);
159    return true;
160  }
161
162  if (FD->getIdentifier() == II_realloc) {
163    ReallocMem(C, CE);
164    return true;
165  }
166
167  if (FD->getIdentifier() == II_calloc) {
168    CallocMem(C, CE);
169    return true;
170  }
171
172  // Check all the attributes, if there are any.
173  // There can be multiple of these attributes.
174  bool rv = false;
175  if (FD->hasAttrs()) {
176    for (specific_attr_iterator<OwnershipAttr>
177                  i = FD->specific_attr_begin<OwnershipAttr>(),
178                  e = FD->specific_attr_end<OwnershipAttr>();
179         i != e; ++i) {
180      switch ((*i)->getOwnKind()) {
181      case OwnershipAttr::Returns: {
182        MallocMemReturnsAttr(C, CE, *i);
183        rv = true;
184        break;
185      }
186      case OwnershipAttr::Takes:
187      case OwnershipAttr::Holds: {
188        FreeMemAttr(C, CE, *i);
189        rv = true;
190        break;
191      }
192      default:
193        break;
194      }
195    }
196  }
197  return rv;
198}
199
200void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
201  const ProgramState *state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
202                                      C.getState());
203  C.addTransition(state);
204}
205
206void 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    const ProgramState *state =
214        MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
215    C.addTransition(state);
216    return;
217  }
218  const ProgramState *state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
219                                        C.getState());
220  C.addTransition(state);
221}
222
223const ProgramState *MallocChecker::MallocMemAux(CheckerContext &C,
224                                           const CallExpr *CE,
225                                           SVal Size, SVal Init,
226                                           const ProgramState *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, 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
255void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
256  const ProgramState *state = FreeMemAux(C, CE, C.getState(), 0, false);
257
258  if (state)
259    C.addTransition(state);
260}
261
262void 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    const ProgramState *state =
270      FreeMemAux(C, CE, C.getState(), *I,
271                 Att->getOwnKind() == OwnershipAttr::Holds);
272    if (state)
273      C.addTransition(state);
274  }
275}
276
277const ProgramState *MallocChecker::FreeMemAux(CheckerContext &C,
278                                              const CallExpr *CE,
279                                              const ProgramState *state,
280                                              unsigned Num,
281                                              bool Hold) const {
282  const Expr *ArgExpr = CE->getArg(Num);
283  SVal ArgVal = state->getSVal(ArgExpr);
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  const ProgramState *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
376bool 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
389bool 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    switch (MS->getKind()) {
411    case MemRegion::StackLocalsSpaceRegionKind: {
412      const VarRegion *VR = dyn_cast<VarRegion>(MR);
413      const VarDecl *VD;
414      if (VR)
415        VD = VR->getDecl();
416      else
417        VD = NULL;
418
419      if (VD)
420        os << "the address of the local variable '" << VD->getName() << "'";
421      else
422        os << "the address of a local stack variable";
423      return true;
424    }
425    case MemRegion::StackArgumentsSpaceRegionKind: {
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    case MemRegion::NonStaticGlobalSpaceRegionKind:
440    case MemRegion::StaticGlobalSpaceRegionKind: {
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    default:
458      return false;
459    }
460  }
461  }
462}
463
464void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
465                                  SourceRange range) const {
466  if (ExplodedNode *N = C.generateSink()) {
467    if (!BT_BadFree)
468      BT_BadFree.reset(new BuiltinBug("Bad free"));
469
470    llvm::SmallString<100> buf;
471    llvm::raw_svector_ostream os(buf);
472
473    const MemRegion *MR = ArgVal.getAsRegion();
474    if (MR) {
475      while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
476        MR = ER->getSuperRegion();
477
478      // Special case for alloca()
479      if (isa<AllocaRegion>(MR))
480        os << "Argument to free() was allocated by alloca(), not malloc()";
481      else {
482        os << "Argument to free() is ";
483        if (SummarizeRegion(os, MR))
484          os << ", which is not memory allocated by malloc()";
485        else
486          os << "not memory allocated by malloc()";
487      }
488    } else {
489      os << "Argument to free() is ";
490      if (SummarizeValue(os, ArgVal))
491        os << ", which is not memory allocated by malloc()";
492      else
493        os << "not memory allocated by malloc()";
494    }
495
496    BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
497    R->addRange(range);
498    C.EmitReport(R);
499  }
500}
501
502void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
503  const ProgramState *state = C.getState();
504  const Expr *arg0Expr = CE->getArg(0);
505  DefinedOrUnknownSVal arg0Val
506    = cast<DefinedOrUnknownSVal>(state->getSVal(arg0Expr));
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));
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  const ProgramState *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    const ProgramState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
540                                              UndefinedVal(), stateEqual);
541    C.addTransition(stateMalloc);
542  }
543
544  if (const ProgramState *stateNotEqual = state->assume(PtrEQ, false)) {
545    // If the size is 0, free the memory.
546    if (const ProgramState *stateSizeZero =
547          stateNotEqual->assume(SizeZero, true))
548      if (const ProgramState *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, svalBuilder.makeNull(), true));
553      }
554    if (const ProgramState *stateSizeNotZero =
555          stateNotEqual->assume(SizeZero,false))
556      if (const ProgramState *stateFree = FreeMemAux(C, CE, stateSizeNotZero,
557                                                0, false)) {
558        // FIXME: We should copy the content of the original buffer.
559        const ProgramState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
560                                                   UnknownVal(), stateFree);
561        C.addTransition(stateRealloc);
562      }
563  }
564}
565
566void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
567  const ProgramState *state = C.getState();
568  SValBuilder &svalBuilder = C.getSValBuilder();
569
570  SVal count = state->getSVal(CE->getArg(0));
571  SVal elementSize = state->getSVal(CE->getArg(1));
572  SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
573                                        svalBuilder.getContext().getSizeType());
574  SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
575
576  C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
577}
578
579void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
580                                     CheckerContext &C) const
581{
582  if (!SymReaper.hasDeadSymbols())
583    return;
584
585  const ProgramState *state = C.getState();
586  RegionStateTy RS = state->get<RegionState>();
587  RegionStateTy::Factory &F = state->get_context<RegionState>();
588
589  bool generateReport = false;
590
591  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
592    if (SymReaper.isDead(I->first)) {
593      if (I->second.isAllocated())
594        generateReport = true;
595
596      // Remove the dead symbol from the map.
597      RS = F.remove(RS, I->first);
598
599    }
600  }
601
602  ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
603
604  // FIXME: This does not handle when we have multiple leaks at a single
605  // place.
606  if (N && generateReport) {
607    if (!BT_Leak)
608      BT_Leak.reset(new BuiltinBug("Memory leak",
609              "Allocated memory never released. Potential memory leak."));
610    // FIXME: where it is allocated.
611    BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
612    C.EmitReport(R);
613  }
614}
615
616void MallocChecker::checkEndPath(CheckerContext &Ctx) const {
617  const ProgramState *state = Ctx.getState();
618  RegionStateTy M = state->get<RegionState>();
619
620  for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
621    RefState RS = I->second;
622    if (RS.isAllocated()) {
623      ExplodedNode *N = Ctx.addTransition(state);
624      if (N) {
625        if (!BT_Leak)
626          BT_Leak.reset(new BuiltinBug("Memory leak",
627                    "Allocated memory never released. Potential memory leak."));
628        BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
629        Ctx.EmitReport(R);
630      }
631    }
632  }
633}
634
635void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
636  const Expr *retExpr = S->getRetValue();
637  if (!retExpr)
638    return;
639
640  const ProgramState *state = C.getState();
641
642  SymbolRef Sym = state->getSVal(retExpr).getAsSymbol();
643  if (!Sym)
644    return;
645
646  const RefState *RS = state->get<RegionState>(Sym);
647  if (!RS)
648    return;
649
650  // FIXME: check other cases.
651  if (RS->isAllocated())
652    state = state->set<RegionState>(Sym, RefState::getEscaped(S));
653
654  C.addTransition(state);
655}
656
657const ProgramState *MallocChecker::evalAssume(const ProgramState *state,
658                                              SVal Cond,
659                                              bool Assumption) const {
660  // If a symblic region is assumed to NULL, set its state to AllocateFailed.
661  // FIXME: should also check symbols assumed to non-null.
662
663  RegionStateTy RS = state->get<RegionState>();
664
665  for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
666    // If the symbol is assumed to NULL, this will return an APSInt*.
667    if (state->getSymVal(I.getKey()))
668      state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
669  }
670
671  return state;
672}
673
674// Check if the location is a freed symbolic region.
675void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
676                                  CheckerContext &C) const {
677  SymbolRef Sym = l.getLocSymbolInBase();
678  if (Sym) {
679    const RefState *RS = C.getState()->get<RegionState>(Sym);
680    if (RS && RS->isReleased()) {
681      if (ExplodedNode *N = C.addTransition()) {
682        if (!BT_UseFree)
683          BT_UseFree.reset(new BuiltinBug("Use dynamically allocated memory "
684                                          "after it is freed."));
685
686        BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
687                                     N);
688        C.EmitReport(R);
689      }
690    }
691  }
692}
693
694void MallocChecker::checkBind(SVal location, SVal val,
695                              const Stmt *BindS, CheckerContext &C) const {
696  // The PreVisitBind implements the same algorithm as already used by the
697  // Objective C ownership checker: if the pointer escaped from this scope by
698  // assignment, let it go.  However, assigning to fields of a stack-storage
699  // structure does not transfer ownership.
700
701  const ProgramState *state = C.getState();
702  DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
703
704  // Check for null dereferences.
705  if (!isa<Loc>(l))
706    return;
707
708  // Before checking if the state is null, check if 'val' has a RefState.
709  // Only then should we check for null and bifurcate the state.
710  SymbolRef Sym = val.getLocSymbolInBase();
711  if (Sym) {
712    if (const RefState *RS = state->get<RegionState>(Sym)) {
713      // If ptr is NULL, no operation is performed.
714      const ProgramState *notNullState, *nullState;
715      llvm::tie(notNullState, nullState) = state->assume(l);
716
717      // Generate a transition for 'nullState' to record the assumption
718      // that the state was null.
719      if (nullState)
720        C.addTransition(nullState);
721
722      if (!notNullState)
723        return;
724
725      if (RS->isAllocated()) {
726        // Something we presently own is being assigned somewhere.
727        const MemRegion *AR = location.getAsRegion();
728        if (!AR)
729          return;
730        AR = AR->StripCasts()->getBaseRegion();
731        do {
732          // If it is on the stack, we still own it.
733          if (AR->hasStackNonParametersStorage())
734            break;
735
736          // If the state can't represent this binding, we still own it.
737          if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
738                                                     UnknownVal())))
739            break;
740
741          // We no longer own this pointer.
742          notNullState =
743            notNullState->set<RegionState>(Sym,
744                                        RefState::getRelinquished(BindS));
745        }
746        while (false);
747      }
748      C.addTransition(notNullState);
749    }
750  }
751}
752
753void ento::registerMallocChecker(CheckerManager &mgr) {
754  mgr.registerChecker<MallocChecker>();
755}
756