blob: 3f0d3d456e347f54011722ff73146cebb8cdf71c [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
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000102public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000103 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000104 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000105
106 /// In pessimistic mode, the checker assumes that it does not know which
107 /// functions might free the memory.
108 struct ChecksFilter {
109 DefaultBool CMallocPessimistic;
110 DefaultBool CMallocOptimistic;
111 };
112
113 ChecksFilter Filter;
114
Anna Zaks66c40402012-02-14 21:55:24 +0000115 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000116 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000117 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000118 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000119 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000120 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000121 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000122 void checkLocation(SVal l, bool isLoad, const Stmt *S,
123 CheckerContext &C) const;
124 void checkBind(SVal location, SVal val, const Stmt*S,
125 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000126 ProgramStateRef
127 checkRegionChanges(ProgramStateRef state,
128 const StoreManager::InvalidatedSymbols *invalidated,
129 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000130 ArrayRef<const MemRegion *> Regions,
131 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000132 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
133 return true;
134 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000135
Zhongxing Xu7b760962009-11-13 07:25:27 +0000136private:
Anna Zaks66c40402012-02-14 21:55:24 +0000137 void initIdentifierInfo(ASTContext &C) const;
138
139 /// Check if this is one of the functions which can allocate/reallocate memory
140 /// pointed to by one of its arguments.
141 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
142
Anna Zaks87cb5be2012-02-22 19:24:52 +0000143 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
144 const CallExpr *CE,
145 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000146 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000147 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000148 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000149 return MallocMemAux(C, CE,
150 state->getSVal(SizeEx, C.getLocationContext()),
151 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000152 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000153
Ted Kremenek8bef8232012-01-26 21:29:00 +0000154 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000155 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000156 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000157
Anna Zaks87cb5be2012-02-22 19:24:52 +0000158 /// Update the RefState to reflect the new memory allocation.
159 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
160 const CallExpr *CE,
161 ProgramStateRef state);
162
163 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
164 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000165 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
166 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000167 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000168
Anna Zaks87cb5be2012-02-22 19:24:52 +0000169 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
170 bool FreesMemOnFailure) const;
171 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000172
Anna Zaks91c2a112012-02-08 23:16:56 +0000173 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
174 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
175 const Stmt *S = 0) const;
176
Anna Zaks66c40402012-02-14 21:55:24 +0000177 /// Check if the function is not known to us. So, for example, we could
178 /// conservatively assume it can free/reallocate it's pointer arguments.
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000179 bool doesNotFreeMemory(const CallOrObjCMessage *Call,
180 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000181
Ted Kremenek9c378f72011-08-12 23:37:29 +0000182 static bool SummarizeValue(raw_ostream &os, SVal V);
183 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000184 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000185
Anna Zaksca8e36e2012-02-23 21:38:21 +0000186 /// Find the location of the allocation for Sym on the path leading to the
187 /// exploded node N.
188 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
189 CheckerContext &C) const;
190
Anna Zaksda046772012-02-11 21:02:40 +0000191 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
192
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000193 /// The bug visitor which allows us to print extra diagnostics along the
194 /// BugReport path. For example, showing the allocation site of the leaked
195 /// region.
196 class MallocBugVisitor : public BugReporterVisitor {
197 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000198 enum NotificationMode {
199 Normal,
200 Complete,
201 ReallocationFailed
202 };
203
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000204 // The allocated region symbol tracked by the main analysis.
205 SymbolRef Sym;
Anna Zaksfe571602012-02-16 22:26:07 +0000206 NotificationMode Mode;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000207
208 public:
Anna Zaksfe571602012-02-16 22:26:07 +0000209 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000210 virtual ~MallocBugVisitor() {}
211
212 void Profile(llvm::FoldingSetNodeID &ID) const {
213 static int X = 0;
214 ID.AddPointer(&X);
215 ID.AddPointer(Sym);
216 }
217
Anna Zaksfe571602012-02-16 22:26:07 +0000218 inline bool isAllocated(const RefState *S, const RefState *SPrev,
219 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000220 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000221 return (Stmt && isa<CallExpr>(Stmt) &&
222 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000223 }
224
Anna Zaksfe571602012-02-16 22:26:07 +0000225 inline bool isReleased(const RefState *S, const RefState *SPrev,
226 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000227 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000228 return (Stmt && isa<CallExpr>(Stmt) &&
229 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
230 }
231
232 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
233 const Stmt *Stmt) {
234 // If the expression is not a call, and the state change is
235 // released -> allocated, it must be the realloc return value
236 // check. If we have to handle more cases here, it might be cleaner just
237 // to track this extra bit in the state itself.
238 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
239 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000240 }
241
242 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
243 const ExplodedNode *PrevN,
244 BugReporterContext &BRC,
245 BugReport &BR);
246 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000247};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000248} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000249
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000250typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000251typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000252class RegionState {};
253class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000254namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000255namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000256 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000257 struct ProgramStateTrait<RegionState>
258 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000259 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000260 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000261
262 template <>
263 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000264 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000265 static void *GDMIndex() { static int x; return &x; }
266 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000267}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000268}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000269
Anna Zaks4fb54872012-02-11 21:02:35 +0000270namespace {
271class StopTrackingCallback : public SymbolVisitor {
272 ProgramStateRef state;
273public:
274 StopTrackingCallback(ProgramStateRef st) : state(st) {}
275 ProgramStateRef getState() const { return state; }
276
277 bool VisitSymbol(SymbolRef sym) {
278 state = state->remove<RegionState>(sym);
279 return true;
280 }
281};
282} // end anonymous namespace
283
Anna Zaks66c40402012-02-14 21:55:24 +0000284void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000285 if (!II_malloc)
286 II_malloc = &Ctx.Idents.get("malloc");
287 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000288 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000289 if (!II_realloc)
290 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000291 if (!II_reallocf)
292 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000293 if (!II_calloc)
294 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000295 if (!II_valloc)
296 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaks60a1fa42012-02-22 03:14:20 +0000297 if (!II_strdup)
298 II_strdup = &Ctx.Idents.get("strdup");
299 if (!II_strndup)
300 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000301}
302
Anna Zaks66c40402012-02-14 21:55:24 +0000303bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000304 if (!FD)
305 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000306 IdentifierInfo *FunI = FD->getIdentifier();
307 if (!FunI)
308 return false;
309
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000310 initIdentifierInfo(C);
311
Anna Zaks40add292012-02-15 00:11:25 +0000312 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000313 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
314 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000315 return true;
316
317 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
318 FD->specific_attr_begin<OwnershipAttr>() !=
319 FD->specific_attr_end<OwnershipAttr>())
320 return true;
321
322
323 return false;
324}
325
Anna Zaksb319e022012-02-08 20:13:28 +0000326void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
327 const FunctionDecl *FD = C.getCalleeDecl(CE);
328 if (!FD)
329 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000330
Anna Zaksb16ce452012-02-15 00:11:22 +0000331 initIdentifierInfo(C.getASTContext());
332 IdentifierInfo *FunI = FD->getIdentifier();
333 if (!FunI)
334 return;
335
Anna Zaks87cb5be2012-02-22 19:24:52 +0000336 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000337 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000338 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000339 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000340 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000341 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000342 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000343 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000344 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000345 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000346 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000347 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000348 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000349 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000350 State = MallocUpdateRefState(C, CE, State);
351 } else if (Filter.CMallocOptimistic) {
352 // Check all the attributes, if there are any.
353 // There can be multiple of these attributes.
354 if (FD->hasAttrs())
355 for (specific_attr_iterator<OwnershipAttr>
356 i = FD->specific_attr_begin<OwnershipAttr>(),
357 e = FD->specific_attr_end<OwnershipAttr>();
358 i != e; ++i) {
359 switch ((*i)->getOwnKind()) {
360 case OwnershipAttr::Returns:
361 State = MallocMemReturnsAttr(C, CE, *i);
362 break;
363 case OwnershipAttr::Takes:
364 case OwnershipAttr::Holds:
365 State = FreeMemAttr(C, CE, *i);
366 break;
367 }
368 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000369 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000370 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000371}
372
Anna Zaks87cb5be2012-02-22 19:24:52 +0000373ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
374 const CallExpr *CE,
375 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000376 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000377 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000378
Sean Huntcf807c42010-08-18 23:23:40 +0000379 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000380 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000381 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000382 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000383 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000384}
385
Anna Zaksb319e022012-02-08 20:13:28 +0000386ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000387 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000388 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000389 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000390 // Get the return value.
391 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000392
Anna Zaksb16ce452012-02-15 00:11:22 +0000393 // We expect the malloc functions to return a pointer.
394 if (!isa<Loc>(retVal))
395 return 0;
396
Jordy Rose32f26562010-07-04 00:00:41 +0000397 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000398 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000399
Jordy Rose32f26562010-07-04 00:00:41 +0000400 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000401 const SymbolicRegion *R =
402 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000403 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000404 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000405 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000406 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000407 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
408 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
409 DefinedOrUnknownSVal extentMatchesSize =
410 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000411
Anna Zaks60a1fa42012-02-22 03:14:20 +0000412 state = state->assume(extentMatchesSize, true);
413 assert(state);
414 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000415
Anna Zaks87cb5be2012-02-22 19:24:52 +0000416 return MallocUpdateRefState(C, CE, state);
417}
418
419ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
420 const CallExpr *CE,
421 ProgramStateRef state) {
422 // Get the return value.
423 SVal retVal = state->getSVal(CE, C.getLocationContext());
424
425 // We expect the malloc functions to return a pointer.
426 if (!isa<Loc>(retVal))
427 return 0;
428
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000429 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000430 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000431
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000432 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000433 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000434
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000435}
436
Anna Zaks87cb5be2012-02-22 19:24:52 +0000437ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
438 const CallExpr *CE,
439 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000440 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000441 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000442
Anna Zaksb3d72752012-03-01 22:06:06 +0000443 ProgramStateRef State = C.getState();
444
Sean Huntcf807c42010-08-18 23:23:40 +0000445 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
446 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000447 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
448 Att->getOwnKind() == OwnershipAttr::Holds);
449 if (StateI)
450 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000451 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000452 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000453}
454
Ted Kremenek8bef8232012-01-26 21:29:00 +0000455ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000456 const CallExpr *CE,
457 ProgramStateRef state,
458 unsigned Num,
459 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000460 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000461 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000462 if (!isa<DefinedOrUnknownSVal>(ArgVal))
463 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000464 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
465
466 // Check for null dereferences.
467 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000468 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000469
Anna Zaksb276bd92012-02-14 00:26:13 +0000470 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000471 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000472 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000473 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000474 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000475
Jordy Rose43859f62010-06-07 19:32:37 +0000476 // Unknown values could easily be okay
477 // Undefined values are handled elsewhere
478 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000479 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000480
Jordy Rose43859f62010-06-07 19:32:37 +0000481 const MemRegion *R = ArgVal.getAsRegion();
482
483 // Nonlocs can't be freed, of course.
484 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
485 if (!R) {
486 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000487 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000488 }
489
490 R = R->StripCasts();
491
492 // Blocks might show up as heap data, but should not be free()d
493 if (isa<BlockDataRegion>(R)) {
494 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000495 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000496 }
497
498 const MemSpaceRegion *MS = R->getMemorySpace();
499
500 // Parameters, locals, statics, and globals shouldn't be freed.
501 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
502 // FIXME: at the time this code was written, malloc() regions were
503 // represented by conjured symbols, which are all in UnknownSpaceRegion.
504 // This means that there isn't actually anything from HeapSpaceRegion
505 // that should be freed, even though we allow it here.
506 // Of course, free() can work on memory allocated outside the current
507 // function, so UnknownSpaceRegion is always a possibility.
508 // False negatives are better than false positives.
509
510 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000511 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000512 }
513
514 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
515 // Various cases could lead to non-symbol values here.
516 // For now, ignore them.
517 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000518 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000519
520 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000521 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000522
523 // If the symbol has not been tracked, return. This is possible when free() is
524 // called on a pointer that does not get its pointee directly from malloc().
525 // Full support of this requires inter-procedural analysis.
526 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000527 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000528
529 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000530 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000531 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000532 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000533 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000534 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000535 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000536 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000537 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000538 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000539 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000540 C.EmitReport(R);
541 }
Anna Zaksb319e022012-02-08 20:13:28 +0000542 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000543 }
544
545 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000546 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000547 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
548 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000549}
550
Ted Kremenek9c378f72011-08-12 23:37:29 +0000551bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000552 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
553 os << "an integer (" << IntVal->getValue() << ")";
554 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
555 os << "a constant address (" << ConstAddr->getValue() << ")";
556 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000557 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000558 else
559 return false;
560
561 return true;
562}
563
Ted Kremenek9c378f72011-08-12 23:37:29 +0000564bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000565 const MemRegion *MR) {
566 switch (MR->getKind()) {
567 case MemRegion::FunctionTextRegionKind: {
568 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
569 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000570 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000571 else
572 os << "the address of a function";
573 return true;
574 }
575 case MemRegion::BlockTextRegionKind:
576 os << "block text";
577 return true;
578 case MemRegion::BlockDataRegionKind:
579 // FIXME: where the block came from?
580 os << "a block";
581 return true;
582 default: {
583 const MemSpaceRegion *MS = MR->getMemorySpace();
584
Anna Zakseb31a762012-01-04 23:54:01 +0000585 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000586 const VarRegion *VR = dyn_cast<VarRegion>(MR);
587 const VarDecl *VD;
588 if (VR)
589 VD = VR->getDecl();
590 else
591 VD = NULL;
592
593 if (VD)
594 os << "the address of the local variable '" << VD->getName() << "'";
595 else
596 os << "the address of a local stack variable";
597 return true;
598 }
Anna Zakseb31a762012-01-04 23:54:01 +0000599
600 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000601 const VarRegion *VR = dyn_cast<VarRegion>(MR);
602 const VarDecl *VD;
603 if (VR)
604 VD = VR->getDecl();
605 else
606 VD = NULL;
607
608 if (VD)
609 os << "the address of the parameter '" << VD->getName() << "'";
610 else
611 os << "the address of a parameter";
612 return true;
613 }
Anna Zakseb31a762012-01-04 23:54:01 +0000614
615 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000616 const VarRegion *VR = dyn_cast<VarRegion>(MR);
617 const VarDecl *VD;
618 if (VR)
619 VD = VR->getDecl();
620 else
621 VD = NULL;
622
623 if (VD) {
624 if (VD->isStaticLocal())
625 os << "the address of the static variable '" << VD->getName() << "'";
626 else
627 os << "the address of the global variable '" << VD->getName() << "'";
628 } else
629 os << "the address of a global variable";
630 return true;
631 }
Anna Zakseb31a762012-01-04 23:54:01 +0000632
633 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000634 }
635 }
636}
637
638void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000639 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000640 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000641 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000642 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000643
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000644 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000645 llvm::raw_svector_ostream os(buf);
646
647 const MemRegion *MR = ArgVal.getAsRegion();
648 if (MR) {
649 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
650 MR = ER->getSuperRegion();
651
652 // Special case for alloca()
653 if (isa<AllocaRegion>(MR))
654 os << "Argument to free() was allocated by alloca(), not malloc()";
655 else {
656 os << "Argument to free() is ";
657 if (SummarizeRegion(os, MR))
658 os << ", which is not memory allocated by malloc()";
659 else
660 os << "not memory allocated by malloc()";
661 }
662 } else {
663 os << "Argument to free() is ";
664 if (SummarizeValue(os, ArgVal))
665 os << ", which is not memory allocated by malloc()";
666 else
667 os << "not memory allocated by malloc()";
668 }
669
Anna Zakse172e8b2011-08-17 23:00:25 +0000670 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000671 R->markInteresting(MR);
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);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000825 R->markInteresting(Sym);
Anna Zaksda046772012-02-11 21:02:40 +0000826 R->addVisitor(new MallocBugVisitor(Sym));
827 C.EmitReport(R);
828}
829
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000830void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
831 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000832{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000833 if (!SymReaper.hasDeadSymbols())
834 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000835
Ted Kremenek8bef8232012-01-26 21:29:00 +0000836 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000837 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000838 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000839
Ted Kremenek217470e2011-07-28 23:07:51 +0000840 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000841 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000842 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
843 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000844 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000845 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000846 Errors.push_back(I->first);
847 }
Jordy Rose90760142010-08-18 04:33:47 +0000848 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000849 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000850
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000851 }
852 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000853
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000854 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000855 ReallocMap RP = state->get<ReallocPairs>();
856 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
857 if (SymReaper.isDead(I->first) ||
858 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000859 state = state->remove<ReallocPairs>(I->first);
860 }
861 }
862
Anna Zaksca8e36e2012-02-23 21:38:21 +0000863 // Generate leak node.
864 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
865 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000866
Anna Zaksca8e36e2012-02-23 21:38:21 +0000867 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000868 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000869 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
870 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000871 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000872 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000873 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000874}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000875
Anna Zaksda046772012-02-11 21:02:40 +0000876void MallocChecker::checkEndPath(CheckerContext &C) const {
877 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000878 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000879
Anna Zaksa19581a2012-02-20 22:25:23 +0000880 // If inside inlined call, skip it.
881 if (C.getLocationContext()->getParent() != 0)
882 return;
883
Jordy Rose09cef092010-08-18 04:26:59 +0000884 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000885 RefState RS = I->second;
886 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000887 ExplodedNode *N = C.addTransition(state);
888 if (N)
889 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000890 }
891 }
892}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000893
Anna Zaks91c2a112012-02-08 23:16:56 +0000894bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
895 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000896 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000897 const RefState *RS = state->get<RegionState>(Sym);
898 if (!RS)
899 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000900
Anna Zaks91c2a112012-02-08 23:16:56 +0000901 if (RS->isAllocated()) {
902 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
903 C.addTransition(state);
904 return true;
905 }
906 return false;
907}
908
Anna Zaks66c40402012-02-14 21:55:24 +0000909void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
910 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
911 return;
912
913 // Check use after free, when a freed pointer is passed to a call.
914 ProgramStateRef State = C.getState();
915 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
916 E = CE->arg_end(); I != E; ++I) {
917 const Expr *A = *I;
918 if (A->getType().getTypePtr()->isAnyPointerType()) {
919 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
920 if (!Sym)
921 continue;
922 if (checkUseAfterFree(Sym, C, A))
923 return;
924 }
925 }
926}
927
Anna Zaks91c2a112012-02-08 23:16:56 +0000928void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
929 const Expr *E = S->getRetValue();
930 if (!E)
931 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000932
933 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +0000934 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
935 SymbolRef Sym = RetVal.getAsSymbol();
936 if (!Sym)
937 // If we are returning a field of the allocated struct or an array element,
938 // the callee could still free the memory.
939 // TODO: This logic should be a part of generic symbol escape callback.
940 if (const MemRegion *MR = RetVal.getAsRegion())
941 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
942 if (const SymbolicRegion *BMR =
943 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
944 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000945 if (!Sym)
946 return;
947
Anna Zaks0860cd02012-02-11 21:44:39 +0000948 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +0000949 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +0000950 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000951
Anna Zaksa19581a2012-02-20 22:25:23 +0000952 // If this function body is not inlined, check if the symbol is escaping.
953 if (C.getLocationContext()->getParent() == 0)
954 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000955}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000956
Anna Zaks91c2a112012-02-08 23:16:56 +0000957bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
958 const Stmt *S) const {
959 assert(Sym);
960 const RefState *RS = C.getState()->get<RegionState>(Sym);
961 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000962 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000963 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000964 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +0000965
Anna Zaksfebdc322012-02-16 22:26:12 +0000966 BugReport *R = new BugReport(*BT_UseFree,
967 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +0000968 if (S)
969 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000970 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000971 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000972 C.EmitReport(R);
973 return true;
974 }
975 }
976 return false;
977}
978
Zhongxing Xuc8023782010-03-10 04:58:55 +0000979// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000980void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
981 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000982 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000983 if (Sym)
984 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000985}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000986
Anna Zaks4fb54872012-02-11 21:02:35 +0000987//===----------------------------------------------------------------------===//
988// Check various ways a symbol can be invalidated.
989// TODO: This logic (the next 3 functions) is copied/similar to the
990// RetainRelease checker. We might want to factor this out.
991//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000992
Anna Zaks4fb54872012-02-11 21:02:35 +0000993// Stop tracking symbols when a value escapes as a result of checkBind.
994// A value escapes in three possible cases:
995// (1) we are binding to something that is not a memory region.
996// (2) we are binding to a memregion that does not have stack storage
997// (3) we are binding to a memregion with stack storage that the store
998// does not understand.
999void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1000 CheckerContext &C) const {
1001 // Are we storing to something that causes the value to "escape"?
1002 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001003 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001004
Anna Zaks4fb54872012-02-11 21:02:35 +00001005 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1006 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001007
Anna Zaks4fb54872012-02-11 21:02:35 +00001008 if (!escapes) {
1009 // To test (3), generate a new state with the binding added. If it is
1010 // the same state, then it escapes (since the store cannot represent
1011 // the binding).
1012 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001013 }
Anna Zaksac593002012-02-16 03:40:57 +00001014 if (!escapes) {
1015 // Case 4: We do not currently model what happens when a symbol is
1016 // assigned to a struct field, so be conservative here and let the symbol
1017 // go. TODO: This could definitely be improved upon.
1018 escapes = !isa<VarRegion>(regionLoc->getRegion());
1019 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001020 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001021
1022 // If our store can represent the binding and we aren't storing to something
1023 // that doesn't have local storage then just return and have the simulation
1024 // state continue as is.
1025 if (!escapes)
1026 return;
1027
1028 // Otherwise, find all symbols referenced by 'val' that we are tracking
1029 // and stop tracking them.
1030 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1031 C.addTransition(state);
1032}
1033
1034// If a symbolic region is assumed to NULL (or another constant), stop tracking
1035// it - assuming that allocation failed on this path.
1036ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1037 SVal Cond,
1038 bool Assumption) const {
1039 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001040 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1041 // If the symbol is assumed to NULL or another constant, this will
1042 // return an APSInt*.
1043 if (state->getSymVal(I.getKey()))
1044 state = state->remove<RegionState>(I.getKey());
1045 }
1046
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001047 // Realloc returns 0 when reallocation fails, which means that we should
1048 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001049 ReallocMap RP = state->get<ReallocPairs>();
1050 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001051 // If the symbol is assumed to NULL or another constant, this will
1052 // return an APSInt*.
1053 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001054 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1055 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001056 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001057 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1058 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001059 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001060 }
1061 state = state->remove<ReallocPairs>(I.getKey());
1062 }
1063 }
1064
Anna Zaks4fb54872012-02-11 21:02:35 +00001065 return state;
1066}
1067
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001068// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001069// conservatively assume it can free/reallocate it's pointer arguments.
1070// (We assume that the pointers cannot escape through calls to system
1071// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001072bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1073 ProgramStateRef State) const {
1074 if (!Call)
1075 return false;
1076
1077 // For now, assume that any C++ call can free memory.
1078 // TODO: If we want to be more optimistic here, we'll need to make sure that
1079 // regions escape to C++ containers. They seem to do that even now, but for
1080 // mysterious reasons.
1081 if (Call->isCXXCall())
1082 return false;
1083
1084 const Decl *D = Call->getDecl();
1085 if (!D)
1086 return false;
1087
Anna Zaks66c40402012-02-14 21:55:24 +00001088 ASTContext &ASTC = State->getStateManager().getContext();
1089
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001090 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001091 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001092 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1093 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001094 }
1095
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001096 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001097 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001098 if (!SM.isInSystemHeader(D->getLocation()))
1099 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001100
Anna Zaks07d39a42012-02-28 01:54:22 +00001101 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001102 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001103 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001104 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001105 if (!II)
1106 return true;
1107 StringRef FName = II->getName();
1108
1109 // White list thread local storage.
1110 if (FName.equals("pthread_setspecific"))
1111 return false;
1112
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001113 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001114 if (FName.endswith("NoCopy")) {
1115 // Look for the deallocator argument. We know that the memory ownership
1116 // is not transfered only if the deallocator argument is
1117 // 'kCFAllocatorNull'.
1118 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1119 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1120 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1121 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1122 if (DeallocatorName == "kCFAllocatorNull")
1123 return true;
1124 }
1125 }
1126 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001127 }
1128
Anna Zaksca23eb22012-02-29 18:42:47 +00001129 // PR12101
1130 // Many CoreFoundation and CoreGraphics might allow a tracked object
1131 // to escape.
1132 if (Call->isCFCGAllowingEscape(FName))
1133 return false;
1134
1135 // Associating streams with malloced buffers. The pointer can escape if
1136 // 'closefn' is specified (and if that function does free memory).
1137 // Currently, we do not inspect the 'closefn' function (PR12101).
1138 if (FName == "funopen")
1139 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1140 return false;
1141
1142 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1143 // these leaks might be intentional when setting the buffer for stdio.
1144 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1145 if (FName == "setbuf" || FName =="setbuffer" ||
1146 FName == "setlinebuf" || FName == "setvbuf") {
1147 if (Call->getNumArgs() >= 1)
1148 if (const DeclRefExpr *Arg =
1149 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1150 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1151 if (D->getCanonicalDecl()->getName().find("std")
1152 != StringRef::npos)
1153 return false;
1154 }
1155
1156 // A bunch of other functions, which take ownership of a pointer (See retain
1157 // release checker). Not all the parameters here are invalidated, but the
1158 // Malloc checker cannot differentiate between them. The right way of doing
1159 // this would be to implement a pointer escapes callback.
1160 if (FName == "CVPixelBufferCreateWithBytes" ||
1161 FName == "CGBitmapContextCreateWithData" ||
1162 FName == "CVPixelBufferCreateWithPlanarBytes") {
1163 return false;
1164 }
1165
Anna Zaks0d389b82012-02-23 01:05:27 +00001166 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001167 // Most system calls, do not free the memory.
1168 return true;
1169
1170 // Process ObjC functions.
1171 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1172 Selector S = ObjCD->getSelector();
1173
1174 // White list the ObjC functions which do free memory.
1175 // - Anything containing 'freeWhenDone' param set to 1.
1176 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1177 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1178 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1179 if (Call->getArgSVal(i).isConstant(1))
1180 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001181 else
1182 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001183 }
1184 }
1185
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001186 // If the first selector ends with NoCopy, assume that the ownership is
1187 // transfered as well.
1188 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1189 if (S.getNameForSlot(0).endswith("NoCopy")) {
1190 return false;
1191 }
1192
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001193 // Otherwise, assume that the function does not free memory.
1194 // Most system calls, do not free the memory.
1195 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001196 }
1197
1198 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001199 return false;
1200
Anna Zaks66c40402012-02-14 21:55:24 +00001201}
1202
Anna Zaks4fb54872012-02-11 21:02:35 +00001203// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1204// escapes, when we are tracking p), do not track the symbol as we cannot reason
1205// about it anymore.
1206ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001207MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001208 const StoreManager::InvalidatedSymbols *invalidated,
1209 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001210 ArrayRef<const MemRegion *> Regions,
1211 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001212 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001213 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001214 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001215
Anna Zaks66c40402012-02-14 21:55:24 +00001216 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001217 // regions (explicit and implicit) escaped.
1218
1219 // Otherwise, whitelist explicit pointers; we still can track them.
1220 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001221 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1222 E = ExplicitRegions.end(); I != E; ++I) {
1223 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1224 WhitelistedSymbols.insert(R->getSymbol());
1225 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001226 }
1227
1228 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1229 E = invalidated->end(); I!=E; ++I) {
1230 SymbolRef sym = *I;
1231 if (WhitelistedSymbols.count(sym))
1232 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001233 // The symbol escaped.
1234 if (const RefState *RS = State->get<RegionState>(sym))
1235 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001236 }
Anna Zaks66c40402012-02-14 21:55:24 +00001237 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001238}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001239
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001240PathDiagnosticPiece *
1241MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1242 const ExplodedNode *PrevN,
1243 BugReporterContext &BRC,
1244 BugReport &BR) {
1245 const RefState *RS = N->getState()->get<RegionState>(Sym);
1246 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1247 if (!RS && !RSPrev)
1248 return 0;
1249
Anna Zaksfe571602012-02-16 22:26:07 +00001250 const Stmt *S = 0;
1251 const char *Msg = 0;
1252
1253 // Retrieve the associated statement.
1254 ProgramPoint ProgLoc = N->getLocation();
1255 if (isa<StmtPoint>(ProgLoc))
1256 S = cast<StmtPoint>(ProgLoc).getStmt();
1257 // If an assumption was made on a branch, it should be caught
1258 // here by looking at the state transition.
1259 if (isa<BlockEdge>(ProgLoc)) {
1260 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1261 S = srcBlk->getTerminator();
1262 }
1263 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001264 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001265
1266 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001267 if (Mode == Normal) {
1268 if (isAllocated(RS, RSPrev, S))
1269 Msg = "Memory is allocated";
1270 else if (isReleased(RS, RSPrev, S))
1271 Msg = "Memory is released";
1272 else if (isReallocFailedCheck(RS, RSPrev, S)) {
1273 Mode = ReallocationFailed;
1274 Msg = "Reallocation failed";
1275 }
1276
1277 // We are in a special mode if a reallocation failed later in the path.
1278 } else if (Mode == ReallocationFailed) {
1279 // Generate a special diagnostic for the first realloc we find.
1280 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1281 return 0;
1282
1283 // Check that the name of the function is realloc.
1284 const CallExpr *CE = dyn_cast<CallExpr>(S);
1285 if (!CE)
1286 return 0;
1287 const FunctionDecl *funDecl = CE->getDirectCallee();
1288 if (!funDecl)
1289 return 0;
1290 StringRef FunName = funDecl->getName();
1291 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1292 return 0;
1293 Msg = "Attempt to reallocate memory";
1294 Mode = Normal;
1295 }
1296
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001297 if (!Msg)
1298 return 0;
1299
1300 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001301 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001302 N->getLocationContext());
1303 return new PathDiagnosticEventPiece(Pos, Msg);
1304}
1305
1306
Anna Zaks231361a2012-02-08 23:16:52 +00001307#define REGISTER_CHECKER(name) \
1308void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001309 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001310 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001311}
Anna Zaks231361a2012-02-08 23:16:52 +00001312
1313REGISTER_CHECKER(MallocPessimistic)
1314REGISTER_CHECKER(MallocOptimistic)