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