blob: 99b84897a5931e0b9fb466e4c7d2327792507ee2 [file] [log] [blame]
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines malloc/free checker, which checks for potential memory
11// leaks, double free, and use-after-free problems.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000017#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000018#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaks66c40402012-02-14 21:55:24 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Anna Zaks15d0ae12012-02-11 23:46:36 +000025#include "clang/Basic/SourceManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000026#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000027#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000029#include <climits>
30
Zhongxing Xu589c0f22009-11-12 08:38:56 +000031using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000032using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000033
34namespace {
35
Zhongxing Xu7fb14642009-12-11 00:55:44 +000036class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000037 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
38 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000039 const Stmt *S;
40
Zhongxing Xu7fb14642009-12-11 00:55:44 +000041public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000042 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
43
Zhongxing Xub94b81a2009-12-31 06:13:07 +000044 bool isAllocated() const { return K == AllocateUnchecked; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000045 bool isReleased() const { return K == Released; }
Anna Zaksca23eb22012-02-29 18:42:47 +000046
Anna Zaksc8bb3be2012-02-13 18:05:39 +000047 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000048
49 bool operator==(const RefState &X) const {
50 return K == X.K && S == X.S;
51 }
52
Zhongxing Xub94b81a2009-12-31 06:13:07 +000053 static RefState getAllocateUnchecked(const Stmt *s) {
54 return RefState(AllocateUnchecked, s);
55 }
56 static RefState getAllocateFailed() {
57 return RefState(AllocateFailed, 0);
58 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000059 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
60 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000061 static RefState getRelinquished(const Stmt *s) {
62 return RefState(Relinquished, s);
63 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064
65 void Profile(llvm::FoldingSetNodeID &ID) const {
66 ID.AddInteger(K);
67 ID.AddPointer(S);
68 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000069};
70
Anna Zaks40add292012-02-15 00:11:25 +000071struct ReallocPair {
72 SymbolRef ReallocatedSym;
73 bool IsFreeOnFailure;
74 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
75 void Profile(llvm::FoldingSetNodeID &ID) const {
76 ID.AddInteger(IsFreeOnFailure);
77 ID.AddPointer(ReallocatedSym);
78 }
79 bool operator==(const ReallocPair &X) const {
80 return ReallocatedSym == X.ReallocatedSym &&
81 IsFreeOnFailure == X.IsFreeOnFailure;
82 }
83};
84
Anna Zaksb319e022012-02-08 20:13:28 +000085class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000086 check::EndPath,
87 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000088 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000089 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000090 check::Location,
91 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000092 eval::Assume,
93 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000094{
Anna Zaksfebdc322012-02-16 22:26:12 +000095 mutable OwningPtr<BugType> BT_DoubleFree;
96 mutable OwningPtr<BugType> BT_Leak;
97 mutable OwningPtr<BugType> BT_UseFree;
98 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +000099 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000100 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
101
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000102public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000103 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000104 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000105
106 /// In pessimistic mode, the checker assumes that it does not know which
107 /// functions might free the memory.
108 struct ChecksFilter {
109 DefaultBool CMallocPessimistic;
110 DefaultBool CMallocOptimistic;
111 };
112
113 ChecksFilter Filter;
114
Anna Zaks66c40402012-02-14 21:55:24 +0000115 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000116 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000117 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000118 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000119 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000120 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000121 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000122 void checkLocation(SVal l, bool isLoad, const Stmt *S,
123 CheckerContext &C) const;
124 void checkBind(SVal location, SVal val, const Stmt*S,
125 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000126 ProgramStateRef
127 checkRegionChanges(ProgramStateRef state,
128 const StoreManager::InvalidatedSymbols *invalidated,
129 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000130 ArrayRef<const MemRegion *> Regions,
131 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000132 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
133 return true;
134 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000135
Zhongxing Xu7b760962009-11-13 07:25:27 +0000136private:
Anna Zaks66c40402012-02-14 21:55:24 +0000137 void initIdentifierInfo(ASTContext &C) const;
138
139 /// Check if this is one of the functions which can allocate/reallocate memory
140 /// pointed to by one of its arguments.
141 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
142
Anna Zaks87cb5be2012-02-22 19:24:52 +0000143 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
144 const CallExpr *CE,
145 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000146 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000147 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000148 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000149 return MallocMemAux(C, CE,
150 state->getSVal(SizeEx, C.getLocationContext()),
151 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000152 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000153
Ted Kremenek8bef8232012-01-26 21:29:00 +0000154 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000155 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000156 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000157
Anna Zaks87cb5be2012-02-22 19:24:52 +0000158 /// Update the RefState to reflect the new memory allocation.
159 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
160 const CallExpr *CE,
161 ProgramStateRef state);
162
163 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
164 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000165 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
166 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000167 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000168
Anna Zaks87cb5be2012-02-22 19:24:52 +0000169 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
170 bool FreesMemOnFailure) const;
171 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000172
Anna Zaks91c2a112012-02-08 23:16:56 +0000173 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
174 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
175 const Stmt *S = 0) const;
176
Anna Zaks66c40402012-02-14 21:55:24 +0000177 /// Check if the function is not known to us. So, for example, we could
178 /// conservatively assume it can free/reallocate it's pointer arguments.
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000179 bool doesNotFreeMemory(const CallOrObjCMessage *Call,
180 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000181
Ted Kremenek9c378f72011-08-12 23:37:29 +0000182 static bool SummarizeValue(raw_ostream &os, SVal V);
183 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000184 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000185
Anna Zaksca8e36e2012-02-23 21:38:21 +0000186 /// Find the location of the allocation for Sym on the path leading to the
187 /// exploded node N.
188 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
189 CheckerContext &C) const;
190
Anna Zaksda046772012-02-11 21:02:40 +0000191 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
192
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000193 /// The bug visitor which allows us to print extra diagnostics along the
194 /// BugReport path. For example, showing the allocation site of the leaked
195 /// region.
196 class MallocBugVisitor : public BugReporterVisitor {
197 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000198 enum NotificationMode {
199 Normal,
200 Complete,
201 ReallocationFailed
202 };
203
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000204 // The allocated region symbol tracked by the main analysis.
205 SymbolRef Sym;
Anna Zaksfe571602012-02-16 22:26:07 +0000206 NotificationMode Mode;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000207
208 public:
Anna Zaksfe571602012-02-16 22:26:07 +0000209 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000210 virtual ~MallocBugVisitor() {}
211
212 void Profile(llvm::FoldingSetNodeID &ID) const {
213 static int X = 0;
214 ID.AddPointer(&X);
215 ID.AddPointer(Sym);
216 }
217
Anna Zaksfe571602012-02-16 22:26:07 +0000218 inline bool isAllocated(const RefState *S, const RefState *SPrev,
219 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000220 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000221 return (Stmt && isa<CallExpr>(Stmt) &&
222 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000223 }
224
Anna Zaksfe571602012-02-16 22:26:07 +0000225 inline bool isReleased(const RefState *S, const RefState *SPrev,
226 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000227 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000228 return (Stmt && isa<CallExpr>(Stmt) &&
229 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
230 }
231
232 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
233 const Stmt *Stmt) {
234 // If the expression is not a call, and the state change is
235 // released -> allocated, it must be the realloc return value
236 // check. If we have to handle more cases here, it might be cleaner just
237 // to track this extra bit in the state itself.
238 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
239 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000240 }
241
242 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
243 const ExplodedNode *PrevN,
244 BugReporterContext &BRC,
245 BugReport &BR);
Anna Zaks56a938f2012-03-16 23:24:20 +0000246 private:
247 class StackHintGeneratorForReallocationFailed
248 : public StackHintGeneratorForSymbol {
249 public:
250 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
251 : StackHintGeneratorForSymbol(S, M) {}
252
253 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
254 SmallString<200> buf;
255 llvm::raw_svector_ostream os(buf);
256
Anna Zaksfbd58742012-03-16 23:44:28 +0000257 os << "Reallocation of ";
Anna Zaks56a938f2012-03-16 23:24:20 +0000258 // Printed parameters start at 1, not 0.
259 printOrdinal(++ArgIndex, os);
260 os << " parameter failed";
261
262 return os.str();
263 }
264
265 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000266 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000267 }
268 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000269 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000270};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000271} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000272
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000273typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000274typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000275class RegionState {};
276class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000277namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000278namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000279 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000280 struct ProgramStateTrait<RegionState>
281 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000282 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000283 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000284
285 template <>
286 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000287 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000288 static void *GDMIndex() { static int x; return &x; }
289 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000290}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000291}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000292
Anna Zaks4fb54872012-02-11 21:02:35 +0000293namespace {
294class StopTrackingCallback : public SymbolVisitor {
295 ProgramStateRef state;
296public:
297 StopTrackingCallback(ProgramStateRef st) : state(st) {}
298 ProgramStateRef getState() const { return state; }
299
300 bool VisitSymbol(SymbolRef sym) {
301 state = state->remove<RegionState>(sym);
302 return true;
303 }
304};
305} // end anonymous namespace
306
Anna Zaks66c40402012-02-14 21:55:24 +0000307void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000308 if (!II_malloc)
309 II_malloc = &Ctx.Idents.get("malloc");
310 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000311 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000312 if (!II_realloc)
313 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000314 if (!II_reallocf)
315 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000316 if (!II_calloc)
317 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000318 if (!II_valloc)
319 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaks60a1fa42012-02-22 03:14:20 +0000320 if (!II_strdup)
321 II_strdup = &Ctx.Idents.get("strdup");
322 if (!II_strndup)
323 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000324}
325
Anna Zaks66c40402012-02-14 21:55:24 +0000326bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000327 if (!FD)
328 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000329 IdentifierInfo *FunI = FD->getIdentifier();
330 if (!FunI)
331 return false;
332
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000333 initIdentifierInfo(C);
334
Anna Zaks40add292012-02-15 00:11:25 +0000335 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000336 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
337 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000338 return true;
339
340 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
341 FD->specific_attr_begin<OwnershipAttr>() !=
342 FD->specific_attr_end<OwnershipAttr>())
343 return true;
344
345
346 return false;
347}
348
Anna Zaksb319e022012-02-08 20:13:28 +0000349void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
350 const FunctionDecl *FD = C.getCalleeDecl(CE);
351 if (!FD)
352 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000353
Anna Zaksb16ce452012-02-15 00:11:22 +0000354 initIdentifierInfo(C.getASTContext());
355 IdentifierInfo *FunI = FD->getIdentifier();
356 if (!FunI)
357 return;
358
Anna Zaks87cb5be2012-02-22 19:24:52 +0000359 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000360 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000361 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000362 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000363 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000364 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000365 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000366 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000367 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000368 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000369 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000370 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000371 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000372 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000373 State = MallocUpdateRefState(C, CE, State);
374 } else if (Filter.CMallocOptimistic) {
375 // Check all the attributes, if there are any.
376 // There can be multiple of these attributes.
377 if (FD->hasAttrs())
378 for (specific_attr_iterator<OwnershipAttr>
379 i = FD->specific_attr_begin<OwnershipAttr>(),
380 e = FD->specific_attr_end<OwnershipAttr>();
381 i != e; ++i) {
382 switch ((*i)->getOwnKind()) {
383 case OwnershipAttr::Returns:
384 State = MallocMemReturnsAttr(C, CE, *i);
385 break;
386 case OwnershipAttr::Takes:
387 case OwnershipAttr::Holds:
388 State = FreeMemAttr(C, CE, *i);
389 break;
390 }
391 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000392 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000393 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000394}
395
Anna Zaks87cb5be2012-02-22 19:24:52 +0000396ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
397 const CallExpr *CE,
398 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000399 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000400 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000401
Sean Huntcf807c42010-08-18 23:23:40 +0000402 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000403 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000404 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000405 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000406 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000407}
408
Anna Zaksb319e022012-02-08 20:13:28 +0000409ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000410 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000411 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000412 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000413 // Get the return value.
414 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000415
Anna Zaksb16ce452012-02-15 00:11:22 +0000416 // We expect the malloc functions to return a pointer.
417 if (!isa<Loc>(retVal))
418 return 0;
419
Jordy Rose32f26562010-07-04 00:00:41 +0000420 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000421 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000422
Jordy Rose32f26562010-07-04 00:00:41 +0000423 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000424 const SymbolicRegion *R =
425 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000426 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000427 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000428 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000429 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000430 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
431 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
432 DefinedOrUnknownSVal extentMatchesSize =
433 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000434
Anna Zaks60a1fa42012-02-22 03:14:20 +0000435 state = state->assume(extentMatchesSize, true);
436 assert(state);
437 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000438
Anna Zaks87cb5be2012-02-22 19:24:52 +0000439 return MallocUpdateRefState(C, CE, state);
440}
441
442ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
443 const CallExpr *CE,
444 ProgramStateRef state) {
445 // Get the return value.
446 SVal retVal = state->getSVal(CE, C.getLocationContext());
447
448 // We expect the malloc functions to return a pointer.
449 if (!isa<Loc>(retVal))
450 return 0;
451
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000452 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000453 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000454
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000455 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000456 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000457
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000458}
459
Anna Zaks87cb5be2012-02-22 19:24:52 +0000460ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
461 const CallExpr *CE,
462 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000463 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000464 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000465
Anna Zaksb3d72752012-03-01 22:06:06 +0000466 ProgramStateRef State = C.getState();
467
Sean Huntcf807c42010-08-18 23:23:40 +0000468 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
469 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000470 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
471 Att->getOwnKind() == OwnershipAttr::Holds);
472 if (StateI)
473 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000474 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000475 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000476}
477
Ted Kremenek8bef8232012-01-26 21:29:00 +0000478ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000479 const CallExpr *CE,
480 ProgramStateRef state,
481 unsigned Num,
482 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000483 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000484 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000485 if (!isa<DefinedOrUnknownSVal>(ArgVal))
486 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000487 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
488
489 // Check for null dereferences.
490 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000491 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000492
Anna Zaksb276bd92012-02-14 00:26:13 +0000493 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000494 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000495 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000496 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000497 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000498
Jordy Rose43859f62010-06-07 19:32:37 +0000499 // Unknown values could easily be okay
500 // Undefined values are handled elsewhere
501 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000502 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000503
Jordy Rose43859f62010-06-07 19:32:37 +0000504 const MemRegion *R = ArgVal.getAsRegion();
505
506 // Nonlocs can't be freed, of course.
507 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
508 if (!R) {
509 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000510 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000511 }
512
513 R = R->StripCasts();
514
515 // Blocks might show up as heap data, but should not be free()d
516 if (isa<BlockDataRegion>(R)) {
517 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000518 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000519 }
520
521 const MemSpaceRegion *MS = R->getMemorySpace();
522
523 // Parameters, locals, statics, and globals shouldn't be freed.
524 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
525 // FIXME: at the time this code was written, malloc() regions were
526 // represented by conjured symbols, which are all in UnknownSpaceRegion.
527 // This means that there isn't actually anything from HeapSpaceRegion
528 // that should be freed, even though we allow it here.
529 // Of course, free() can work on memory allocated outside the current
530 // function, so UnknownSpaceRegion is always a possibility.
531 // False negatives are better than false positives.
532
533 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000534 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000535 }
536
537 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
538 // Various cases could lead to non-symbol values here.
539 // For now, ignore them.
540 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000541 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000542
543 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000544 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000545
546 // If the symbol has not been tracked, return. This is possible when free() is
547 // called on a pointer that does not get its pointee directly from malloc().
548 // Full support of this requires inter-procedural analysis.
549 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000550 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000551
552 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000553 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000554 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000555 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000556 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000557 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000558 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000559 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000560 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000561 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000562 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000563 C.EmitReport(R);
564 }
Anna Zaksb319e022012-02-08 20:13:28 +0000565 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000566 }
567
568 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000569 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000570 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
571 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000572}
573
Ted Kremenek9c378f72011-08-12 23:37:29 +0000574bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000575 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
576 os << "an integer (" << IntVal->getValue() << ")";
577 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
578 os << "a constant address (" << ConstAddr->getValue() << ")";
579 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000580 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000581 else
582 return false;
583
584 return true;
585}
586
Ted Kremenek9c378f72011-08-12 23:37:29 +0000587bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000588 const MemRegion *MR) {
589 switch (MR->getKind()) {
590 case MemRegion::FunctionTextRegionKind: {
591 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
592 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000593 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000594 else
595 os << "the address of a function";
596 return true;
597 }
598 case MemRegion::BlockTextRegionKind:
599 os << "block text";
600 return true;
601 case MemRegion::BlockDataRegionKind:
602 // FIXME: where the block came from?
603 os << "a block";
604 return true;
605 default: {
606 const MemSpaceRegion *MS = MR->getMemorySpace();
607
Anna Zakseb31a762012-01-04 23:54:01 +0000608 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000609 const VarRegion *VR = dyn_cast<VarRegion>(MR);
610 const VarDecl *VD;
611 if (VR)
612 VD = VR->getDecl();
613 else
614 VD = NULL;
615
616 if (VD)
617 os << "the address of the local variable '" << VD->getName() << "'";
618 else
619 os << "the address of a local stack variable";
620 return true;
621 }
Anna Zakseb31a762012-01-04 23:54:01 +0000622
623 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000624 const VarRegion *VR = dyn_cast<VarRegion>(MR);
625 const VarDecl *VD;
626 if (VR)
627 VD = VR->getDecl();
628 else
629 VD = NULL;
630
631 if (VD)
632 os << "the address of the parameter '" << VD->getName() << "'";
633 else
634 os << "the address of a parameter";
635 return true;
636 }
Anna Zakseb31a762012-01-04 23:54:01 +0000637
638 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000639 const VarRegion *VR = dyn_cast<VarRegion>(MR);
640 const VarDecl *VD;
641 if (VR)
642 VD = VR->getDecl();
643 else
644 VD = NULL;
645
646 if (VD) {
647 if (VD->isStaticLocal())
648 os << "the address of the static variable '" << VD->getName() << "'";
649 else
650 os << "the address of the global variable '" << VD->getName() << "'";
651 } else
652 os << "the address of a global variable";
653 return true;
654 }
Anna Zakseb31a762012-01-04 23:54:01 +0000655
656 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000657 }
658 }
659}
660
661void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000662 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000663 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000664 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000665 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000666
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000667 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000668 llvm::raw_svector_ostream os(buf);
669
670 const MemRegion *MR = ArgVal.getAsRegion();
671 if (MR) {
672 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
673 MR = ER->getSuperRegion();
674
675 // Special case for alloca()
676 if (isa<AllocaRegion>(MR))
677 os << "Argument to free() was allocated by alloca(), not malloc()";
678 else {
679 os << "Argument to free() is ";
680 if (SummarizeRegion(os, MR))
681 os << ", which is not memory allocated by malloc()";
682 else
683 os << "not memory allocated by malloc()";
684 }
685 } else {
686 os << "Argument to free() is ";
687 if (SummarizeValue(os, ArgVal))
688 os << ", which is not memory allocated by malloc()";
689 else
690 os << "not memory allocated by malloc()";
691 }
692
Anna Zakse172e8b2011-08-17 23:00:25 +0000693 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000694 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000695 R->addRange(range);
696 C.EmitReport(R);
697 }
698}
699
Anna Zaks87cb5be2012-02-22 19:24:52 +0000700ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
701 const CallExpr *CE,
702 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000703 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000704 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000705 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000706 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
707 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000708 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000709 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000710
Ted Kremenek846eabd2010-12-01 21:28:31 +0000711 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000712
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000713 DefinedOrUnknownSVal PtrEQ =
714 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000715
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000716 // Get the size argument. If there is no size arg then give up.
717 const Expr *Arg1 = CE->getArg(1);
718 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000719 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000720
721 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000722 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
723 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000724 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000725 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000726
727 // Compare the size argument to 0.
728 DefinedOrUnknownSVal SizeZero =
729 svalBuilder.evalEQ(state, Arg1Val,
730 svalBuilder.makeIntValWithPtrWidth(0, false));
731
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000732 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
733 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
734 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
735 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
736 // We only assume exceptional states if they are definitely true; if the
737 // state is under-constrained, assume regular realloc behavior.
738 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
739 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
740
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000741 // If the ptr is NULL and the size is not 0, the call is equivalent to
742 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000743 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000744 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000745 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000746 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000747 }
748
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000749 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000750 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000751
Anna Zaks30838b92012-02-13 20:57:07 +0000752 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000753 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000754 SymbolRef FromPtr = arg0Val.getAsSymbol();
755 SVal RetVal = state->getSVal(CE, LCtx);
756 SymbolRef ToPtr = RetVal.getAsSymbol();
757 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000758 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000759
760 // If the size is 0, free the memory.
761 if (SizeIsZero)
762 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000763 // The semantics of the return value are:
764 // If size was equal to 0, either NULL or a pointer suitable to be passed
765 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000766 stateFree = stateFree->set<ReallocPairs>(ToPtr,
767 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000768 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000769 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000770 }
771
772 // Default behavior.
773 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
774 // FIXME: We should copy the content of the original buffer.
775 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
776 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000777 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000778 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000779 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
780 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000781 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000782 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000783 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000784 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000785}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000786
Anna Zaks87cb5be2012-02-22 19:24:52 +0000787ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Ted Kremenek8bef8232012-01-26 21:29:00 +0000788 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000789 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000790 const LocationContext *LCtx = C.getLocationContext();
791 SVal count = state->getSVal(CE->getArg(0), LCtx);
792 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000793 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
794 svalBuilder.getContext().getSizeType());
795 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000796
Anna Zaks87cb5be2012-02-22 19:24:52 +0000797 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000798}
799
Anna Zaksca8e36e2012-02-23 21:38:21 +0000800const Stmt *
801MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
802 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000803 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000804 // Walk the ExplodedGraph backwards and find the first node that referred to
805 // the tracked symbol.
806 const ExplodedNode *AllocNode = N;
807
808 while (N) {
809 if (!N->getState()->get<RegionState>(Sym))
810 break;
Anna Zaks7752d292012-02-27 23:40:55 +0000811 // Allocation node, is the last node in the current context in which the
812 // symbol was tracked.
813 if (N->getLocationContext() == LeakContext)
814 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000815 N = N->pred_empty() ? NULL : *(N->pred_begin());
816 }
817
818 ProgramPoint P = AllocNode->getLocation();
Anna Zaks7752d292012-02-27 23:40:55 +0000819 if (!isa<StmtPoint>(P))
820 return 0;
821
822 return cast<StmtPoint>(P).getStmt();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000823}
824
Anna Zaksda046772012-02-11 21:02:40 +0000825void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
826 CheckerContext &C) const {
827 assert(N);
828 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000829 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000830 // Leaks should not be reported if they are post-dominated by a sink:
831 // (1) Sinks are higher importance bugs.
832 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
833 // with __noreturn functions such as assert() or exit(). We choose not
834 // to report leaks on such paths.
835 BT_Leak->setSuppressOnSink(true);
836 }
837
Anna Zaksca8e36e2012-02-23 21:38:21 +0000838 // Most bug reports are cached at the location where they occurred.
839 // With leaks, we want to unique them by the location where they were
840 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000841 PathDiagnosticLocation LocUsedForUniqueing;
842 if (const Stmt *AllocStmt = getAllocationSite(N, Sym, C))
843 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
844 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000845
Anna Zaksfebdc322012-02-16 22:26:12 +0000846 BugReport *R = new BugReport(*BT_Leak,
Anna Zaksca8e36e2012-02-23 21:38:21 +0000847 "Memory is never released; potential memory leak", N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000848 R->markInteresting(Sym);
Jordy Rose393f98b2012-03-18 07:43:35 +0000849 // FIXME: This is a hack to make sure the MallocBugVisitor gets to look at
850 // the ExplodedNode chain first, in order to mark any failed realloc symbols
851 // as interesting for ConditionBRVisitor.
852 R->addVisitor(new ConditionBRVisitor());
Anna Zaksda046772012-02-11 21:02:40 +0000853 R->addVisitor(new MallocBugVisitor(Sym));
854 C.EmitReport(R);
855}
856
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000857void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
858 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000859{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000860 if (!SymReaper.hasDeadSymbols())
861 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000862
Ted Kremenek8bef8232012-01-26 21:29:00 +0000863 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000864 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000865 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000866
Ted Kremenek217470e2011-07-28 23:07:51 +0000867 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000868 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000869 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
870 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000871 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000872 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000873 Errors.push_back(I->first);
874 }
Jordy Rose90760142010-08-18 04:33:47 +0000875 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000876 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000877
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000878 }
879 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000880
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000881 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000882 ReallocMap RP = state->get<ReallocPairs>();
883 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
884 if (SymReaper.isDead(I->first) ||
885 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000886 state = state->remove<ReallocPairs>(I->first);
887 }
888 }
889
Anna Zaksca8e36e2012-02-23 21:38:21 +0000890 // Generate leak node.
891 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
892 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000893
Anna Zaksca8e36e2012-02-23 21:38:21 +0000894 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000895 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000896 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
897 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000898 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000899 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000900 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000901}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000902
Anna Zaksda046772012-02-11 21:02:40 +0000903void MallocChecker::checkEndPath(CheckerContext &C) const {
904 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000905 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000906
Anna Zaksa19581a2012-02-20 22:25:23 +0000907 // If inside inlined call, skip it.
908 if (C.getLocationContext()->getParent() != 0)
909 return;
910
Jordy Rose09cef092010-08-18 04:26:59 +0000911 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000912 RefState RS = I->second;
913 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000914 ExplodedNode *N = C.addTransition(state);
915 if (N)
916 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000917 }
918 }
919}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000920
Anna Zaks91c2a112012-02-08 23:16:56 +0000921bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
922 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000923 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000924 const RefState *RS = state->get<RegionState>(Sym);
925 if (!RS)
926 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000927
Anna Zaks91c2a112012-02-08 23:16:56 +0000928 if (RS->isAllocated()) {
929 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
930 C.addTransition(state);
931 return true;
932 }
933 return false;
934}
935
Anna Zaks66c40402012-02-14 21:55:24 +0000936void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
937 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
938 return;
939
940 // Check use after free, when a freed pointer is passed to a call.
941 ProgramStateRef State = C.getState();
942 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
943 E = CE->arg_end(); I != E; ++I) {
944 const Expr *A = *I;
945 if (A->getType().getTypePtr()->isAnyPointerType()) {
946 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
947 if (!Sym)
948 continue;
949 if (checkUseAfterFree(Sym, C, A))
950 return;
951 }
952 }
953}
954
Anna Zaks91c2a112012-02-08 23:16:56 +0000955void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
956 const Expr *E = S->getRetValue();
957 if (!E)
958 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000959
960 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +0000961 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
962 SymbolRef Sym = RetVal.getAsSymbol();
963 if (!Sym)
964 // If we are returning a field of the allocated struct or an array element,
965 // the callee could still free the memory.
966 // TODO: This logic should be a part of generic symbol escape callback.
967 if (const MemRegion *MR = RetVal.getAsRegion())
968 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
969 if (const SymbolicRegion *BMR =
970 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
971 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000972 if (!Sym)
973 return;
974
Anna Zaks0860cd02012-02-11 21:44:39 +0000975 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +0000976 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +0000977 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000978
Anna Zaksa19581a2012-02-20 22:25:23 +0000979 // If this function body is not inlined, check if the symbol is escaping.
980 if (C.getLocationContext()->getParent() == 0)
981 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000982}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000983
Anna Zaks91c2a112012-02-08 23:16:56 +0000984bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
985 const Stmt *S) const {
986 assert(Sym);
987 const RefState *RS = C.getState()->get<RegionState>(Sym);
988 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000989 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000990 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000991 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +0000992
Anna Zaksfebdc322012-02-16 22:26:12 +0000993 BugReport *R = new BugReport(*BT_UseFree,
994 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +0000995 if (S)
996 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000997 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000998 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000999 C.EmitReport(R);
1000 return true;
1001 }
1002 }
1003 return false;
1004}
1005
Zhongxing Xuc8023782010-03-10 04:58:55 +00001006// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001007void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1008 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001009 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001010 if (Sym)
1011 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001012}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001013
Anna Zaks4fb54872012-02-11 21:02:35 +00001014//===----------------------------------------------------------------------===//
1015// Check various ways a symbol can be invalidated.
1016// TODO: This logic (the next 3 functions) is copied/similar to the
1017// RetainRelease checker. We might want to factor this out.
1018//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001019
Anna Zaks4fb54872012-02-11 21:02:35 +00001020// Stop tracking symbols when a value escapes as a result of checkBind.
1021// A value escapes in three possible cases:
1022// (1) we are binding to something that is not a memory region.
1023// (2) we are binding to a memregion that does not have stack storage
1024// (3) we are binding to a memregion with stack storage that the store
1025// does not understand.
1026void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1027 CheckerContext &C) const {
1028 // Are we storing to something that causes the value to "escape"?
1029 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001030 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001031
Anna Zaks4fb54872012-02-11 21:02:35 +00001032 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1033 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001034
Anna Zaks4fb54872012-02-11 21:02:35 +00001035 if (!escapes) {
1036 // To test (3), generate a new state with the binding added. If it is
1037 // the same state, then it escapes (since the store cannot represent
1038 // the binding).
1039 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001040 }
Anna Zaksac593002012-02-16 03:40:57 +00001041 if (!escapes) {
1042 // Case 4: We do not currently model what happens when a symbol is
1043 // assigned to a struct field, so be conservative here and let the symbol
1044 // go. TODO: This could definitely be improved upon.
1045 escapes = !isa<VarRegion>(regionLoc->getRegion());
1046 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001047 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001048
1049 // If our store can represent the binding and we aren't storing to something
1050 // that doesn't have local storage then just return and have the simulation
1051 // state continue as is.
1052 if (!escapes)
1053 return;
1054
1055 // Otherwise, find all symbols referenced by 'val' that we are tracking
1056 // and stop tracking them.
1057 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1058 C.addTransition(state);
1059}
1060
1061// If a symbolic region is assumed to NULL (or another constant), stop tracking
1062// it - assuming that allocation failed on this path.
1063ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1064 SVal Cond,
1065 bool Assumption) const {
1066 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001067 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1068 // If the symbol is assumed to NULL or another constant, this will
1069 // return an APSInt*.
1070 if (state->getSymVal(I.getKey()))
1071 state = state->remove<RegionState>(I.getKey());
1072 }
1073
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001074 // Realloc returns 0 when reallocation fails, which means that we should
1075 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001076 ReallocMap RP = state->get<ReallocPairs>();
1077 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001078 // If the symbol is assumed to NULL or another constant, this will
1079 // return an APSInt*.
1080 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001081 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1082 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001083 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001084 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1085 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001086 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001087 }
1088 state = state->remove<ReallocPairs>(I.getKey());
1089 }
1090 }
1091
Anna Zaks4fb54872012-02-11 21:02:35 +00001092 return state;
1093}
1094
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001095// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001096// conservatively assume it can free/reallocate it's pointer arguments.
1097// (We assume that the pointers cannot escape through calls to system
1098// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001099bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1100 ProgramStateRef State) const {
1101 if (!Call)
1102 return false;
1103
1104 // For now, assume that any C++ call can free memory.
1105 // TODO: If we want to be more optimistic here, we'll need to make sure that
1106 // regions escape to C++ containers. They seem to do that even now, but for
1107 // mysterious reasons.
1108 if (Call->isCXXCall())
1109 return false;
1110
1111 const Decl *D = Call->getDecl();
1112 if (!D)
1113 return false;
1114
Anna Zaks66c40402012-02-14 21:55:24 +00001115 ASTContext &ASTC = State->getStateManager().getContext();
1116
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001117 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001118 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001119 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1120 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001121 }
1122
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001123 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001124 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001125 if (!SM.isInSystemHeader(D->getLocation()))
1126 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001127
Anna Zaks07d39a42012-02-28 01:54:22 +00001128 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001129 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001130 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001131 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001132 if (!II)
1133 return true;
1134 StringRef FName = II->getName();
1135
1136 // White list thread local storage.
1137 if (FName.equals("pthread_setspecific"))
1138 return false;
1139
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001140 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001141 if (FName.endswith("NoCopy")) {
1142 // Look for the deallocator argument. We know that the memory ownership
1143 // is not transfered only if the deallocator argument is
1144 // 'kCFAllocatorNull'.
1145 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1146 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1147 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1148 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1149 if (DeallocatorName == "kCFAllocatorNull")
1150 return true;
1151 }
1152 }
1153 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001154 }
1155
Anna Zaksca23eb22012-02-29 18:42:47 +00001156 // PR12101
1157 // Many CoreFoundation and CoreGraphics might allow a tracked object
1158 // to escape.
1159 if (Call->isCFCGAllowingEscape(FName))
1160 return false;
1161
1162 // Associating streams with malloced buffers. The pointer can escape if
1163 // 'closefn' is specified (and if that function does free memory).
1164 // Currently, we do not inspect the 'closefn' function (PR12101).
1165 if (FName == "funopen")
1166 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1167 return false;
1168
1169 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1170 // these leaks might be intentional when setting the buffer for stdio.
1171 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1172 if (FName == "setbuf" || FName =="setbuffer" ||
1173 FName == "setlinebuf" || FName == "setvbuf") {
1174 if (Call->getNumArgs() >= 1)
1175 if (const DeclRefExpr *Arg =
1176 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1177 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1178 if (D->getCanonicalDecl()->getName().find("std")
1179 != StringRef::npos)
1180 return false;
1181 }
1182
1183 // A bunch of other functions, which take ownership of a pointer (See retain
1184 // release checker). Not all the parameters here are invalidated, but the
1185 // Malloc checker cannot differentiate between them. The right way of doing
1186 // this would be to implement a pointer escapes callback.
1187 if (FName == "CVPixelBufferCreateWithBytes" ||
1188 FName == "CGBitmapContextCreateWithData" ||
1189 FName == "CVPixelBufferCreateWithPlanarBytes") {
1190 return false;
1191 }
1192
Anna Zaks0d389b82012-02-23 01:05:27 +00001193 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001194 // Most system calls, do not free the memory.
1195 return true;
1196
1197 // Process ObjC functions.
1198 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1199 Selector S = ObjCD->getSelector();
1200
1201 // White list the ObjC functions which do free memory.
1202 // - Anything containing 'freeWhenDone' param set to 1.
1203 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1204 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1205 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1206 if (Call->getArgSVal(i).isConstant(1))
1207 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001208 else
1209 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001210 }
1211 }
1212
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001213 // If the first selector ends with NoCopy, assume that the ownership is
1214 // transfered as well.
1215 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1216 if (S.getNameForSlot(0).endswith("NoCopy")) {
1217 return false;
1218 }
1219
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001220 // Otherwise, assume that the function does not free memory.
1221 // Most system calls, do not free the memory.
1222 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001223 }
1224
1225 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001226 return false;
1227
Anna Zaks66c40402012-02-14 21:55:24 +00001228}
1229
Anna Zaks4fb54872012-02-11 21:02:35 +00001230// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1231// escapes, when we are tracking p), do not track the symbol as we cannot reason
1232// about it anymore.
1233ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001234MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001235 const StoreManager::InvalidatedSymbols *invalidated,
1236 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001237 ArrayRef<const MemRegion *> Regions,
1238 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001239 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001240 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001241 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001242
Anna Zaks66c40402012-02-14 21:55:24 +00001243 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001244 // regions (explicit and implicit) escaped.
1245
1246 // Otherwise, whitelist explicit pointers; we still can track them.
1247 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001248 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1249 E = ExplicitRegions.end(); I != E; ++I) {
1250 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1251 WhitelistedSymbols.insert(R->getSymbol());
1252 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001253 }
1254
1255 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1256 E = invalidated->end(); I!=E; ++I) {
1257 SymbolRef sym = *I;
1258 if (WhitelistedSymbols.count(sym))
1259 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001260 // The symbol escaped.
1261 if (const RefState *RS = State->get<RegionState>(sym))
1262 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001263 }
Anna Zaks66c40402012-02-14 21:55:24 +00001264 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001265}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001266
Jordy Rose393f98b2012-03-18 07:43:35 +00001267static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1268 ProgramStateRef prevState) {
1269 ReallocMap currMap = currState->get<ReallocPairs>();
1270 ReallocMap prevMap = prevState->get<ReallocPairs>();
1271
1272 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1273 I != E; ++I) {
1274 SymbolRef sym = I.getKey();
1275 if (!currMap.lookup(sym))
1276 return sym;
1277 }
1278
1279 return NULL;
1280}
1281
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001282PathDiagnosticPiece *
1283MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1284 const ExplodedNode *PrevN,
1285 BugReporterContext &BRC,
1286 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001287 ProgramStateRef state = N->getState();
1288 ProgramStateRef statePrev = PrevN->getState();
1289
1290 const RefState *RS = state->get<RegionState>(Sym);
1291 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001292 if (!RS && !RSPrev)
1293 return 0;
1294
Anna Zaksfe571602012-02-16 22:26:07 +00001295 const Stmt *S = 0;
1296 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001297 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001298
1299 // Retrieve the associated statement.
1300 ProgramPoint ProgLoc = N->getLocation();
1301 if (isa<StmtPoint>(ProgLoc))
1302 S = cast<StmtPoint>(ProgLoc).getStmt();
1303 // If an assumption was made on a branch, it should be caught
1304 // here by looking at the state transition.
1305 if (isa<BlockEdge>(ProgLoc)) {
1306 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1307 S = srcBlk->getTerminator();
1308 }
1309 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001310 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001311
1312 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001313 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001314 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001315 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001316 StackHint = new StackHintGeneratorForSymbol(Sym,
1317 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001318 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001319 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001320 StackHint = new StackHintGeneratorForSymbol(Sym,
1321 "Returned released memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001322 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001323 Mode = ReallocationFailed;
1324 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001325 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001326 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001327
1328 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev))
1329 BR.markInteresting(sym);
Anna Zaksfe571602012-02-16 22:26:07 +00001330 }
1331
1332 // We are in a special mode if a reallocation failed later in the path.
1333 } else if (Mode == ReallocationFailed) {
1334 // Generate a special diagnostic for the first realloc we find.
1335 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1336 return 0;
1337
1338 // Check that the name of the function is realloc.
1339 const CallExpr *CE = dyn_cast<CallExpr>(S);
1340 if (!CE)
1341 return 0;
1342 const FunctionDecl *funDecl = CE->getDirectCallee();
1343 if (!funDecl)
1344 return 0;
1345 StringRef FunName = funDecl->getName();
1346 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1347 return 0;
1348 Msg = "Attempt to reallocate memory";
Anna Zaksfbd58742012-03-16 23:44:28 +00001349 StackHint = new StackHintGeneratorForSymbol(Sym,
1350 "Returned reallocated memory");
Anna Zaksfe571602012-02-16 22:26:07 +00001351 Mode = Normal;
1352 }
1353
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001354 if (!Msg)
1355 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001356 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001357
1358 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001359 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001360 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001361 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001362}
1363
1364
Anna Zaks231361a2012-02-08 23:16:52 +00001365#define REGISTER_CHECKER(name) \
1366void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001367 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001368 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001369}
Anna Zaks231361a2012-02-08 23:16:52 +00001370
1371REGISTER_CHECKER(MallocPessimistic)
1372REGISTER_CHECKER(MallocOptimistic)