blob: 007eba19ab09eee245d742e4f4d618e4c6baa370 [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; }
Chris Lattnerfae96222010-09-03 04:34:38 +000045 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000046 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000047 //bool isEscaped() const { return K == Escaped; }
48 //bool isRelinquished() const { return K == Relinquished; }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000049 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000050
51 bool operator==(const RefState &X) const {
52 return K == X.K && S == X.S;
53 }
54
Zhongxing Xub94b81a2009-12-31 06:13:07 +000055 static RefState getAllocateUnchecked(const Stmt *s) {
56 return RefState(AllocateUnchecked, s);
57 }
58 static RefState getAllocateFailed() {
59 return RefState(AllocateFailed, 0);
60 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000061 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
62 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000063 static RefState getRelinquished(const Stmt *s) {
64 return RefState(Relinquished, s);
65 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000066
67 void Profile(llvm::FoldingSetNodeID &ID) const {
68 ID.AddInteger(K);
69 ID.AddPointer(S);
70 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000071};
72
Anna Zaks40add292012-02-15 00:11:25 +000073struct ReallocPair {
74 SymbolRef ReallocatedSym;
75 bool IsFreeOnFailure;
76 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
77 void Profile(llvm::FoldingSetNodeID &ID) const {
78 ID.AddInteger(IsFreeOnFailure);
79 ID.AddPointer(ReallocatedSym);
80 }
81 bool operator==(const ReallocPair &X) const {
82 return ReallocatedSym == X.ReallocatedSym &&
83 IsFreeOnFailure == X.IsFreeOnFailure;
84 }
85};
86
Anna Zaksb319e022012-02-08 20:13:28 +000087class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000088 check::EndPath,
89 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000090 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000091 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000092 check::Location,
93 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000094 eval::Assume,
95 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000096{
Anna Zaksfebdc322012-02-16 22:26:12 +000097 mutable OwningPtr<BugType> BT_DoubleFree;
98 mutable OwningPtr<BugType> BT_Leak;
99 mutable OwningPtr<BugType> BT_UseFree;
100 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000101 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000102 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
103
104 static const unsigned InvalidArgIndex = UINT_MAX;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000105
106public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000107 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000108 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000109
110 /// In pessimistic mode, the checker assumes that it does not know which
111 /// functions might free the memory.
112 struct ChecksFilter {
113 DefaultBool CMallocPessimistic;
114 DefaultBool CMallocOptimistic;
115 };
116
117 ChecksFilter Filter;
118
Anna Zaks66c40402012-02-14 21:55:24 +0000119 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000120 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000121 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000122 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000123 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000124 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000125 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000126 void checkLocation(SVal l, bool isLoad, const Stmt *S,
127 CheckerContext &C) const;
128 void checkBind(SVal location, SVal val, const Stmt*S,
129 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000130 ProgramStateRef
131 checkRegionChanges(ProgramStateRef state,
132 const StoreManager::InvalidatedSymbols *invalidated,
133 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000134 ArrayRef<const MemRegion *> Regions,
135 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000136 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
137 return true;
138 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000139
Zhongxing Xu7b760962009-11-13 07:25:27 +0000140private:
Anna Zaks66c40402012-02-14 21:55:24 +0000141 void initIdentifierInfo(ASTContext &C) const;
142
143 /// Check if this is one of the functions which can allocate/reallocate memory
144 /// pointed to by one of its arguments.
145 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
146
Anna Zaks87cb5be2012-02-22 19:24:52 +0000147 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
148 const CallExpr *CE,
149 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000150 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000151 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000152 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000153 return MallocMemAux(C, CE,
154 state->getSVal(SizeEx, C.getLocationContext()),
155 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000156 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000157
Ted Kremenek8bef8232012-01-26 21:29:00 +0000158 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000159 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000160 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000161
Anna Zaks87cb5be2012-02-22 19:24:52 +0000162 /// Update the RefState to reflect the new memory allocation.
163 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
164 const CallExpr *CE,
165 ProgramStateRef state);
166
167 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
168 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000169 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
170 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000171 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000172
Anna Zaks87cb5be2012-02-22 19:24:52 +0000173 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
174 bool FreesMemOnFailure) const;
175 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000176
Anna Zaks91c2a112012-02-08 23:16:56 +0000177 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
178 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
179 const Stmt *S = 0) const;
180
Anna Zaks66c40402012-02-14 21:55:24 +0000181 /// Check if the function is not known to us. So, for example, we could
182 /// conservatively assume it can free/reallocate it's pointer arguments.
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000183 bool doesNotFreeMemory(const CallOrObjCMessage *Call,
184 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000185
Ted Kremenek9c378f72011-08-12 23:37:29 +0000186 static bool SummarizeValue(raw_ostream &os, SVal V);
187 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000188 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000189
Anna Zaksca8e36e2012-02-23 21:38:21 +0000190 /// Find the location of the allocation for Sym on the path leading to the
191 /// exploded node N.
192 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
193 CheckerContext &C) const;
194
Anna Zaksda046772012-02-11 21:02:40 +0000195 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
196
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000197 /// The bug visitor which allows us to print extra diagnostics along the
198 /// BugReport path. For example, showing the allocation site of the leaked
199 /// region.
200 class MallocBugVisitor : public BugReporterVisitor {
201 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000202 enum NotificationMode {
203 Normal,
204 Complete,
205 ReallocationFailed
206 };
207
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000208 // The allocated region symbol tracked by the main analysis.
209 SymbolRef Sym;
Anna Zaksfe571602012-02-16 22:26:07 +0000210 NotificationMode Mode;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000211
212 public:
Anna Zaksfe571602012-02-16 22:26:07 +0000213 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000214 virtual ~MallocBugVisitor() {}
215
216 void Profile(llvm::FoldingSetNodeID &ID) const {
217 static int X = 0;
218 ID.AddPointer(&X);
219 ID.AddPointer(Sym);
220 }
221
Anna Zaksfe571602012-02-16 22:26:07 +0000222 inline bool isAllocated(const RefState *S, const RefState *SPrev,
223 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000224 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000225 return (Stmt && isa<CallExpr>(Stmt) &&
226 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000227 }
228
Anna Zaksfe571602012-02-16 22:26:07 +0000229 inline bool isReleased(const RefState *S, const RefState *SPrev,
230 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000231 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000232 return (Stmt && isa<CallExpr>(Stmt) &&
233 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
234 }
235
236 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
237 const Stmt *Stmt) {
238 // If the expression is not a call, and the state change is
239 // released -> allocated, it must be the realloc return value
240 // check. If we have to handle more cases here, it might be cleaner just
241 // to track this extra bit in the state itself.
242 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
243 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000244 }
245
246 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
247 const ExplodedNode *PrevN,
248 BugReporterContext &BRC,
249 BugReport &BR);
250 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000251};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000252} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000253
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000254typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000255typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000256class RegionState {};
257class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000258namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000259namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000260 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000261 struct ProgramStateTrait<RegionState>
262 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000263 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000264 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000265
266 template <>
267 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000268 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000269 static void *GDMIndex() { static int x; return &x; }
270 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000271}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000272}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000273
Anna Zaks4fb54872012-02-11 21:02:35 +0000274namespace {
275class StopTrackingCallback : public SymbolVisitor {
276 ProgramStateRef state;
277public:
278 StopTrackingCallback(ProgramStateRef st) : state(st) {}
279 ProgramStateRef getState() const { return state; }
280
281 bool VisitSymbol(SymbolRef sym) {
282 state = state->remove<RegionState>(sym);
283 return true;
284 }
285};
286} // end anonymous namespace
287
Anna Zaks66c40402012-02-14 21:55:24 +0000288void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000289 if (!II_malloc)
290 II_malloc = &Ctx.Idents.get("malloc");
291 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000292 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000293 if (!II_realloc)
294 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000295 if (!II_reallocf)
296 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000297 if (!II_calloc)
298 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000299 if (!II_valloc)
300 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaks60a1fa42012-02-22 03:14:20 +0000301 if (!II_strdup)
302 II_strdup = &Ctx.Idents.get("strdup");
303 if (!II_strndup)
304 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000305}
306
Anna Zaks66c40402012-02-14 21:55:24 +0000307bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000308 if (!FD)
309 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000310 IdentifierInfo *FunI = FD->getIdentifier();
311 if (!FunI)
312 return false;
313
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000314 initIdentifierInfo(C);
315
Anna Zaks40add292012-02-15 00:11:25 +0000316 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000317 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
318 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000319 return true;
320
321 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
322 FD->specific_attr_begin<OwnershipAttr>() !=
323 FD->specific_attr_end<OwnershipAttr>())
324 return true;
325
326
327 return false;
328}
329
Anna Zaksb319e022012-02-08 20:13:28 +0000330void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
331 const FunctionDecl *FD = C.getCalleeDecl(CE);
332 if (!FD)
333 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000334
Anna Zaksb16ce452012-02-15 00:11:22 +0000335 initIdentifierInfo(C.getASTContext());
336 IdentifierInfo *FunI = FD->getIdentifier();
337 if (!FunI)
338 return;
339
Anna Zaks87cb5be2012-02-22 19:24:52 +0000340 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000341 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000342 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000343 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000344 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000345 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000346 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000347 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000348 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000349 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000350 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000351 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000352 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000353 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000354 State = MallocUpdateRefState(C, CE, State);
355 } else if (Filter.CMallocOptimistic) {
356 // Check all the attributes, if there are any.
357 // There can be multiple of these attributes.
358 if (FD->hasAttrs())
359 for (specific_attr_iterator<OwnershipAttr>
360 i = FD->specific_attr_begin<OwnershipAttr>(),
361 e = FD->specific_attr_end<OwnershipAttr>();
362 i != e; ++i) {
363 switch ((*i)->getOwnKind()) {
364 case OwnershipAttr::Returns:
365 State = MallocMemReturnsAttr(C, CE, *i);
366 break;
367 case OwnershipAttr::Takes:
368 case OwnershipAttr::Holds:
369 State = FreeMemAttr(C, CE, *i);
370 break;
371 }
372 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000373 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000374 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000375}
376
Anna Zaks87cb5be2012-02-22 19:24:52 +0000377ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
378 const CallExpr *CE,
379 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000380 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000381 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000382
Sean Huntcf807c42010-08-18 23:23:40 +0000383 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000384 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000385 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000386 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000387 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000388}
389
Anna Zaksb319e022012-02-08 20:13:28 +0000390ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000391 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000392 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000393 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000394 // Get the return value.
395 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000396
Anna Zaksb16ce452012-02-15 00:11:22 +0000397 // We expect the malloc functions to return a pointer.
398 if (!isa<Loc>(retVal))
399 return 0;
400
Jordy Rose32f26562010-07-04 00:00:41 +0000401 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000402 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000403
Jordy Rose32f26562010-07-04 00:00:41 +0000404 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000405 const SymbolicRegion *R =
406 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000407 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000408 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000409 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000410 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000411 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
412 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
413 DefinedOrUnknownSVal extentMatchesSize =
414 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000415
Anna Zaks60a1fa42012-02-22 03:14:20 +0000416 state = state->assume(extentMatchesSize, true);
417 assert(state);
418 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000419
Anna Zaks87cb5be2012-02-22 19:24:52 +0000420 return MallocUpdateRefState(C, CE, state);
421}
422
423ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
424 const CallExpr *CE,
425 ProgramStateRef state) {
426 // Get the return value.
427 SVal retVal = state->getSVal(CE, C.getLocationContext());
428
429 // We expect the malloc functions to return a pointer.
430 if (!isa<Loc>(retVal))
431 return 0;
432
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000433 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000434 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000435
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000436 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000437 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000438
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000439}
440
Anna Zaks87cb5be2012-02-22 19:24:52 +0000441ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
442 const CallExpr *CE,
443 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000444 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000445 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000446
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 Zaks87cb5be2012-02-22 19:24:52 +0000449 return FreeMemAux(C, CE, C.getState(), *I,
450 Att->getOwnKind() == OwnershipAttr::Holds);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000451 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000452 return 0;
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());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000538 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000539 C.EmitReport(R);
540 }
Anna Zaksb319e022012-02-08 20:13:28 +0000541 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000542 }
543
544 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000545 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000546 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
547 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000548}
549
Ted Kremenek9c378f72011-08-12 23:37:29 +0000550bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000551 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
552 os << "an integer (" << IntVal->getValue() << ")";
553 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
554 os << "a constant address (" << ConstAddr->getValue() << ")";
555 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000556 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000557 else
558 return false;
559
560 return true;
561}
562
Ted Kremenek9c378f72011-08-12 23:37:29 +0000563bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000564 const MemRegion *MR) {
565 switch (MR->getKind()) {
566 case MemRegion::FunctionTextRegionKind: {
567 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
568 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000569 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000570 else
571 os << "the address of a function";
572 return true;
573 }
574 case MemRegion::BlockTextRegionKind:
575 os << "block text";
576 return true;
577 case MemRegion::BlockDataRegionKind:
578 // FIXME: where the block came from?
579 os << "a block";
580 return true;
581 default: {
582 const MemSpaceRegion *MS = MR->getMemorySpace();
583
Anna Zakseb31a762012-01-04 23:54:01 +0000584 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000585 const VarRegion *VR = dyn_cast<VarRegion>(MR);
586 const VarDecl *VD;
587 if (VR)
588 VD = VR->getDecl();
589 else
590 VD = NULL;
591
592 if (VD)
593 os << "the address of the local variable '" << VD->getName() << "'";
594 else
595 os << "the address of a local stack variable";
596 return true;
597 }
Anna Zakseb31a762012-01-04 23:54:01 +0000598
599 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000600 const VarRegion *VR = dyn_cast<VarRegion>(MR);
601 const VarDecl *VD;
602 if (VR)
603 VD = VR->getDecl();
604 else
605 VD = NULL;
606
607 if (VD)
608 os << "the address of the parameter '" << VD->getName() << "'";
609 else
610 os << "the address of a parameter";
611 return true;
612 }
Anna Zakseb31a762012-01-04 23:54:01 +0000613
614 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000615 const VarRegion *VR = dyn_cast<VarRegion>(MR);
616 const VarDecl *VD;
617 if (VR)
618 VD = VR->getDecl();
619 else
620 VD = NULL;
621
622 if (VD) {
623 if (VD->isStaticLocal())
624 os << "the address of the static variable '" << VD->getName() << "'";
625 else
626 os << "the address of the global variable '" << VD->getName() << "'";
627 } else
628 os << "the address of a global variable";
629 return true;
630 }
Anna Zakseb31a762012-01-04 23:54:01 +0000631
632 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000633 }
634 }
635}
636
637void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000638 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000639 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000640 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000641 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000642
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000643 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000644 llvm::raw_svector_ostream os(buf);
645
646 const MemRegion *MR = ArgVal.getAsRegion();
647 if (MR) {
648 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
649 MR = ER->getSuperRegion();
650
651 // Special case for alloca()
652 if (isa<AllocaRegion>(MR))
653 os << "Argument to free() was allocated by alloca(), not malloc()";
654 else {
655 os << "Argument to free() is ";
656 if (SummarizeRegion(os, MR))
657 os << ", which is not memory allocated by malloc()";
658 else
659 os << "not memory allocated by malloc()";
660 }
661 } else {
662 os << "Argument to free() is ";
663 if (SummarizeValue(os, ArgVal))
664 os << ", which is not memory allocated by malloc()";
665 else
666 os << "not memory allocated by malloc()";
667 }
668
Anna Zakse172e8b2011-08-17 23:00:25 +0000669 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000670 R->addRange(range);
671 C.EmitReport(R);
672 }
673}
674
Anna Zaks87cb5be2012-02-22 19:24:52 +0000675ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
676 const CallExpr *CE,
677 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000678 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000679 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000680 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000681 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
682 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000683 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000684 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000685
Ted Kremenek846eabd2010-12-01 21:28:31 +0000686 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000687
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000688 DefinedOrUnknownSVal PtrEQ =
689 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000690
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000691 // Get the size argument. If there is no size arg then give up.
692 const Expr *Arg1 = CE->getArg(1);
693 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000694 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000695
696 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000697 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
698 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000699 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000700 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000701
702 // Compare the size argument to 0.
703 DefinedOrUnknownSVal SizeZero =
704 svalBuilder.evalEQ(state, Arg1Val,
705 svalBuilder.makeIntValWithPtrWidth(0, false));
706
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000707 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
708 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
709 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
710 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
711 // We only assume exceptional states if they are definitely true; if the
712 // state is under-constrained, assume regular realloc behavior.
713 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
714 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
715
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000716 // If the ptr is NULL and the size is not 0, the call is equivalent to
717 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000718 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000719 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000720 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000721 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000722 }
723
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000724 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000725 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000726
Anna Zaks30838b92012-02-13 20:57:07 +0000727 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000728 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000729 SymbolRef FromPtr = arg0Val.getAsSymbol();
730 SVal RetVal = state->getSVal(CE, LCtx);
731 SymbolRef ToPtr = RetVal.getAsSymbol();
732 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000733 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000734
735 // If the size is 0, free the memory.
736 if (SizeIsZero)
737 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000738 // The semantics of the return value are:
739 // If size was equal to 0, either NULL or a pointer suitable to be passed
740 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000741 stateFree = stateFree->set<ReallocPairs>(ToPtr,
742 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000743 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000744 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000745 }
746
747 // Default behavior.
748 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
749 // FIXME: We should copy the content of the original buffer.
750 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
751 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000752 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000753 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000754 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
755 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000756 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000757 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000758 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000759 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000760}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000761
Anna Zaks87cb5be2012-02-22 19:24:52 +0000762ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Ted Kremenek8bef8232012-01-26 21:29:00 +0000763 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000764 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000765 const LocationContext *LCtx = C.getLocationContext();
766 SVal count = state->getSVal(CE->getArg(0), LCtx);
767 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000768 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
769 svalBuilder.getContext().getSizeType());
770 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000771
Anna Zaks87cb5be2012-02-22 19:24:52 +0000772 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000773}
774
Anna Zaksca8e36e2012-02-23 21:38:21 +0000775const Stmt *
776MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
777 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000778 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000779 // Walk the ExplodedGraph backwards and find the first node that referred to
780 // the tracked symbol.
781 const ExplodedNode *AllocNode = N;
782
783 while (N) {
784 if (!N->getState()->get<RegionState>(Sym))
785 break;
Anna Zaks7752d292012-02-27 23:40:55 +0000786 // Allocation node, is the last node in the current context in which the
787 // symbol was tracked.
788 if (N->getLocationContext() == LeakContext)
789 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000790 N = N->pred_empty() ? NULL : *(N->pred_begin());
791 }
792
793 ProgramPoint P = AllocNode->getLocation();
Anna Zaks7752d292012-02-27 23:40:55 +0000794 if (!isa<StmtPoint>(P))
795 return 0;
796
797 return cast<StmtPoint>(P).getStmt();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000798}
799
Anna Zaksda046772012-02-11 21:02:40 +0000800void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
801 CheckerContext &C) const {
802 assert(N);
803 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000804 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000805 // Leaks should not be reported if they are post-dominated by a sink:
806 // (1) Sinks are higher importance bugs.
807 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
808 // with __noreturn functions such as assert() or exit(). We choose not
809 // to report leaks on such paths.
810 BT_Leak->setSuppressOnSink(true);
811 }
812
Anna Zaksca8e36e2012-02-23 21:38:21 +0000813 // Most bug reports are cached at the location where they occurred.
814 // With leaks, we want to unique them by the location where they were
815 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000816 PathDiagnosticLocation LocUsedForUniqueing;
817 if (const Stmt *AllocStmt = getAllocationSite(N, Sym, C))
818 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
819 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000820
Anna Zaksfebdc322012-02-16 22:26:12 +0000821 BugReport *R = new BugReport(*BT_Leak,
Anna Zaksca8e36e2012-02-23 21:38:21 +0000822 "Memory is never released; potential memory leak", N, LocUsedForUniqueing);
Anna Zaksda046772012-02-11 21:02:40 +0000823 R->addVisitor(new MallocBugVisitor(Sym));
824 C.EmitReport(R);
825}
826
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000827void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
828 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000829{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000830 if (!SymReaper.hasDeadSymbols())
831 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000832
Ted Kremenek8bef8232012-01-26 21:29:00 +0000833 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000834 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000835 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000836
Ted Kremenek217470e2011-07-28 23:07:51 +0000837 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000838 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000839 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
840 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000841 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000842 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000843 Errors.push_back(I->first);
844 }
Jordy Rose90760142010-08-18 04:33:47 +0000845 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000846 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000847
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000848 }
849 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000850
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000851 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000852 ReallocMap RP = state->get<ReallocPairs>();
853 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
854 if (SymReaper.isDead(I->first) ||
855 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000856 state = state->remove<ReallocPairs>(I->first);
857 }
858 }
859
Anna Zaksca8e36e2012-02-23 21:38:21 +0000860 // Generate leak node.
861 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
862 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000863
Anna Zaksca8e36e2012-02-23 21:38:21 +0000864 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000865 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000866 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
867 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000868 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000869 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000870 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000871}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000872
Anna Zaksda046772012-02-11 21:02:40 +0000873void MallocChecker::checkEndPath(CheckerContext &C) const {
874 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000875 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000876
Anna Zaksa19581a2012-02-20 22:25:23 +0000877 // If inside inlined call, skip it.
878 if (C.getLocationContext()->getParent() != 0)
879 return;
880
Jordy Rose09cef092010-08-18 04:26:59 +0000881 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000882 RefState RS = I->second;
883 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000884 ExplodedNode *N = C.addTransition(state);
885 if (N)
886 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000887 }
888 }
889}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000890
Anna Zaks91c2a112012-02-08 23:16:56 +0000891bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
892 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000893 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000894 const RefState *RS = state->get<RegionState>(Sym);
895 if (!RS)
896 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000897
Anna Zaks91c2a112012-02-08 23:16:56 +0000898 if (RS->isAllocated()) {
899 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
900 C.addTransition(state);
901 return true;
902 }
903 return false;
904}
905
Anna Zaks66c40402012-02-14 21:55:24 +0000906void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
907 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
908 return;
909
910 // Check use after free, when a freed pointer is passed to a call.
911 ProgramStateRef State = C.getState();
912 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
913 E = CE->arg_end(); I != E; ++I) {
914 const Expr *A = *I;
915 if (A->getType().getTypePtr()->isAnyPointerType()) {
916 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
917 if (!Sym)
918 continue;
919 if (checkUseAfterFree(Sym, C, A))
920 return;
921 }
922 }
923}
924
Anna Zaks91c2a112012-02-08 23:16:56 +0000925void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
926 const Expr *E = S->getRetValue();
927 if (!E)
928 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000929
930 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +0000931 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
932 SymbolRef Sym = RetVal.getAsSymbol();
933 if (!Sym)
934 // If we are returning a field of the allocated struct or an array element,
935 // the callee could still free the memory.
936 // TODO: This logic should be a part of generic symbol escape callback.
937 if (const MemRegion *MR = RetVal.getAsRegion())
938 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
939 if (const SymbolicRegion *BMR =
940 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
941 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000942 if (!Sym)
943 return;
944
Anna Zaks0860cd02012-02-11 21:44:39 +0000945 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +0000946 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +0000947 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000948
Anna Zaksa19581a2012-02-20 22:25:23 +0000949 // If this function body is not inlined, check if the symbol is escaping.
950 if (C.getLocationContext()->getParent() == 0)
951 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000952}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000953
Anna Zaks91c2a112012-02-08 23:16:56 +0000954bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
955 const Stmt *S) const {
956 assert(Sym);
957 const RefState *RS = C.getState()->get<RegionState>(Sym);
958 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000959 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000960 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000961 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +0000962
Anna Zaksfebdc322012-02-16 22:26:12 +0000963 BugReport *R = new BugReport(*BT_UseFree,
964 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +0000965 if (S)
966 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000967 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000968 C.EmitReport(R);
969 return true;
970 }
971 }
972 return false;
973}
974
Zhongxing Xuc8023782010-03-10 04:58:55 +0000975// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000976void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
977 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000978 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000979 if (Sym)
980 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000981}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000982
Anna Zaks4fb54872012-02-11 21:02:35 +0000983//===----------------------------------------------------------------------===//
984// Check various ways a symbol can be invalidated.
985// TODO: This logic (the next 3 functions) is copied/similar to the
986// RetainRelease checker. We might want to factor this out.
987//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000988
Anna Zaks4fb54872012-02-11 21:02:35 +0000989// Stop tracking symbols when a value escapes as a result of checkBind.
990// A value escapes in three possible cases:
991// (1) we are binding to something that is not a memory region.
992// (2) we are binding to a memregion that does not have stack storage
993// (3) we are binding to a memregion with stack storage that the store
994// does not understand.
995void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
996 CheckerContext &C) const {
997 // Are we storing to something that causes the value to "escape"?
998 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000999 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001000
Anna Zaks4fb54872012-02-11 21:02:35 +00001001 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1002 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001003
Anna Zaks4fb54872012-02-11 21:02:35 +00001004 if (!escapes) {
1005 // To test (3), generate a new state with the binding added. If it is
1006 // the same state, then it escapes (since the store cannot represent
1007 // the binding).
1008 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001009 }
Anna Zaksac593002012-02-16 03:40:57 +00001010 if (!escapes) {
1011 // Case 4: We do not currently model what happens when a symbol is
1012 // assigned to a struct field, so be conservative here and let the symbol
1013 // go. TODO: This could definitely be improved upon.
1014 escapes = !isa<VarRegion>(regionLoc->getRegion());
1015 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001016 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001017
1018 // If our store can represent the binding and we aren't storing to something
1019 // that doesn't have local storage then just return and have the simulation
1020 // state continue as is.
1021 if (!escapes)
1022 return;
1023
1024 // Otherwise, find all symbols referenced by 'val' that we are tracking
1025 // and stop tracking them.
1026 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1027 C.addTransition(state);
1028}
1029
1030// If a symbolic region is assumed to NULL (or another constant), stop tracking
1031// it - assuming that allocation failed on this path.
1032ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1033 SVal Cond,
1034 bool Assumption) const {
1035 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001036 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1037 // If the symbol is assumed to NULL or another constant, this will
1038 // return an APSInt*.
1039 if (state->getSymVal(I.getKey()))
1040 state = state->remove<RegionState>(I.getKey());
1041 }
1042
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001043 // Realloc returns 0 when reallocation fails, which means that we should
1044 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001045 ReallocMap RP = state->get<ReallocPairs>();
1046 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001047 // If the symbol is assumed to NULL or another constant, this will
1048 // return an APSInt*.
1049 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001050 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1051 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001052 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001053 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1054 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001055 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001056 }
1057 state = state->remove<ReallocPairs>(I.getKey());
1058 }
1059 }
1060
Anna Zaks4fb54872012-02-11 21:02:35 +00001061 return state;
1062}
1063
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001064// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001065// conservatively assume it can free/reallocate it's pointer arguments.
1066// (We assume that the pointers cannot escape through calls to system
1067// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001068bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1069 ProgramStateRef State) const {
1070 if (!Call)
1071 return false;
1072
1073 // For now, assume that any C++ call can free memory.
1074 // TODO: If we want to be more optimistic here, we'll need to make sure that
1075 // regions escape to C++ containers. They seem to do that even now, but for
1076 // mysterious reasons.
1077 if (Call->isCXXCall())
1078 return false;
1079
1080 const Decl *D = Call->getDecl();
1081 if (!D)
1082 return false;
1083
Anna Zaks66c40402012-02-14 21:55:24 +00001084 ASTContext &ASTC = State->getStateManager().getContext();
1085
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001086 // If it's one of the allocation functions we can reason about, we model
1087 // it's behavior explicitly.
1088 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1089 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001090 }
1091
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001092 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001093 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001094 if (!SM.isInSystemHeader(D->getLocation()))
1095 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001096
Anna Zaks07d39a42012-02-28 01:54:22 +00001097 // Process C/ObjC functions.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001098 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001099 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001100 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001101 if (!II)
1102 return true;
1103 StringRef FName = II->getName();
1104
1105 // White list thread local storage.
1106 if (FName.equals("pthread_setspecific"))
1107 return false;
1108
1109 // White list the 'XXXNoCopy' ObjC Methods.
1110 if (FName.endswith("NoCopy")) {
1111 // Look for the deallocator argument. We know that the memory ownership
1112 // is not transfered only if the deallocator argument is
1113 // 'kCFAllocatorNull'.
1114 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1115 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1116 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1117 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1118 if (DeallocatorName == "kCFAllocatorNull")
1119 return true;
1120 }
1121 }
1122 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001123 }
1124
1125 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001126 // Most system calls, do not free the memory.
1127 return true;
1128
1129 // Process ObjC functions.
1130 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1131 Selector S = ObjCD->getSelector();
1132
1133 // White list the ObjC functions which do free memory.
1134 // - Anything containing 'freeWhenDone' param set to 1.
1135 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1136 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1137 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1138 if (Call->getArgSVal(i).isConstant(1))
1139 return false;
1140 }
1141 }
1142
1143 // Otherwise, assume that the function does not free memory.
1144 // Most system calls, do not free the memory.
1145 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001146 }
1147
1148 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001149 return false;
1150
Anna Zaks66c40402012-02-14 21:55:24 +00001151}
1152
Anna Zaks4fb54872012-02-11 21:02:35 +00001153// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1154// escapes, when we are tracking p), do not track the symbol as we cannot reason
1155// about it anymore.
1156ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001157MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001158 const StoreManager::InvalidatedSymbols *invalidated,
1159 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001160 ArrayRef<const MemRegion *> Regions,
1161 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001162 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001163 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001164 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001165
Anna Zaks66c40402012-02-14 21:55:24 +00001166 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001167 // regions (explicit and implicit) escaped.
1168
1169 // Otherwise, whitelist explicit pointers; we still can track them.
1170 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001171 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1172 E = ExplicitRegions.end(); I != E; ++I) {
1173 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1174 WhitelistedSymbols.insert(R->getSymbol());
1175 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001176 }
1177
1178 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1179 E = invalidated->end(); I!=E; ++I) {
1180 SymbolRef sym = *I;
1181 if (WhitelistedSymbols.count(sym))
1182 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001183 // The symbol escaped.
1184 if (const RefState *RS = State->get<RegionState>(sym))
1185 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001186 }
Anna Zaks66c40402012-02-14 21:55:24 +00001187 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001188}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001189
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001190PathDiagnosticPiece *
1191MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1192 const ExplodedNode *PrevN,
1193 BugReporterContext &BRC,
1194 BugReport &BR) {
1195 const RefState *RS = N->getState()->get<RegionState>(Sym);
1196 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1197 if (!RS && !RSPrev)
1198 return 0;
1199
Anna Zaksfe571602012-02-16 22:26:07 +00001200 const Stmt *S = 0;
1201 const char *Msg = 0;
1202
1203 // Retrieve the associated statement.
1204 ProgramPoint ProgLoc = N->getLocation();
1205 if (isa<StmtPoint>(ProgLoc))
1206 S = cast<StmtPoint>(ProgLoc).getStmt();
1207 // If an assumption was made on a branch, it should be caught
1208 // here by looking at the state transition.
1209 if (isa<BlockEdge>(ProgLoc)) {
1210 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1211 S = srcBlk->getTerminator();
1212 }
1213 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001214 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001215
1216 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001217 if (Mode == Normal) {
1218 if (isAllocated(RS, RSPrev, S))
1219 Msg = "Memory is allocated";
1220 else if (isReleased(RS, RSPrev, S))
1221 Msg = "Memory is released";
1222 else if (isReallocFailedCheck(RS, RSPrev, S)) {
1223 Mode = ReallocationFailed;
1224 Msg = "Reallocation failed";
1225 }
1226
1227 // We are in a special mode if a reallocation failed later in the path.
1228 } else if (Mode == ReallocationFailed) {
1229 // Generate a special diagnostic for the first realloc we find.
1230 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1231 return 0;
1232
1233 // Check that the name of the function is realloc.
1234 const CallExpr *CE = dyn_cast<CallExpr>(S);
1235 if (!CE)
1236 return 0;
1237 const FunctionDecl *funDecl = CE->getDirectCallee();
1238 if (!funDecl)
1239 return 0;
1240 StringRef FunName = funDecl->getName();
1241 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1242 return 0;
1243 Msg = "Attempt to reallocate memory";
1244 Mode = Normal;
1245 }
1246
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001247 if (!Msg)
1248 return 0;
1249
1250 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001251 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001252 N->getLocationContext());
1253 return new PathDiagnosticEventPiece(Pos, Msg);
1254}
1255
1256
Anna Zaks231361a2012-02-08 23:16:52 +00001257#define REGISTER_CHECKER(name) \
1258void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001259 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001260 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001261}
Anna Zaks231361a2012-02-08 23:16:52 +00001262
1263REGISTER_CHECKER(MallocPessimistic)
1264REGISTER_CHECKER(MallocOptimistic)