blob: 8a704760e4d63b70a7c3a393ff1aca60cbcc2af7 [file] [log] [blame]
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001//=== 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
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000017#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000018#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaks66c40402012-02-14 21:55:24 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Anna Zaks15d0ae12012-02-11 23:46:36 +000025#include "clang/Basic/SourceManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000026#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000027#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000029#include <climits>
30
Zhongxing Xu589c0f22009-11-12 08:38:56 +000031using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000032using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000033
34namespace {
35
Zhongxing Xu7fb14642009-12-11 00:55:44 +000036class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000037 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
38 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000039 const Stmt *S;
40
Zhongxing Xu7fb14642009-12-11 00:55:44 +000041public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000042 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
43
Zhongxing Xub94b81a2009-12-31 06:13:07 +000044 bool isAllocated() const { return K == AllocateUnchecked; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000045 bool isReleased() const { return K == Released; }
Anna Zaksca23eb22012-02-29 18:42:47 +000046
Anna Zaksc8bb3be2012-02-13 18:05:39 +000047 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000048
49 bool operator==(const RefState &X) const {
50 return K == X.K && S == X.S;
51 }
52
Zhongxing Xub94b81a2009-12-31 06:13:07 +000053 static RefState getAllocateUnchecked(const Stmt *s) {
54 return RefState(AllocateUnchecked, s);
55 }
56 static RefState getAllocateFailed() {
57 return RefState(AllocateFailed, 0);
58 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000059 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
60 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000061 static RefState getRelinquished(const Stmt *s) {
62 return RefState(Relinquished, s);
63 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064
65 void Profile(llvm::FoldingSetNodeID &ID) const {
66 ID.AddInteger(K);
67 ID.AddPointer(S);
68 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000069};
70
Anna Zaks40add292012-02-15 00:11:25 +000071struct ReallocPair {
72 SymbolRef ReallocatedSym;
73 bool IsFreeOnFailure;
74 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
75 void Profile(llvm::FoldingSetNodeID &ID) const {
76 ID.AddInteger(IsFreeOnFailure);
77 ID.AddPointer(ReallocatedSym);
78 }
79 bool operator==(const ReallocPair &X) const {
80 return ReallocatedSym == X.ReallocatedSym &&
81 IsFreeOnFailure == X.IsFreeOnFailure;
82 }
83};
84
Anna Zaksb319e022012-02-08 20:13:28 +000085class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000086 check::EndPath,
87 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000088 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000089 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000090 check::Location,
91 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000092 eval::Assume,
93 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000094{
Anna Zaksfebdc322012-02-16 22:26:12 +000095 mutable OwningPtr<BugType> BT_DoubleFree;
96 mutable OwningPtr<BugType> BT_Leak;
97 mutable OwningPtr<BugType> BT_UseFree;
98 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +000099 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000100 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
101
102 static const unsigned InvalidArgIndex = UINT_MAX;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000103
104public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000105 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000106 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000107
108 /// In pessimistic mode, the checker assumes that it does not know which
109 /// functions might free the memory.
110 struct ChecksFilter {
111 DefaultBool CMallocPessimistic;
112 DefaultBool CMallocOptimistic;
113 };
114
115 ChecksFilter Filter;
116
Anna Zaks66c40402012-02-14 21:55:24 +0000117 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000118 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000119 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000120 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000121 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000123 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000124 void checkLocation(SVal l, bool isLoad, const Stmt *S,
125 CheckerContext &C) const;
126 void checkBind(SVal location, SVal val, const Stmt*S,
127 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000128 ProgramStateRef
129 checkRegionChanges(ProgramStateRef state,
130 const StoreManager::InvalidatedSymbols *invalidated,
131 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000132 ArrayRef<const MemRegion *> Regions,
133 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000134 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
135 return true;
136 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000137
Zhongxing Xu7b760962009-11-13 07:25:27 +0000138private:
Anna Zaks66c40402012-02-14 21:55:24 +0000139 void initIdentifierInfo(ASTContext &C) const;
140
141 /// Check if this is one of the functions which can allocate/reallocate memory
142 /// pointed to by one of its arguments.
143 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
144
Anna Zaks87cb5be2012-02-22 19:24:52 +0000145 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
146 const CallExpr *CE,
147 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000148 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000149 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000150 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000151 return MallocMemAux(C, CE,
152 state->getSVal(SizeEx, C.getLocationContext()),
153 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000154 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000155
Ted Kremenek8bef8232012-01-26 21:29:00 +0000156 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000157 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000158 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000159
Anna Zaks87cb5be2012-02-22 19:24:52 +0000160 /// Update the RefState to reflect the new memory allocation.
161 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
162 const CallExpr *CE,
163 ProgramStateRef state);
164
165 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
166 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000167 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
168 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000169 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000170
Anna Zaks87cb5be2012-02-22 19:24:52 +0000171 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
172 bool FreesMemOnFailure) const;
173 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000174
Anna Zaks91c2a112012-02-08 23:16:56 +0000175 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
176 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
177 const Stmt *S = 0) const;
178
Anna Zaks66c40402012-02-14 21:55:24 +0000179 /// Check if the function is not known to us. So, for example, we could
180 /// conservatively assume it can free/reallocate it's pointer arguments.
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000181 bool doesNotFreeMemory(const CallOrObjCMessage *Call,
182 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000183
Ted Kremenek9c378f72011-08-12 23:37:29 +0000184 static bool SummarizeValue(raw_ostream &os, SVal V);
185 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000186 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000187
Anna Zaksca8e36e2012-02-23 21:38:21 +0000188 /// Find the location of the allocation for Sym on the path leading to the
189 /// exploded node N.
190 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
191 CheckerContext &C) const;
192
Anna Zaksda046772012-02-11 21:02:40 +0000193 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
194
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000195 /// The bug visitor which allows us to print extra diagnostics along the
196 /// BugReport path. For example, showing the allocation site of the leaked
197 /// region.
198 class MallocBugVisitor : public BugReporterVisitor {
199 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000200 enum NotificationMode {
201 Normal,
202 Complete,
203 ReallocationFailed
204 };
205
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000206 // The allocated region symbol tracked by the main analysis.
207 SymbolRef Sym;
Anna Zaksfe571602012-02-16 22:26:07 +0000208 NotificationMode Mode;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000209
210 public:
Anna Zaksfe571602012-02-16 22:26:07 +0000211 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000212 virtual ~MallocBugVisitor() {}
213
214 void Profile(llvm::FoldingSetNodeID &ID) const {
215 static int X = 0;
216 ID.AddPointer(&X);
217 ID.AddPointer(Sym);
218 }
219
Anna Zaksfe571602012-02-16 22:26:07 +0000220 inline bool isAllocated(const RefState *S, const RefState *SPrev,
221 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000222 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000223 return (Stmt && isa<CallExpr>(Stmt) &&
224 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000225 }
226
Anna Zaksfe571602012-02-16 22:26:07 +0000227 inline bool isReleased(const RefState *S, const RefState *SPrev,
228 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000229 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000230 return (Stmt && isa<CallExpr>(Stmt) &&
231 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
232 }
233
234 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
235 const Stmt *Stmt) {
236 // If the expression is not a call, and the state change is
237 // released -> allocated, it must be the realloc return value
238 // check. If we have to handle more cases here, it might be cleaner just
239 // to track this extra bit in the state itself.
240 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
241 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000242 }
243
244 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
245 const ExplodedNode *PrevN,
246 BugReporterContext &BRC,
247 BugReport &BR);
248 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000249};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000250} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000251
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000252typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000253typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000254class RegionState {};
255class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000256namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000257namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000258 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000259 struct ProgramStateTrait<RegionState>
260 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000261 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000262 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000263
264 template <>
265 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000266 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000267 static void *GDMIndex() { static int x; return &x; }
268 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000269}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000270}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000271
Anna Zaks4fb54872012-02-11 21:02:35 +0000272namespace {
273class StopTrackingCallback : public SymbolVisitor {
274 ProgramStateRef state;
275public:
276 StopTrackingCallback(ProgramStateRef st) : state(st) {}
277 ProgramStateRef getState() const { return state; }
278
279 bool VisitSymbol(SymbolRef sym) {
280 state = state->remove<RegionState>(sym);
281 return true;
282 }
283};
284} // end anonymous namespace
285
Anna Zaks66c40402012-02-14 21:55:24 +0000286void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000287 if (!II_malloc)
288 II_malloc = &Ctx.Idents.get("malloc");
289 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000290 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000291 if (!II_realloc)
292 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000293 if (!II_reallocf)
294 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000295 if (!II_calloc)
296 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000297 if (!II_valloc)
298 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaks60a1fa42012-02-22 03:14:20 +0000299 if (!II_strdup)
300 II_strdup = &Ctx.Idents.get("strdup");
301 if (!II_strndup)
302 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000303}
304
Anna Zaks66c40402012-02-14 21:55:24 +0000305bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000306 if (!FD)
307 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000308 IdentifierInfo *FunI = FD->getIdentifier();
309 if (!FunI)
310 return false;
311
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000312 initIdentifierInfo(C);
313
Anna Zaks40add292012-02-15 00:11:25 +0000314 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000315 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
316 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000317 return true;
318
319 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
320 FD->specific_attr_begin<OwnershipAttr>() !=
321 FD->specific_attr_end<OwnershipAttr>())
322 return true;
323
324
325 return false;
326}
327
Anna Zaksb319e022012-02-08 20:13:28 +0000328void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
329 const FunctionDecl *FD = C.getCalleeDecl(CE);
330 if (!FD)
331 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000332
Anna Zaksb16ce452012-02-15 00:11:22 +0000333 initIdentifierInfo(C.getASTContext());
334 IdentifierInfo *FunI = FD->getIdentifier();
335 if (!FunI)
336 return;
337
Anna Zaks87cb5be2012-02-22 19:24:52 +0000338 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000339 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000340 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000341 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000342 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000343 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000344 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000345 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000346 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000347 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000348 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000349 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000350 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000351 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000352 State = MallocUpdateRefState(C, CE, State);
353 } else if (Filter.CMallocOptimistic) {
354 // Check all the attributes, if there are any.
355 // There can be multiple of these attributes.
356 if (FD->hasAttrs())
357 for (specific_attr_iterator<OwnershipAttr>
358 i = FD->specific_attr_begin<OwnershipAttr>(),
359 e = FD->specific_attr_end<OwnershipAttr>();
360 i != e; ++i) {
361 switch ((*i)->getOwnKind()) {
362 case OwnershipAttr::Returns:
363 State = MallocMemReturnsAttr(C, CE, *i);
364 break;
365 case OwnershipAttr::Takes:
366 case OwnershipAttr::Holds:
367 State = FreeMemAttr(C, CE, *i);
368 break;
369 }
370 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000371 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000372 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000373}
374
Anna Zaks87cb5be2012-02-22 19:24:52 +0000375ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
376 const CallExpr *CE,
377 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000378 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000379 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000380
Sean Huntcf807c42010-08-18 23:23:40 +0000381 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000382 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000383 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000384 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000385 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000386}
387
Anna Zaksb319e022012-02-08 20:13:28 +0000388ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000389 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000390 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000391 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000392 // Get the return value.
393 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000394
Anna Zaksb16ce452012-02-15 00:11:22 +0000395 // We expect the malloc functions to return a pointer.
396 if (!isa<Loc>(retVal))
397 return 0;
398
Jordy Rose32f26562010-07-04 00:00:41 +0000399 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000400 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000401
Jordy Rose32f26562010-07-04 00:00:41 +0000402 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000403 const SymbolicRegion *R =
404 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000405 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000406 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000407 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000408 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000409 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
410 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
411 DefinedOrUnknownSVal extentMatchesSize =
412 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000413
Anna Zaks60a1fa42012-02-22 03:14:20 +0000414 state = state->assume(extentMatchesSize, true);
415 assert(state);
416 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000417
Anna Zaks87cb5be2012-02-22 19:24:52 +0000418 return MallocUpdateRefState(C, CE, state);
419}
420
421ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
422 const CallExpr *CE,
423 ProgramStateRef state) {
424 // Get the return value.
425 SVal retVal = state->getSVal(CE, C.getLocationContext());
426
427 // We expect the malloc functions to return a pointer.
428 if (!isa<Loc>(retVal))
429 return 0;
430
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000431 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000432 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000433
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000434 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000435 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000436
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000437}
438
Anna Zaks87cb5be2012-02-22 19:24:52 +0000439ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
440 const CallExpr *CE,
441 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000442 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000443 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000444
Anna Zaksb3d72752012-03-01 22:06:06 +0000445 ProgramStateRef State = C.getState();
446
Sean Huntcf807c42010-08-18 23:23:40 +0000447 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
448 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000449 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
450 Att->getOwnKind() == OwnershipAttr::Holds);
451 if (StateI)
452 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000453 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000454 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000455}
456
Ted Kremenek8bef8232012-01-26 21:29:00 +0000457ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000458 const CallExpr *CE,
459 ProgramStateRef state,
460 unsigned Num,
461 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000462 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000463 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000464 if (!isa<DefinedOrUnknownSVal>(ArgVal))
465 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000466 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
467
468 // Check for null dereferences.
469 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000470 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000471
Anna Zaksb276bd92012-02-14 00:26:13 +0000472 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000473 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000474 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000475 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000476 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000477
Jordy Rose43859f62010-06-07 19:32:37 +0000478 // Unknown values could easily be okay
479 // Undefined values are handled elsewhere
480 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000481 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000482
Jordy Rose43859f62010-06-07 19:32:37 +0000483 const MemRegion *R = ArgVal.getAsRegion();
484
485 // Nonlocs can't be freed, of course.
486 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
487 if (!R) {
488 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000489 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000490 }
491
492 R = R->StripCasts();
493
494 // Blocks might show up as heap data, but should not be free()d
495 if (isa<BlockDataRegion>(R)) {
496 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000497 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000498 }
499
500 const MemSpaceRegion *MS = R->getMemorySpace();
501
502 // Parameters, locals, statics, and globals shouldn't be freed.
503 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
504 // FIXME: at the time this code was written, malloc() regions were
505 // represented by conjured symbols, which are all in UnknownSpaceRegion.
506 // This means that there isn't actually anything from HeapSpaceRegion
507 // that should be freed, even though we allow it here.
508 // Of course, free() can work on memory allocated outside the current
509 // function, so UnknownSpaceRegion is always a possibility.
510 // False negatives are better than false positives.
511
512 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000513 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000514 }
515
516 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
517 // Various cases could lead to non-symbol values here.
518 // For now, ignore them.
519 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000520 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000521
522 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000523 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000524
525 // If the symbol has not been tracked, return. This is possible when free() is
526 // called on a pointer that does not get its pointee directly from malloc().
527 // Full support of this requires inter-procedural analysis.
528 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000529 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000530
531 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000532 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000533 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000534 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000535 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000536 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000537 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000538 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000539 R->addRange(ArgExpr->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000540 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000541 C.EmitReport(R);
542 }
Anna Zaksb319e022012-02-08 20:13:28 +0000543 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000544 }
545
546 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000547 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000548 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
549 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000550}
551
Ted Kremenek9c378f72011-08-12 23:37:29 +0000552bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000553 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
554 os << "an integer (" << IntVal->getValue() << ")";
555 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
556 os << "a constant address (" << ConstAddr->getValue() << ")";
557 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000558 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000559 else
560 return false;
561
562 return true;
563}
564
Ted Kremenek9c378f72011-08-12 23:37:29 +0000565bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000566 const MemRegion *MR) {
567 switch (MR->getKind()) {
568 case MemRegion::FunctionTextRegionKind: {
569 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
570 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000571 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000572 else
573 os << "the address of a function";
574 return true;
575 }
576 case MemRegion::BlockTextRegionKind:
577 os << "block text";
578 return true;
579 case MemRegion::BlockDataRegionKind:
580 // FIXME: where the block came from?
581 os << "a block";
582 return true;
583 default: {
584 const MemSpaceRegion *MS = MR->getMemorySpace();
585
Anna Zakseb31a762012-01-04 23:54:01 +0000586 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000587 const VarRegion *VR = dyn_cast<VarRegion>(MR);
588 const VarDecl *VD;
589 if (VR)
590 VD = VR->getDecl();
591 else
592 VD = NULL;
593
594 if (VD)
595 os << "the address of the local variable '" << VD->getName() << "'";
596 else
597 os << "the address of a local stack variable";
598 return true;
599 }
Anna Zakseb31a762012-01-04 23:54:01 +0000600
601 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000602 const VarRegion *VR = dyn_cast<VarRegion>(MR);
603 const VarDecl *VD;
604 if (VR)
605 VD = VR->getDecl();
606 else
607 VD = NULL;
608
609 if (VD)
610 os << "the address of the parameter '" << VD->getName() << "'";
611 else
612 os << "the address of a parameter";
613 return true;
614 }
Anna Zakseb31a762012-01-04 23:54:01 +0000615
616 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000617 const VarRegion *VR = dyn_cast<VarRegion>(MR);
618 const VarDecl *VD;
619 if (VR)
620 VD = VR->getDecl();
621 else
622 VD = NULL;
623
624 if (VD) {
625 if (VD->isStaticLocal())
626 os << "the address of the static variable '" << VD->getName() << "'";
627 else
628 os << "the address of the global variable '" << VD->getName() << "'";
629 } else
630 os << "the address of a global variable";
631 return true;
632 }
Anna Zakseb31a762012-01-04 23:54:01 +0000633
634 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000635 }
636 }
637}
638
639void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000640 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000641 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000642 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000643 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000644
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000645 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000646 llvm::raw_svector_ostream os(buf);
647
648 const MemRegion *MR = ArgVal.getAsRegion();
649 if (MR) {
650 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
651 MR = ER->getSuperRegion();
652
653 // Special case for alloca()
654 if (isa<AllocaRegion>(MR))
655 os << "Argument to free() was allocated by alloca(), not malloc()";
656 else {
657 os << "Argument to free() is ";
658 if (SummarizeRegion(os, MR))
659 os << ", which is not memory allocated by malloc()";
660 else
661 os << "not memory allocated by malloc()";
662 }
663 } else {
664 os << "Argument to free() is ";
665 if (SummarizeValue(os, ArgVal))
666 os << ", which is not memory allocated by malloc()";
667 else
668 os << "not memory allocated by malloc()";
669 }
670
Anna Zakse172e8b2011-08-17 23:00:25 +0000671 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000672 R->addRange(range);
673 C.EmitReport(R);
674 }
675}
676
Anna Zaks87cb5be2012-02-22 19:24:52 +0000677ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
678 const CallExpr *CE,
679 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000680 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000681 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000682 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000683 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
684 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000685 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000686 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000687
Ted Kremenek846eabd2010-12-01 21:28:31 +0000688 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000689
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000690 DefinedOrUnknownSVal PtrEQ =
691 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000692
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000693 // Get the size argument. If there is no size arg then give up.
694 const Expr *Arg1 = CE->getArg(1);
695 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000696 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000697
698 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000699 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
700 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000701 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000702 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000703
704 // Compare the size argument to 0.
705 DefinedOrUnknownSVal SizeZero =
706 svalBuilder.evalEQ(state, Arg1Val,
707 svalBuilder.makeIntValWithPtrWidth(0, false));
708
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000709 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
710 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
711 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
712 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
713 // We only assume exceptional states if they are definitely true; if the
714 // state is under-constrained, assume regular realloc behavior.
715 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
716 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
717
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000718 // If the ptr is NULL and the size is not 0, the call is equivalent to
719 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000720 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000721 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000722 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000723 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000724 }
725
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000726 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000727 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000728
Anna Zaks30838b92012-02-13 20:57:07 +0000729 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000730 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000731 SymbolRef FromPtr = arg0Val.getAsSymbol();
732 SVal RetVal = state->getSVal(CE, LCtx);
733 SymbolRef ToPtr = RetVal.getAsSymbol();
734 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000735 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000736
737 // If the size is 0, free the memory.
738 if (SizeIsZero)
739 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000740 // The semantics of the return value are:
741 // If size was equal to 0, either NULL or a pointer suitable to be passed
742 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000743 stateFree = stateFree->set<ReallocPairs>(ToPtr,
744 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000745 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000746 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000747 }
748
749 // Default behavior.
750 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
751 // FIXME: We should copy the content of the original buffer.
752 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
753 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000754 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000755 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000756 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
757 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000758 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000759 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000760 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000761 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000762}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000763
Anna Zaks87cb5be2012-02-22 19:24:52 +0000764ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Ted Kremenek8bef8232012-01-26 21:29:00 +0000765 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000766 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000767 const LocationContext *LCtx = C.getLocationContext();
768 SVal count = state->getSVal(CE->getArg(0), LCtx);
769 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000770 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
771 svalBuilder.getContext().getSizeType());
772 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000773
Anna Zaks87cb5be2012-02-22 19:24:52 +0000774 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000775}
776
Anna Zaksca8e36e2012-02-23 21:38:21 +0000777const Stmt *
778MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
779 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000780 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000781 // Walk the ExplodedGraph backwards and find the first node that referred to
782 // the tracked symbol.
783 const ExplodedNode *AllocNode = N;
784
785 while (N) {
786 if (!N->getState()->get<RegionState>(Sym))
787 break;
Anna Zaks7752d292012-02-27 23:40:55 +0000788 // Allocation node, is the last node in the current context in which the
789 // symbol was tracked.
790 if (N->getLocationContext() == LeakContext)
791 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000792 N = N->pred_empty() ? NULL : *(N->pred_begin());
793 }
794
795 ProgramPoint P = AllocNode->getLocation();
Anna Zaks7752d292012-02-27 23:40:55 +0000796 if (!isa<StmtPoint>(P))
797 return 0;
798
799 return cast<StmtPoint>(P).getStmt();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000800}
801
Anna Zaksda046772012-02-11 21:02:40 +0000802void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
803 CheckerContext &C) const {
804 assert(N);
805 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000806 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000807 // Leaks should not be reported if they are post-dominated by a sink:
808 // (1) Sinks are higher importance bugs.
809 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
810 // with __noreturn functions such as assert() or exit(). We choose not
811 // to report leaks on such paths.
812 BT_Leak->setSuppressOnSink(true);
813 }
814
Anna Zaksca8e36e2012-02-23 21:38:21 +0000815 // Most bug reports are cached at the location where they occurred.
816 // With leaks, we want to unique them by the location where they were
817 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000818 PathDiagnosticLocation LocUsedForUniqueing;
819 if (const Stmt *AllocStmt = getAllocationSite(N, Sym, C))
820 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
821 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000822
Anna Zaksfebdc322012-02-16 22:26:12 +0000823 BugReport *R = new BugReport(*BT_Leak,
Anna Zaksca8e36e2012-02-23 21:38:21 +0000824 "Memory is never released; potential memory leak", N, LocUsedForUniqueing);
Anna Zaksda046772012-02-11 21:02:40 +0000825 R->addVisitor(new MallocBugVisitor(Sym));
826 C.EmitReport(R);
827}
828
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000829void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
830 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000831{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000832 if (!SymReaper.hasDeadSymbols())
833 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000834
Ted Kremenek8bef8232012-01-26 21:29:00 +0000835 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000836 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000837 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000838
Ted Kremenek217470e2011-07-28 23:07:51 +0000839 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000840 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000841 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
842 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000843 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000844 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000845 Errors.push_back(I->first);
846 }
Jordy Rose90760142010-08-18 04:33:47 +0000847 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000848 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000849
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000850 }
851 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000852
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000853 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000854 ReallocMap RP = state->get<ReallocPairs>();
855 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
856 if (SymReaper.isDead(I->first) ||
857 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000858 state = state->remove<ReallocPairs>(I->first);
859 }
860 }
861
Anna Zaksca8e36e2012-02-23 21:38:21 +0000862 // Generate leak node.
863 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
864 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000865
Anna Zaksca8e36e2012-02-23 21:38:21 +0000866 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000867 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000868 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
869 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000870 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000871 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000872 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000873}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000874
Anna Zaksda046772012-02-11 21:02:40 +0000875void MallocChecker::checkEndPath(CheckerContext &C) const {
876 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000877 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000878
Anna Zaksa19581a2012-02-20 22:25:23 +0000879 // If inside inlined call, skip it.
880 if (C.getLocationContext()->getParent() != 0)
881 return;
882
Jordy Rose09cef092010-08-18 04:26:59 +0000883 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000884 RefState RS = I->second;
885 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000886 ExplodedNode *N = C.addTransition(state);
887 if (N)
888 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000889 }
890 }
891}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000892
Anna Zaks91c2a112012-02-08 23:16:56 +0000893bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
894 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000895 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000896 const RefState *RS = state->get<RegionState>(Sym);
897 if (!RS)
898 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000899
Anna Zaks91c2a112012-02-08 23:16:56 +0000900 if (RS->isAllocated()) {
901 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
902 C.addTransition(state);
903 return true;
904 }
905 return false;
906}
907
Anna Zaks66c40402012-02-14 21:55:24 +0000908void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
909 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
910 return;
911
912 // Check use after free, when a freed pointer is passed to a call.
913 ProgramStateRef State = C.getState();
914 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
915 E = CE->arg_end(); I != E; ++I) {
916 const Expr *A = *I;
917 if (A->getType().getTypePtr()->isAnyPointerType()) {
918 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
919 if (!Sym)
920 continue;
921 if (checkUseAfterFree(Sym, C, A))
922 return;
923 }
924 }
925}
926
Anna Zaks91c2a112012-02-08 23:16:56 +0000927void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
928 const Expr *E = S->getRetValue();
929 if (!E)
930 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000931
932 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +0000933 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
934 SymbolRef Sym = RetVal.getAsSymbol();
935 if (!Sym)
936 // If we are returning a field of the allocated struct or an array element,
937 // the callee could still free the memory.
938 // TODO: This logic should be a part of generic symbol escape callback.
939 if (const MemRegion *MR = RetVal.getAsRegion())
940 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
941 if (const SymbolicRegion *BMR =
942 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
943 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000944 if (!Sym)
945 return;
946
Anna Zaks0860cd02012-02-11 21:44:39 +0000947 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +0000948 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +0000949 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000950
Anna Zaksa19581a2012-02-20 22:25:23 +0000951 // If this function body is not inlined, check if the symbol is escaping.
952 if (C.getLocationContext()->getParent() == 0)
953 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000954}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000955
Anna Zaks91c2a112012-02-08 23:16:56 +0000956bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
957 const Stmt *S) const {
958 assert(Sym);
959 const RefState *RS = C.getState()->get<RegionState>(Sym);
960 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000961 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000962 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000963 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +0000964
Anna Zaksfebdc322012-02-16 22:26:12 +0000965 BugReport *R = new BugReport(*BT_UseFree,
966 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +0000967 if (S)
968 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000969 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000970 C.EmitReport(R);
971 return true;
972 }
973 }
974 return false;
975}
976
Zhongxing Xuc8023782010-03-10 04:58:55 +0000977// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000978void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
979 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000980 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000981 if (Sym)
982 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000983}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000984
Anna Zaks4fb54872012-02-11 21:02:35 +0000985//===----------------------------------------------------------------------===//
986// Check various ways a symbol can be invalidated.
987// TODO: This logic (the next 3 functions) is copied/similar to the
988// RetainRelease checker. We might want to factor this out.
989//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000990
Anna Zaks4fb54872012-02-11 21:02:35 +0000991// Stop tracking symbols when a value escapes as a result of checkBind.
992// A value escapes in three possible cases:
993// (1) we are binding to something that is not a memory region.
994// (2) we are binding to a memregion that does not have stack storage
995// (3) we are binding to a memregion with stack storage that the store
996// does not understand.
997void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
998 CheckerContext &C) const {
999 // Are we storing to something that causes the value to "escape"?
1000 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001001 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001002
Anna Zaks4fb54872012-02-11 21:02:35 +00001003 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1004 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001005
Anna Zaks4fb54872012-02-11 21:02:35 +00001006 if (!escapes) {
1007 // To test (3), generate a new state with the binding added. If it is
1008 // the same state, then it escapes (since the store cannot represent
1009 // the binding).
1010 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001011 }
Anna Zaksac593002012-02-16 03:40:57 +00001012 if (!escapes) {
1013 // Case 4: We do not currently model what happens when a symbol is
1014 // assigned to a struct field, so be conservative here and let the symbol
1015 // go. TODO: This could definitely be improved upon.
1016 escapes = !isa<VarRegion>(regionLoc->getRegion());
1017 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001018 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001019
1020 // If our store can represent the binding and we aren't storing to something
1021 // that doesn't have local storage then just return and have the simulation
1022 // state continue as is.
1023 if (!escapes)
1024 return;
1025
1026 // Otherwise, find all symbols referenced by 'val' that we are tracking
1027 // and stop tracking them.
1028 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1029 C.addTransition(state);
1030}
1031
1032// If a symbolic region is assumed to NULL (or another constant), stop tracking
1033// it - assuming that allocation failed on this path.
1034ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1035 SVal Cond,
1036 bool Assumption) const {
1037 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001038 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1039 // If the symbol is assumed to NULL or another constant, this will
1040 // return an APSInt*.
1041 if (state->getSymVal(I.getKey()))
1042 state = state->remove<RegionState>(I.getKey());
1043 }
1044
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001045 // Realloc returns 0 when reallocation fails, which means that we should
1046 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001047 ReallocMap RP = state->get<ReallocPairs>();
1048 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001049 // If the symbol is assumed to NULL or another constant, this will
1050 // return an APSInt*.
1051 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001052 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1053 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001054 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001055 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1056 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001057 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001058 }
1059 state = state->remove<ReallocPairs>(I.getKey());
1060 }
1061 }
1062
Anna Zaks4fb54872012-02-11 21:02:35 +00001063 return state;
1064}
1065
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001066// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001067// conservatively assume it can free/reallocate it's pointer arguments.
1068// (We assume that the pointers cannot escape through calls to system
1069// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001070bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1071 ProgramStateRef State) const {
1072 if (!Call)
1073 return false;
1074
1075 // For now, assume that any C++ call can free memory.
1076 // TODO: If we want to be more optimistic here, we'll need to make sure that
1077 // regions escape to C++ containers. They seem to do that even now, but for
1078 // mysterious reasons.
1079 if (Call->isCXXCall())
1080 return false;
1081
1082 const Decl *D = Call->getDecl();
1083 if (!D)
1084 return false;
1085
Anna Zaks66c40402012-02-14 21:55:24 +00001086 ASTContext &ASTC = State->getStateManager().getContext();
1087
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001088 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001089 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001090 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1091 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001092 }
1093
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001094 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001095 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001096 if (!SM.isInSystemHeader(D->getLocation()))
1097 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001098
Anna Zaks07d39a42012-02-28 01:54:22 +00001099 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001100 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001101 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001102 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001103 if (!II)
1104 return true;
1105 StringRef FName = II->getName();
1106
1107 // White list thread local storage.
1108 if (FName.equals("pthread_setspecific"))
1109 return false;
1110
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001111 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001112 if (FName.endswith("NoCopy")) {
1113 // Look for the deallocator argument. We know that the memory ownership
1114 // is not transfered only if the deallocator argument is
1115 // 'kCFAllocatorNull'.
1116 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1117 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1118 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1119 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1120 if (DeallocatorName == "kCFAllocatorNull")
1121 return true;
1122 }
1123 }
1124 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001125 }
1126
Anna Zaksca23eb22012-02-29 18:42:47 +00001127 // PR12101
1128 // Many CoreFoundation and CoreGraphics might allow a tracked object
1129 // to escape.
1130 if (Call->isCFCGAllowingEscape(FName))
1131 return false;
1132
1133 // Associating streams with malloced buffers. The pointer can escape if
1134 // 'closefn' is specified (and if that function does free memory).
1135 // Currently, we do not inspect the 'closefn' function (PR12101).
1136 if (FName == "funopen")
1137 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1138 return false;
1139
1140 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1141 // these leaks might be intentional when setting the buffer for stdio.
1142 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1143 if (FName == "setbuf" || FName =="setbuffer" ||
1144 FName == "setlinebuf" || FName == "setvbuf") {
1145 if (Call->getNumArgs() >= 1)
1146 if (const DeclRefExpr *Arg =
1147 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1148 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1149 if (D->getCanonicalDecl()->getName().find("std")
1150 != StringRef::npos)
1151 return false;
1152 }
1153
1154 // A bunch of other functions, which take ownership of a pointer (See retain
1155 // release checker). Not all the parameters here are invalidated, but the
1156 // Malloc checker cannot differentiate between them. The right way of doing
1157 // this would be to implement a pointer escapes callback.
1158 if (FName == "CVPixelBufferCreateWithBytes" ||
1159 FName == "CGBitmapContextCreateWithData" ||
1160 FName == "CVPixelBufferCreateWithPlanarBytes") {
1161 return false;
1162 }
1163
Anna Zaks0d389b82012-02-23 01:05:27 +00001164 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001165 // Most system calls, do not free the memory.
1166 return true;
1167
1168 // Process ObjC functions.
1169 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1170 Selector S = ObjCD->getSelector();
1171
1172 // White list the ObjC functions which do free memory.
1173 // - Anything containing 'freeWhenDone' param set to 1.
1174 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1175 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1176 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1177 if (Call->getArgSVal(i).isConstant(1))
1178 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001179 else
1180 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001181 }
1182 }
1183
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001184 // If the first selector ends with NoCopy, assume that the ownership is
1185 // transfered as well.
1186 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1187 if (S.getNameForSlot(0).endswith("NoCopy")) {
1188 return false;
1189 }
1190
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001191 // Otherwise, assume that the function does not free memory.
1192 // Most system calls, do not free the memory.
1193 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001194 }
1195
1196 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001197 return false;
1198
Anna Zaks66c40402012-02-14 21:55:24 +00001199}
1200
Anna Zaks4fb54872012-02-11 21:02:35 +00001201// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1202// escapes, when we are tracking p), do not track the symbol as we cannot reason
1203// about it anymore.
1204ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001205MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001206 const StoreManager::InvalidatedSymbols *invalidated,
1207 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001208 ArrayRef<const MemRegion *> Regions,
1209 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001210 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001211 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001212 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001213
Anna Zaks66c40402012-02-14 21:55:24 +00001214 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001215 // regions (explicit and implicit) escaped.
1216
1217 // Otherwise, whitelist explicit pointers; we still can track them.
1218 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001219 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1220 E = ExplicitRegions.end(); I != E; ++I) {
1221 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1222 WhitelistedSymbols.insert(R->getSymbol());
1223 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001224 }
1225
1226 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1227 E = invalidated->end(); I!=E; ++I) {
1228 SymbolRef sym = *I;
1229 if (WhitelistedSymbols.count(sym))
1230 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001231 // The symbol escaped.
1232 if (const RefState *RS = State->get<RegionState>(sym))
1233 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001234 }
Anna Zaks66c40402012-02-14 21:55:24 +00001235 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001236}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001237
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001238PathDiagnosticPiece *
1239MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1240 const ExplodedNode *PrevN,
1241 BugReporterContext &BRC,
1242 BugReport &BR) {
1243 const RefState *RS = N->getState()->get<RegionState>(Sym);
1244 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1245 if (!RS && !RSPrev)
1246 return 0;
1247
Anna Zaksfe571602012-02-16 22:26:07 +00001248 const Stmt *S = 0;
1249 const char *Msg = 0;
1250
1251 // Retrieve the associated statement.
1252 ProgramPoint ProgLoc = N->getLocation();
1253 if (isa<StmtPoint>(ProgLoc))
1254 S = cast<StmtPoint>(ProgLoc).getStmt();
1255 // If an assumption was made on a branch, it should be caught
1256 // here by looking at the state transition.
1257 if (isa<BlockEdge>(ProgLoc)) {
1258 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1259 S = srcBlk->getTerminator();
1260 }
1261 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001262 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001263
1264 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001265 if (Mode == Normal) {
1266 if (isAllocated(RS, RSPrev, S))
1267 Msg = "Memory is allocated";
1268 else if (isReleased(RS, RSPrev, S))
1269 Msg = "Memory is released";
1270 else if (isReallocFailedCheck(RS, RSPrev, S)) {
1271 Mode = ReallocationFailed;
1272 Msg = "Reallocation failed";
1273 }
1274
1275 // We are in a special mode if a reallocation failed later in the path.
1276 } else if (Mode == ReallocationFailed) {
1277 // Generate a special diagnostic for the first realloc we find.
1278 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1279 return 0;
1280
1281 // Check that the name of the function is realloc.
1282 const CallExpr *CE = dyn_cast<CallExpr>(S);
1283 if (!CE)
1284 return 0;
1285 const FunctionDecl *funDecl = CE->getDirectCallee();
1286 if (!funDecl)
1287 return 0;
1288 StringRef FunName = funDecl->getName();
1289 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1290 return 0;
1291 Msg = "Attempt to reallocate memory";
1292 Mode = Normal;
1293 }
1294
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001295 if (!Msg)
1296 return 0;
1297
1298 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001299 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001300 N->getLocationContext());
1301 return new PathDiagnosticEventPiece(Pos, Msg);
1302}
1303
1304
Anna Zaks231361a2012-02-08 23:16:52 +00001305#define REGISTER_CHECKER(name) \
1306void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001307 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001308 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001309}
Anna Zaks231361a2012-02-08 23:16:52 +00001310
1311REGISTER_CHECKER(MallocPessimistic)
1312REGISTER_CHECKER(MallocOptimistic)