blob: ae81ad6eda019ac61187d60098b7acf73a326ce3 [file] [log] [blame]
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines malloc/free checker, which checks for potential memory
11// leaks, double free, and use-after-free problems.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000017#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000018#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaks66c40402012-02-14 21:55:24 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Anna Zaks15d0ae12012-02-11 23:46:36 +000025#include "clang/Basic/SourceManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000026#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000027#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000029#include <climits>
30
Zhongxing Xu589c0f22009-11-12 08:38:56 +000031using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000032using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000033
34namespace {
35
Zhongxing Xu7fb14642009-12-11 00:55:44 +000036class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000037 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
38 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000039 const Stmt *S;
40
Zhongxing Xu7fb14642009-12-11 00:55:44 +000041public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000042 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
43
Zhongxing Xub94b81a2009-12-31 06:13:07 +000044 bool isAllocated() const { return K == AllocateUnchecked; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000045 bool isReleased() const { return K == Released; }
Anna Zaksca23eb22012-02-29 18:42:47 +000046
Anna Zaksc8bb3be2012-02-13 18:05:39 +000047 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000048
49 bool operator==(const RefState &X) const {
50 return K == X.K && S == X.S;
51 }
52
Zhongxing Xub94b81a2009-12-31 06:13:07 +000053 static RefState getAllocateUnchecked(const Stmt *s) {
54 return RefState(AllocateUnchecked, s);
55 }
56 static RefState getAllocateFailed() {
57 return RefState(AllocateFailed, 0);
58 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000059 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
60 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000061 static RefState getRelinquished(const Stmt *s) {
62 return RefState(Relinquished, s);
63 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064
65 void Profile(llvm::FoldingSetNodeID &ID) const {
66 ID.AddInteger(K);
67 ID.AddPointer(S);
68 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000069};
70
Anna Zaks40add292012-02-15 00:11:25 +000071struct ReallocPair {
72 SymbolRef ReallocatedSym;
73 bool IsFreeOnFailure;
74 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
75 void Profile(llvm::FoldingSetNodeID &ID) const {
76 ID.AddInteger(IsFreeOnFailure);
77 ID.AddPointer(ReallocatedSym);
78 }
79 bool operator==(const ReallocPair &X) const {
80 return ReallocatedSym == X.ReallocatedSym &&
81 IsFreeOnFailure == X.IsFreeOnFailure;
82 }
83};
84
Anna Zaksb319e022012-02-08 20:13:28 +000085class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000086 check::EndPath,
87 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000088 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000089 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000090 check::Location,
91 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000092 eval::Assume,
93 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000094{
Anna Zaksfebdc322012-02-16 22:26:12 +000095 mutable OwningPtr<BugType> BT_DoubleFree;
96 mutable OwningPtr<BugType> BT_Leak;
97 mutable OwningPtr<BugType> BT_UseFree;
98 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +000099 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000100 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
101
102 static const unsigned InvalidArgIndex = UINT_MAX;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000103
104public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000105 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000106 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000107
108 /// In pessimistic mode, the checker assumes that it does not know which
109 /// functions might free the memory.
110 struct ChecksFilter {
111 DefaultBool CMallocPessimistic;
112 DefaultBool CMallocOptimistic;
113 };
114
115 ChecksFilter Filter;
116
Anna Zaks66c40402012-02-14 21:55:24 +0000117 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000118 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000119 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000120 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000121 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000123 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000124 void checkLocation(SVal l, bool isLoad, const Stmt *S,
125 CheckerContext &C) const;
126 void checkBind(SVal location, SVal val, const Stmt*S,
127 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000128 ProgramStateRef
129 checkRegionChanges(ProgramStateRef state,
130 const StoreManager::InvalidatedSymbols *invalidated,
131 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000132 ArrayRef<const MemRegion *> Regions,
133 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000134 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
135 return true;
136 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000137
Zhongxing Xu7b760962009-11-13 07:25:27 +0000138private:
Anna Zaks66c40402012-02-14 21:55:24 +0000139 void initIdentifierInfo(ASTContext &C) const;
140
141 /// Check if this is one of the functions which can allocate/reallocate memory
142 /// pointed to by one of its arguments.
143 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
144
Anna Zaks87cb5be2012-02-22 19:24:52 +0000145 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
146 const CallExpr *CE,
147 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000148 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000149 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000150 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000151 return MallocMemAux(C, CE,
152 state->getSVal(SizeEx, C.getLocationContext()),
153 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000154 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000155
Ted Kremenek8bef8232012-01-26 21:29:00 +0000156 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000157 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000158 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000159
Anna Zaks87cb5be2012-02-22 19:24:52 +0000160 /// Update the RefState to reflect the new memory allocation.
161 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
162 const CallExpr *CE,
163 ProgramStateRef state);
164
165 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
166 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000167 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
168 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000169 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000170
Anna Zaks87cb5be2012-02-22 19:24:52 +0000171 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
172 bool FreesMemOnFailure) const;
173 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000174
Anna Zaks91c2a112012-02-08 23:16:56 +0000175 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
176 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
177 const Stmt *S = 0) const;
178
Anna Zaks66c40402012-02-14 21:55:24 +0000179 /// Check if the function is not known to us. So, for example, we could
180 /// conservatively assume it can free/reallocate it's pointer arguments.
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000181 bool doesNotFreeMemory(const CallOrObjCMessage *Call,
182 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000183
Ted Kremenek9c378f72011-08-12 23:37:29 +0000184 static bool SummarizeValue(raw_ostream &os, SVal V);
185 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000186 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000187
Anna Zaksca8e36e2012-02-23 21:38:21 +0000188 /// Find the location of the allocation for Sym on the path leading to the
189 /// exploded node N.
190 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
191 CheckerContext &C) const;
192
Anna Zaksda046772012-02-11 21:02:40 +0000193 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
194
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000195 /// The bug visitor which allows us to print extra diagnostics along the
196 /// BugReport path. For example, showing the allocation site of the leaked
197 /// region.
198 class MallocBugVisitor : public BugReporterVisitor {
199 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000200 enum NotificationMode {
201 Normal,
202 Complete,
203 ReallocationFailed
204 };
205
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000206 // The allocated region symbol tracked by the main analysis.
207 SymbolRef Sym;
Anna Zaksfe571602012-02-16 22:26:07 +0000208 NotificationMode Mode;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000209
210 public:
Anna Zaksfe571602012-02-16 22:26:07 +0000211 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000212 virtual ~MallocBugVisitor() {}
213
214 void Profile(llvm::FoldingSetNodeID &ID) const {
215 static int X = 0;
216 ID.AddPointer(&X);
217 ID.AddPointer(Sym);
218 }
219
Anna Zaksfe571602012-02-16 22:26:07 +0000220 inline bool isAllocated(const RefState *S, const RefState *SPrev,
221 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000222 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000223 return (Stmt && isa<CallExpr>(Stmt) &&
224 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000225 }
226
Anna Zaksfe571602012-02-16 22:26:07 +0000227 inline bool isReleased(const RefState *S, const RefState *SPrev,
228 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000229 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000230 return (Stmt && isa<CallExpr>(Stmt) &&
231 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
232 }
233
234 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
235 const Stmt *Stmt) {
236 // If the expression is not a call, and the state change is
237 // released -> allocated, it must be the realloc return value
238 // check. If we have to handle more cases here, it might be cleaner just
239 // to track this extra bit in the state itself.
240 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
241 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000242 }
243
244 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
245 const ExplodedNode *PrevN,
246 BugReporterContext &BRC,
247 BugReport &BR);
248 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000249};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000250} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000251
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000252typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000253typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000254class RegionState {};
255class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000256namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000257namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000258 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000259 struct ProgramStateTrait<RegionState>
260 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000261 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000262 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000263
264 template <>
265 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000266 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000267 static void *GDMIndex() { static int x; return &x; }
268 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000269}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000270}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000271
Anna Zaks4fb54872012-02-11 21:02:35 +0000272namespace {
273class StopTrackingCallback : public SymbolVisitor {
274 ProgramStateRef state;
275public:
276 StopTrackingCallback(ProgramStateRef st) : state(st) {}
277 ProgramStateRef getState() const { return state; }
278
279 bool VisitSymbol(SymbolRef sym) {
280 state = state->remove<RegionState>(sym);
281 return true;
282 }
283};
284} // end anonymous namespace
285
Anna Zaks66c40402012-02-14 21:55:24 +0000286void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000287 if (!II_malloc)
288 II_malloc = &Ctx.Idents.get("malloc");
289 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000290 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000291 if (!II_realloc)
292 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000293 if (!II_reallocf)
294 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000295 if (!II_calloc)
296 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000297 if (!II_valloc)
298 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaks60a1fa42012-02-22 03:14:20 +0000299 if (!II_strdup)
300 II_strdup = &Ctx.Idents.get("strdup");
301 if (!II_strndup)
302 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000303}
304
Anna Zaks66c40402012-02-14 21:55:24 +0000305bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000306 if (!FD)
307 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000308 IdentifierInfo *FunI = FD->getIdentifier();
309 if (!FunI)
310 return false;
311
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000312 initIdentifierInfo(C);
313
Anna Zaks40add292012-02-15 00:11:25 +0000314 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000315 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
316 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000317 return true;
318
319 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
320 FD->specific_attr_begin<OwnershipAttr>() !=
321 FD->specific_attr_end<OwnershipAttr>())
322 return true;
323
324
325 return false;
326}
327
Anna Zaksb319e022012-02-08 20:13:28 +0000328void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
329 const FunctionDecl *FD = C.getCalleeDecl(CE);
330 if (!FD)
331 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000332
Anna Zaksb16ce452012-02-15 00:11:22 +0000333 initIdentifierInfo(C.getASTContext());
334 IdentifierInfo *FunI = FD->getIdentifier();
335 if (!FunI)
336 return;
337
Anna Zaks87cb5be2012-02-22 19:24:52 +0000338 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000339 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000340 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000341 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000342 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000343 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000344 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000345 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000346 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000347 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000348 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000349 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000350 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000351 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000352 State = MallocUpdateRefState(C, CE, State);
353 } else if (Filter.CMallocOptimistic) {
354 // Check all the attributes, if there are any.
355 // There can be multiple of these attributes.
356 if (FD->hasAttrs())
357 for (specific_attr_iterator<OwnershipAttr>
358 i = FD->specific_attr_begin<OwnershipAttr>(),
359 e = FD->specific_attr_end<OwnershipAttr>();
360 i != e; ++i) {
361 switch ((*i)->getOwnKind()) {
362 case OwnershipAttr::Returns:
363 State = MallocMemReturnsAttr(C, CE, *i);
364 break;
365 case OwnershipAttr::Takes:
366 case OwnershipAttr::Holds:
367 State = FreeMemAttr(C, CE, *i);
368 break;
369 }
370 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000371 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000372 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000373}
374
Anna Zaks87cb5be2012-02-22 19:24:52 +0000375ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
376 const CallExpr *CE,
377 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000378 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000379 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000380
Sean Huntcf807c42010-08-18 23:23:40 +0000381 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000382 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000383 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000384 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000385 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000386}
387
Anna Zaksb319e022012-02-08 20:13:28 +0000388ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000389 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000390 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000391 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000392 // Get the return value.
393 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000394
Anna Zaksb16ce452012-02-15 00:11:22 +0000395 // We expect the malloc functions to return a pointer.
396 if (!isa<Loc>(retVal))
397 return 0;
398
Jordy Rose32f26562010-07-04 00:00:41 +0000399 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000400 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000401
Jordy Rose32f26562010-07-04 00:00:41 +0000402 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000403 const SymbolicRegion *R =
404 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000405 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000406 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000407 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000408 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000409 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
410 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
411 DefinedOrUnknownSVal extentMatchesSize =
412 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000413
Anna Zaks60a1fa42012-02-22 03:14:20 +0000414 state = state->assume(extentMatchesSize, true);
415 assert(state);
416 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000417
Anna Zaks87cb5be2012-02-22 19:24:52 +0000418 return MallocUpdateRefState(C, CE, state);
419}
420
421ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
422 const CallExpr *CE,
423 ProgramStateRef state) {
424 // Get the return value.
425 SVal retVal = state->getSVal(CE, C.getLocationContext());
426
427 // We expect the malloc functions to return a pointer.
428 if (!isa<Loc>(retVal))
429 return 0;
430
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000431 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000432 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000433
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000434 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000435 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000436
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000437}
438
Anna Zaks87cb5be2012-02-22 19:24:52 +0000439ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
440 const CallExpr *CE,
441 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000442 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000443 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000444
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 Zaks87cb5be2012-02-22 19:24:52 +0000447 return FreeMemAux(C, CE, C.getState(), *I,
448 Att->getOwnKind() == OwnershipAttr::Holds);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000449 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000450 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000451}
452
Ted Kremenek8bef8232012-01-26 21:29:00 +0000453ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000454 const CallExpr *CE,
455 ProgramStateRef state,
456 unsigned Num,
457 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000458 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000459 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000460 if (!isa<DefinedOrUnknownSVal>(ArgVal))
461 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000462 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
463
464 // Check for null dereferences.
465 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000466 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000467
Anna Zaksb276bd92012-02-14 00:26:13 +0000468 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000469 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000470 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000471 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000472 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000473
Jordy Rose43859f62010-06-07 19:32:37 +0000474 // Unknown values could easily be okay
475 // Undefined values are handled elsewhere
476 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000477 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000478
Jordy Rose43859f62010-06-07 19:32:37 +0000479 const MemRegion *R = ArgVal.getAsRegion();
480
481 // Nonlocs can't be freed, of course.
482 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
483 if (!R) {
484 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000485 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000486 }
487
488 R = R->StripCasts();
489
490 // Blocks might show up as heap data, but should not be free()d
491 if (isa<BlockDataRegion>(R)) {
492 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000493 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000494 }
495
496 const MemSpaceRegion *MS = R->getMemorySpace();
497
498 // Parameters, locals, statics, and globals shouldn't be freed.
499 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
500 // FIXME: at the time this code was written, malloc() regions were
501 // represented by conjured symbols, which are all in UnknownSpaceRegion.
502 // This means that there isn't actually anything from HeapSpaceRegion
503 // that should be freed, even though we allow it here.
504 // Of course, free() can work on memory allocated outside the current
505 // function, so UnknownSpaceRegion is always a possibility.
506 // False negatives are better than false positives.
507
508 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000509 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000510 }
511
512 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
513 // Various cases could lead to non-symbol values here.
514 // For now, ignore them.
515 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000516 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000517
518 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000519 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000520
521 // If the symbol has not been tracked, return. This is possible when free() is
522 // called on a pointer that does not get its pointee directly from malloc().
523 // Full support of this requires inter-procedural analysis.
524 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000525 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000526
527 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000528 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000529 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000530 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000531 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000532 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000533 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000534 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000535 R->addRange(ArgExpr->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000536 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000537 C.EmitReport(R);
538 }
Anna Zaksb319e022012-02-08 20:13:28 +0000539 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000540 }
541
542 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000543 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000544 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
545 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000546}
547
Ted Kremenek9c378f72011-08-12 23:37:29 +0000548bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000549 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
550 os << "an integer (" << IntVal->getValue() << ")";
551 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
552 os << "a constant address (" << ConstAddr->getValue() << ")";
553 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000554 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000555 else
556 return false;
557
558 return true;
559}
560
Ted Kremenek9c378f72011-08-12 23:37:29 +0000561bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000562 const MemRegion *MR) {
563 switch (MR->getKind()) {
564 case MemRegion::FunctionTextRegionKind: {
565 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
566 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000567 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000568 else
569 os << "the address of a function";
570 return true;
571 }
572 case MemRegion::BlockTextRegionKind:
573 os << "block text";
574 return true;
575 case MemRegion::BlockDataRegionKind:
576 // FIXME: where the block came from?
577 os << "a block";
578 return true;
579 default: {
580 const MemSpaceRegion *MS = MR->getMemorySpace();
581
Anna Zakseb31a762012-01-04 23:54:01 +0000582 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000583 const VarRegion *VR = dyn_cast<VarRegion>(MR);
584 const VarDecl *VD;
585 if (VR)
586 VD = VR->getDecl();
587 else
588 VD = NULL;
589
590 if (VD)
591 os << "the address of the local variable '" << VD->getName() << "'";
592 else
593 os << "the address of a local stack variable";
594 return true;
595 }
Anna Zakseb31a762012-01-04 23:54:01 +0000596
597 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000598 const VarRegion *VR = dyn_cast<VarRegion>(MR);
599 const VarDecl *VD;
600 if (VR)
601 VD = VR->getDecl();
602 else
603 VD = NULL;
604
605 if (VD)
606 os << "the address of the parameter '" << VD->getName() << "'";
607 else
608 os << "the address of a parameter";
609 return true;
610 }
Anna Zakseb31a762012-01-04 23:54:01 +0000611
612 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000613 const VarRegion *VR = dyn_cast<VarRegion>(MR);
614 const VarDecl *VD;
615 if (VR)
616 VD = VR->getDecl();
617 else
618 VD = NULL;
619
620 if (VD) {
621 if (VD->isStaticLocal())
622 os << "the address of the static variable '" << VD->getName() << "'";
623 else
624 os << "the address of the global variable '" << VD->getName() << "'";
625 } else
626 os << "the address of a global variable";
627 return true;
628 }
Anna Zakseb31a762012-01-04 23:54:01 +0000629
630 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000631 }
632 }
633}
634
635void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000636 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000637 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000638 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000639 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000640
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000641 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000642 llvm::raw_svector_ostream os(buf);
643
644 const MemRegion *MR = ArgVal.getAsRegion();
645 if (MR) {
646 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
647 MR = ER->getSuperRegion();
648
649 // Special case for alloca()
650 if (isa<AllocaRegion>(MR))
651 os << "Argument to free() was allocated by alloca(), not malloc()";
652 else {
653 os << "Argument to free() is ";
654 if (SummarizeRegion(os, MR))
655 os << ", which is not memory allocated by malloc()";
656 else
657 os << "not memory allocated by malloc()";
658 }
659 } else {
660 os << "Argument to free() is ";
661 if (SummarizeValue(os, ArgVal))
662 os << ", which is not memory allocated by malloc()";
663 else
664 os << "not memory allocated by malloc()";
665 }
666
Anna Zakse172e8b2011-08-17 23:00:25 +0000667 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000668 R->addRange(range);
669 C.EmitReport(R);
670 }
671}
672
Anna Zaks87cb5be2012-02-22 19:24:52 +0000673ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
674 const CallExpr *CE,
675 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000676 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000677 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000678 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000679 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
680 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000681 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000682 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000683
Ted Kremenek846eabd2010-12-01 21:28:31 +0000684 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000685
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000686 DefinedOrUnknownSVal PtrEQ =
687 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000688
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000689 // Get the size argument. If there is no size arg then give up.
690 const Expr *Arg1 = CE->getArg(1);
691 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000692 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000693
694 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000695 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
696 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000697 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000698 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000699
700 // Compare the size argument to 0.
701 DefinedOrUnknownSVal SizeZero =
702 svalBuilder.evalEQ(state, Arg1Val,
703 svalBuilder.makeIntValWithPtrWidth(0, false));
704
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000705 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
706 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
707 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
708 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
709 // We only assume exceptional states if they are definitely true; if the
710 // state is under-constrained, assume regular realloc behavior.
711 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
712 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
713
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000714 // If the ptr is NULL and the size is not 0, the call is equivalent to
715 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000716 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000717 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000718 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000719 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000720 }
721
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000722 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000723 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000724
Anna Zaks30838b92012-02-13 20:57:07 +0000725 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000726 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000727 SymbolRef FromPtr = arg0Val.getAsSymbol();
728 SVal RetVal = state->getSVal(CE, LCtx);
729 SymbolRef ToPtr = RetVal.getAsSymbol();
730 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000731 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000732
733 // If the size is 0, free the memory.
734 if (SizeIsZero)
735 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000736 // The semantics of the return value are:
737 // If size was equal to 0, either NULL or a pointer suitable to be passed
738 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000739 stateFree = stateFree->set<ReallocPairs>(ToPtr,
740 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000741 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000742 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000743 }
744
745 // Default behavior.
746 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
747 // FIXME: We should copy the content of the original buffer.
748 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
749 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000750 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000751 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000752 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
753 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000754 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000755 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000756 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000757 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000758}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000759
Anna Zaks87cb5be2012-02-22 19:24:52 +0000760ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Ted Kremenek8bef8232012-01-26 21:29:00 +0000761 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000762 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000763 const LocationContext *LCtx = C.getLocationContext();
764 SVal count = state->getSVal(CE->getArg(0), LCtx);
765 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000766 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
767 svalBuilder.getContext().getSizeType());
768 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000769
Anna Zaks87cb5be2012-02-22 19:24:52 +0000770 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000771}
772
Anna Zaksca8e36e2012-02-23 21:38:21 +0000773const Stmt *
774MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
775 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000776 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000777 // Walk the ExplodedGraph backwards and find the first node that referred to
778 // the tracked symbol.
779 const ExplodedNode *AllocNode = N;
780
781 while (N) {
782 if (!N->getState()->get<RegionState>(Sym))
783 break;
Anna Zaks7752d292012-02-27 23:40:55 +0000784 // Allocation node, is the last node in the current context in which the
785 // symbol was tracked.
786 if (N->getLocationContext() == LeakContext)
787 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000788 N = N->pred_empty() ? NULL : *(N->pred_begin());
789 }
790
791 ProgramPoint P = AllocNode->getLocation();
Anna Zaks7752d292012-02-27 23:40:55 +0000792 if (!isa<StmtPoint>(P))
793 return 0;
794
795 return cast<StmtPoint>(P).getStmt();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000796}
797
Anna Zaksda046772012-02-11 21:02:40 +0000798void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
799 CheckerContext &C) const {
800 assert(N);
801 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000802 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000803 // Leaks should not be reported if they are post-dominated by a sink:
804 // (1) Sinks are higher importance bugs.
805 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
806 // with __noreturn functions such as assert() or exit(). We choose not
807 // to report leaks on such paths.
808 BT_Leak->setSuppressOnSink(true);
809 }
810
Anna Zaksca8e36e2012-02-23 21:38:21 +0000811 // Most bug reports are cached at the location where they occurred.
812 // With leaks, we want to unique them by the location where they were
813 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000814 PathDiagnosticLocation LocUsedForUniqueing;
815 if (const Stmt *AllocStmt = getAllocationSite(N, Sym, C))
816 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
817 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000818
Anna Zaksfebdc322012-02-16 22:26:12 +0000819 BugReport *R = new BugReport(*BT_Leak,
Anna Zaksca8e36e2012-02-23 21:38:21 +0000820 "Memory is never released; potential memory leak", N, LocUsedForUniqueing);
Anna Zaksda046772012-02-11 21:02:40 +0000821 R->addVisitor(new MallocBugVisitor(Sym));
822 C.EmitReport(R);
823}
824
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000825void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
826 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000827{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000828 if (!SymReaper.hasDeadSymbols())
829 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000830
Ted Kremenek8bef8232012-01-26 21:29:00 +0000831 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000832 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000833 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000834
Ted Kremenek217470e2011-07-28 23:07:51 +0000835 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000836 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000837 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
838 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000839 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000840 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000841 Errors.push_back(I->first);
842 }
Jordy Rose90760142010-08-18 04:33:47 +0000843 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000844 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000845
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000846 }
847 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000848
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000849 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000850 ReallocMap RP = state->get<ReallocPairs>();
851 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
852 if (SymReaper.isDead(I->first) ||
853 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000854 state = state->remove<ReallocPairs>(I->first);
855 }
856 }
857
Anna Zaksca8e36e2012-02-23 21:38:21 +0000858 // Generate leak node.
859 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
860 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000861
Anna Zaksca8e36e2012-02-23 21:38:21 +0000862 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000863 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000864 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
865 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000866 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000867 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000868 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000869}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000870
Anna Zaksda046772012-02-11 21:02:40 +0000871void MallocChecker::checkEndPath(CheckerContext &C) const {
872 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000873 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000874
Anna Zaksa19581a2012-02-20 22:25:23 +0000875 // If inside inlined call, skip it.
876 if (C.getLocationContext()->getParent() != 0)
877 return;
878
Jordy Rose09cef092010-08-18 04:26:59 +0000879 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000880 RefState RS = I->second;
881 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000882 ExplodedNode *N = C.addTransition(state);
883 if (N)
884 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000885 }
886 }
887}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000888
Anna Zaks91c2a112012-02-08 23:16:56 +0000889bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
890 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000891 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000892 const RefState *RS = state->get<RegionState>(Sym);
893 if (!RS)
894 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000895
Anna Zaks91c2a112012-02-08 23:16:56 +0000896 if (RS->isAllocated()) {
897 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
898 C.addTransition(state);
899 return true;
900 }
901 return false;
902}
903
Anna Zaks66c40402012-02-14 21:55:24 +0000904void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
905 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
906 return;
907
908 // Check use after free, when a freed pointer is passed to a call.
909 ProgramStateRef State = C.getState();
910 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
911 E = CE->arg_end(); I != E; ++I) {
912 const Expr *A = *I;
913 if (A->getType().getTypePtr()->isAnyPointerType()) {
914 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
915 if (!Sym)
916 continue;
917 if (checkUseAfterFree(Sym, C, A))
918 return;
919 }
920 }
921}
922
Anna Zaks91c2a112012-02-08 23:16:56 +0000923void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
924 const Expr *E = S->getRetValue();
925 if (!E)
926 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000927
928 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +0000929 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
930 SymbolRef Sym = RetVal.getAsSymbol();
931 if (!Sym)
932 // If we are returning a field of the allocated struct or an array element,
933 // the callee could still free the memory.
934 // TODO: This logic should be a part of generic symbol escape callback.
935 if (const MemRegion *MR = RetVal.getAsRegion())
936 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
937 if (const SymbolicRegion *BMR =
938 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
939 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000940 if (!Sym)
941 return;
942
Anna Zaks0860cd02012-02-11 21:44:39 +0000943 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +0000944 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +0000945 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000946
Anna Zaksa19581a2012-02-20 22:25:23 +0000947 // If this function body is not inlined, check if the symbol is escaping.
948 if (C.getLocationContext()->getParent() == 0)
949 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000950}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000951
Anna Zaks91c2a112012-02-08 23:16:56 +0000952bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
953 const Stmt *S) const {
954 assert(Sym);
955 const RefState *RS = C.getState()->get<RegionState>(Sym);
956 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000957 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000958 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000959 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +0000960
Anna Zaksfebdc322012-02-16 22:26:12 +0000961 BugReport *R = new BugReport(*BT_UseFree,
962 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +0000963 if (S)
964 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000965 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000966 C.EmitReport(R);
967 return true;
968 }
969 }
970 return false;
971}
972
Zhongxing Xuc8023782010-03-10 04:58:55 +0000973// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000974void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
975 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000976 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000977 if (Sym)
978 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000979}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000980
Anna Zaks4fb54872012-02-11 21:02:35 +0000981//===----------------------------------------------------------------------===//
982// Check various ways a symbol can be invalidated.
983// TODO: This logic (the next 3 functions) is copied/similar to the
984// RetainRelease checker. We might want to factor this out.
985//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000986
Anna Zaks4fb54872012-02-11 21:02:35 +0000987// Stop tracking symbols when a value escapes as a result of checkBind.
988// A value escapes in three possible cases:
989// (1) we are binding to something that is not a memory region.
990// (2) we are binding to a memregion that does not have stack storage
991// (3) we are binding to a memregion with stack storage that the store
992// does not understand.
993void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
994 CheckerContext &C) const {
995 // Are we storing to something that causes the value to "escape"?
996 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000997 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000998
Anna Zaks4fb54872012-02-11 21:02:35 +0000999 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1000 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001001
Anna Zaks4fb54872012-02-11 21:02:35 +00001002 if (!escapes) {
1003 // To test (3), generate a new state with the binding added. If it is
1004 // the same state, then it escapes (since the store cannot represent
1005 // the binding).
1006 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001007 }
Anna Zaksac593002012-02-16 03:40:57 +00001008 if (!escapes) {
1009 // Case 4: We do not currently model what happens when a symbol is
1010 // assigned to a struct field, so be conservative here and let the symbol
1011 // go. TODO: This could definitely be improved upon.
1012 escapes = !isa<VarRegion>(regionLoc->getRegion());
1013 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001014 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001015
1016 // If our store can represent the binding and we aren't storing to something
1017 // that doesn't have local storage then just return and have the simulation
1018 // state continue as is.
1019 if (!escapes)
1020 return;
1021
1022 // Otherwise, find all symbols referenced by 'val' that we are tracking
1023 // and stop tracking them.
1024 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1025 C.addTransition(state);
1026}
1027
1028// If a symbolic region is assumed to NULL (or another constant), stop tracking
1029// it - assuming that allocation failed on this path.
1030ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1031 SVal Cond,
1032 bool Assumption) const {
1033 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001034 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1035 // If the symbol is assumed to NULL or another constant, this will
1036 // return an APSInt*.
1037 if (state->getSymVal(I.getKey()))
1038 state = state->remove<RegionState>(I.getKey());
1039 }
1040
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001041 // Realloc returns 0 when reallocation fails, which means that we should
1042 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001043 ReallocMap RP = state->get<ReallocPairs>();
1044 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001045 // If the symbol is assumed to NULL or another constant, this will
1046 // return an APSInt*.
1047 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001048 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1049 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001050 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001051 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1052 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001053 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001054 }
1055 state = state->remove<ReallocPairs>(I.getKey());
1056 }
1057 }
1058
Anna Zaks4fb54872012-02-11 21:02:35 +00001059 return state;
1060}
1061
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001062// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001063// conservatively assume it can free/reallocate it's pointer arguments.
1064// (We assume that the pointers cannot escape through calls to system
1065// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001066bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1067 ProgramStateRef State) const {
1068 if (!Call)
1069 return false;
1070
1071 // For now, assume that any C++ call can free memory.
1072 // TODO: If we want to be more optimistic here, we'll need to make sure that
1073 // regions escape to C++ containers. They seem to do that even now, but for
1074 // mysterious reasons.
1075 if (Call->isCXXCall())
1076 return false;
1077
1078 const Decl *D = Call->getDecl();
1079 if (!D)
1080 return false;
1081
Anna Zaks66c40402012-02-14 21:55:24 +00001082 ASTContext &ASTC = State->getStateManager().getContext();
1083
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001084 // If it's one of the allocation functions we can reason about, we model
1085 // it's behavior explicitly.
1086 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1087 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001088 }
1089
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001090 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001091 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001092 if (!SM.isInSystemHeader(D->getLocation()))
1093 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001094
Anna Zaks07d39a42012-02-28 01:54:22 +00001095 // Process C/ObjC functions.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001096 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001097 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001098 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001099 if (!II)
1100 return true;
1101 StringRef FName = II->getName();
1102
1103 // White list thread local storage.
1104 if (FName.equals("pthread_setspecific"))
1105 return false;
1106
1107 // White list the 'XXXNoCopy' ObjC Methods.
1108 if (FName.endswith("NoCopy")) {
1109 // Look for the deallocator argument. We know that the memory ownership
1110 // is not transfered only if the deallocator argument is
1111 // 'kCFAllocatorNull'.
1112 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1113 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1114 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1115 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1116 if (DeallocatorName == "kCFAllocatorNull")
1117 return true;
1118 }
1119 }
1120 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001121 }
1122
Anna Zaksca23eb22012-02-29 18:42:47 +00001123 // PR12101
1124 // Many CoreFoundation and CoreGraphics might allow a tracked object
1125 // to escape.
1126 if (Call->isCFCGAllowingEscape(FName))
1127 return false;
1128
1129 // Associating streams with malloced buffers. The pointer can escape if
1130 // 'closefn' is specified (and if that function does free memory).
1131 // Currently, we do not inspect the 'closefn' function (PR12101).
1132 if (FName == "funopen")
1133 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1134 return false;
1135
1136 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1137 // these leaks might be intentional when setting the buffer for stdio.
1138 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1139 if (FName == "setbuf" || FName =="setbuffer" ||
1140 FName == "setlinebuf" || FName == "setvbuf") {
1141 if (Call->getNumArgs() >= 1)
1142 if (const DeclRefExpr *Arg =
1143 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1144 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1145 if (D->getCanonicalDecl()->getName().find("std")
1146 != StringRef::npos)
1147 return false;
1148 }
1149
1150 // A bunch of other functions, which take ownership of a pointer (See retain
1151 // release checker). Not all the parameters here are invalidated, but the
1152 // Malloc checker cannot differentiate between them. The right way of doing
1153 // this would be to implement a pointer escapes callback.
1154 if (FName == "CVPixelBufferCreateWithBytes" ||
1155 FName == "CGBitmapContextCreateWithData" ||
1156 FName == "CVPixelBufferCreateWithPlanarBytes") {
1157 return false;
1158 }
1159
Anna Zaks0d389b82012-02-23 01:05:27 +00001160 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001161 // Most system calls, do not free the memory.
1162 return true;
1163
1164 // Process ObjC functions.
1165 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1166 Selector S = ObjCD->getSelector();
1167
1168 // White list the ObjC functions which do free memory.
1169 // - Anything containing 'freeWhenDone' param set to 1.
1170 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1171 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1172 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1173 if (Call->getArgSVal(i).isConstant(1))
1174 return false;
1175 }
1176 }
1177
1178 // Otherwise, assume that the function does not free memory.
1179 // Most system calls, do not free the memory.
1180 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001181 }
1182
1183 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001184 return false;
1185
Anna Zaks66c40402012-02-14 21:55:24 +00001186}
1187
Anna Zaks4fb54872012-02-11 21:02:35 +00001188// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1189// escapes, when we are tracking p), do not track the symbol as we cannot reason
1190// about it anymore.
1191ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001192MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001193 const StoreManager::InvalidatedSymbols *invalidated,
1194 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001195 ArrayRef<const MemRegion *> Regions,
1196 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001197 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001198 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001199 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001200
Anna Zaks66c40402012-02-14 21:55:24 +00001201 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001202 // regions (explicit and implicit) escaped.
1203
1204 // Otherwise, whitelist explicit pointers; we still can track them.
1205 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001206 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1207 E = ExplicitRegions.end(); I != E; ++I) {
1208 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1209 WhitelistedSymbols.insert(R->getSymbol());
1210 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001211 }
1212
1213 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1214 E = invalidated->end(); I!=E; ++I) {
1215 SymbolRef sym = *I;
1216 if (WhitelistedSymbols.count(sym))
1217 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001218 // The symbol escaped.
1219 if (const RefState *RS = State->get<RegionState>(sym))
1220 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001221 }
Anna Zaks66c40402012-02-14 21:55:24 +00001222 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001223}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001224
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001225PathDiagnosticPiece *
1226MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1227 const ExplodedNode *PrevN,
1228 BugReporterContext &BRC,
1229 BugReport &BR) {
1230 const RefState *RS = N->getState()->get<RegionState>(Sym);
1231 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1232 if (!RS && !RSPrev)
1233 return 0;
1234
Anna Zaksfe571602012-02-16 22:26:07 +00001235 const Stmt *S = 0;
1236 const char *Msg = 0;
1237
1238 // Retrieve the associated statement.
1239 ProgramPoint ProgLoc = N->getLocation();
1240 if (isa<StmtPoint>(ProgLoc))
1241 S = cast<StmtPoint>(ProgLoc).getStmt();
1242 // If an assumption was made on a branch, it should be caught
1243 // here by looking at the state transition.
1244 if (isa<BlockEdge>(ProgLoc)) {
1245 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1246 S = srcBlk->getTerminator();
1247 }
1248 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001249 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001250
1251 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001252 if (Mode == Normal) {
1253 if (isAllocated(RS, RSPrev, S))
1254 Msg = "Memory is allocated";
1255 else if (isReleased(RS, RSPrev, S))
1256 Msg = "Memory is released";
1257 else if (isReallocFailedCheck(RS, RSPrev, S)) {
1258 Mode = ReallocationFailed;
1259 Msg = "Reallocation failed";
1260 }
1261
1262 // We are in a special mode if a reallocation failed later in the path.
1263 } else if (Mode == ReallocationFailed) {
1264 // Generate a special diagnostic for the first realloc we find.
1265 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1266 return 0;
1267
1268 // Check that the name of the function is realloc.
1269 const CallExpr *CE = dyn_cast<CallExpr>(S);
1270 if (!CE)
1271 return 0;
1272 const FunctionDecl *funDecl = CE->getDirectCallee();
1273 if (!funDecl)
1274 return 0;
1275 StringRef FunName = funDecl->getName();
1276 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1277 return 0;
1278 Msg = "Attempt to reallocate memory";
1279 Mode = Normal;
1280 }
1281
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001282 if (!Msg)
1283 return 0;
1284
1285 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001286 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001287 N->getLocationContext());
1288 return new PathDiagnosticEventPiece(Pos, Msg);
1289}
1290
1291
Anna Zaks231361a2012-02-08 23:16:52 +00001292#define REGISTER_CHECKER(name) \
1293void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001294 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001295 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001296}
Anna Zaks231361a2012-02-08 23:16:52 +00001297
1298REGISTER_CHECKER(MallocPessimistic)
1299REGISTER_CHECKER(MallocOptimistic)