blob: 84366f434b994f75883dd411858d90e97a8cd7fd [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 Zaks3d7c44e2012-03-21 19:45:08 +000085typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
86
Anna Zaksb319e022012-02-08 20:13:28 +000087class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000088 check::EndPath,
89 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000090 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000091 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000092 check::Location,
93 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000094 eval::Assume,
95 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000096{
Anna Zaksfebdc322012-02-16 22:26:12 +000097 mutable OwningPtr<BugType> BT_DoubleFree;
98 mutable OwningPtr<BugType> BT_Leak;
99 mutable OwningPtr<BugType> BT_UseFree;
100 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000101 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000102 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
103
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000104public:
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.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000190 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
191 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000192
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);
Anna Zaks56a938f2012-03-16 23:24:20 +0000248 private:
249 class StackHintGeneratorForReallocationFailed
250 : public StackHintGeneratorForSymbol {
251 public:
252 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
253 : StackHintGeneratorForSymbol(S, M) {}
254
255 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
256 SmallString<200> buf;
257 llvm::raw_svector_ostream os(buf);
258
Anna Zaksfbd58742012-03-16 23:44:28 +0000259 os << "Reallocation of ";
Anna Zaks56a938f2012-03-16 23:24:20 +0000260 // Printed parameters start at 1, not 0.
261 printOrdinal(++ArgIndex, os);
262 os << " parameter failed";
263
264 return os.str();
265 }
266
267 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000268 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000269 }
270 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000271 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000272};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000273} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000274
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000275typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000276typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000277class RegionState {};
278class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000279namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000280namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000281 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000282 struct ProgramStateTrait<RegionState>
283 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000284 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000285 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000286
287 template <>
288 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000289 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000290 static void *GDMIndex() { static int x; return &x; }
291 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000292}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000293}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000294
Anna Zaks4fb54872012-02-11 21:02:35 +0000295namespace {
296class StopTrackingCallback : public SymbolVisitor {
297 ProgramStateRef state;
298public:
299 StopTrackingCallback(ProgramStateRef st) : state(st) {}
300 ProgramStateRef getState() const { return state; }
301
302 bool VisitSymbol(SymbolRef sym) {
303 state = state->remove<RegionState>(sym);
304 return true;
305 }
306};
307} // end anonymous namespace
308
Anna Zaks66c40402012-02-14 21:55:24 +0000309void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000310 if (!II_malloc)
311 II_malloc = &Ctx.Idents.get("malloc");
312 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000313 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000314 if (!II_realloc)
315 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000316 if (!II_reallocf)
317 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000318 if (!II_calloc)
319 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000320 if (!II_valloc)
321 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaks60a1fa42012-02-22 03:14:20 +0000322 if (!II_strdup)
323 II_strdup = &Ctx.Idents.get("strdup");
324 if (!II_strndup)
325 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000326}
327
Anna Zaks66c40402012-02-14 21:55:24 +0000328bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000329 if (!FD)
330 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000331 IdentifierInfo *FunI = FD->getIdentifier();
332 if (!FunI)
333 return false;
334
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000335 initIdentifierInfo(C);
336
Anna Zaks40add292012-02-15 00:11:25 +0000337 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000338 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
339 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000340 return true;
341
342 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
343 FD->specific_attr_begin<OwnershipAttr>() !=
344 FD->specific_attr_end<OwnershipAttr>())
345 return true;
346
347
348 return false;
349}
350
Anna Zaksb319e022012-02-08 20:13:28 +0000351void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
352 const FunctionDecl *FD = C.getCalleeDecl(CE);
353 if (!FD)
354 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000355
Anna Zaksb16ce452012-02-15 00:11:22 +0000356 initIdentifierInfo(C.getASTContext());
357 IdentifierInfo *FunI = FD->getIdentifier();
358 if (!FunI)
359 return;
360
Anna Zaks87cb5be2012-02-22 19:24:52 +0000361 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000362 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000363 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000364 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000365 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000366 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000367 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000368 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000369 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000370 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000371 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000372 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000373 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000374 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000375 State = MallocUpdateRefState(C, CE, State);
376 } else if (Filter.CMallocOptimistic) {
377 // Check all the attributes, if there are any.
378 // There can be multiple of these attributes.
379 if (FD->hasAttrs())
380 for (specific_attr_iterator<OwnershipAttr>
381 i = FD->specific_attr_begin<OwnershipAttr>(),
382 e = FD->specific_attr_end<OwnershipAttr>();
383 i != e; ++i) {
384 switch ((*i)->getOwnKind()) {
385 case OwnershipAttr::Returns:
386 State = MallocMemReturnsAttr(C, CE, *i);
387 break;
388 case OwnershipAttr::Takes:
389 case OwnershipAttr::Holds:
390 State = FreeMemAttr(C, CE, *i);
391 break;
392 }
393 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000394 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000395 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000396}
397
Anna Zaks87cb5be2012-02-22 19:24:52 +0000398ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
399 const CallExpr *CE,
400 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000401 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000402 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000403
Sean Huntcf807c42010-08-18 23:23:40 +0000404 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000405 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000406 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000407 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000408 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000409}
410
Anna Zaksb319e022012-02-08 20:13:28 +0000411ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000412 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000413 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000414 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000415 // Get the return value.
416 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000417
Anna Zaksb16ce452012-02-15 00:11:22 +0000418 // We expect the malloc functions to return a pointer.
419 if (!isa<Loc>(retVal))
420 return 0;
421
Jordy Rose32f26562010-07-04 00:00:41 +0000422 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000423 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000424
Jordy Rose32f26562010-07-04 00:00:41 +0000425 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000426 const SymbolicRegion *R =
427 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000428 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000429 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000430 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000431 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000432 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
433 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
434 DefinedOrUnknownSVal extentMatchesSize =
435 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000436
Anna Zaks60a1fa42012-02-22 03:14:20 +0000437 state = state->assume(extentMatchesSize, true);
438 assert(state);
439 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000440
Anna Zaks87cb5be2012-02-22 19:24:52 +0000441 return MallocUpdateRefState(C, CE, state);
442}
443
444ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
445 const CallExpr *CE,
446 ProgramStateRef state) {
447 // Get the return value.
448 SVal retVal = state->getSVal(CE, C.getLocationContext());
449
450 // We expect the malloc functions to return a pointer.
451 if (!isa<Loc>(retVal))
452 return 0;
453
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000454 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000455 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000456
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000457 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000458 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000459
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000460}
461
Anna Zaks87cb5be2012-02-22 19:24:52 +0000462ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
463 const CallExpr *CE,
464 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000465 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000466 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000467
Anna Zaksb3d72752012-03-01 22:06:06 +0000468 ProgramStateRef State = C.getState();
469
Sean Huntcf807c42010-08-18 23:23:40 +0000470 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
471 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000472 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
473 Att->getOwnKind() == OwnershipAttr::Holds);
474 if (StateI)
475 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000476 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000477 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000478}
479
Ted Kremenek8bef8232012-01-26 21:29:00 +0000480ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000481 const CallExpr *CE,
482 ProgramStateRef state,
483 unsigned Num,
484 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000485 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000486 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000487 if (!isa<DefinedOrUnknownSVal>(ArgVal))
488 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000489 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
490
491 // Check for null dereferences.
492 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000493 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000494
Anna Zaksb276bd92012-02-14 00:26:13 +0000495 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000496 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000497 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000498 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000499 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000500
Jordy Rose43859f62010-06-07 19:32:37 +0000501 // Unknown values could easily be okay
502 // Undefined values are handled elsewhere
503 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000504 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000505
Jordy Rose43859f62010-06-07 19:32:37 +0000506 const MemRegion *R = ArgVal.getAsRegion();
507
508 // Nonlocs can't be freed, of course.
509 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
510 if (!R) {
511 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000512 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000513 }
514
515 R = R->StripCasts();
516
517 // Blocks might show up as heap data, but should not be free()d
518 if (isa<BlockDataRegion>(R)) {
519 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000520 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000521 }
522
523 const MemSpaceRegion *MS = R->getMemorySpace();
524
525 // Parameters, locals, statics, and globals shouldn't be freed.
526 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
527 // FIXME: at the time this code was written, malloc() regions were
528 // represented by conjured symbols, which are all in UnknownSpaceRegion.
529 // This means that there isn't actually anything from HeapSpaceRegion
530 // that should be freed, even though we allow it here.
531 // Of course, free() can work on memory allocated outside the current
532 // function, so UnknownSpaceRegion is always a possibility.
533 // False negatives are better than false positives.
534
535 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000536 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000537 }
538
539 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
540 // Various cases could lead to non-symbol values here.
541 // For now, ignore them.
542 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000543 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000544
545 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000546 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000547
548 // If the symbol has not been tracked, return. This is possible when free() is
549 // called on a pointer that does not get its pointee directly from malloc().
550 // Full support of this requires inter-procedural analysis.
551 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000552 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000553
554 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000555 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000556 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000557 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000558 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000559 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000560 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000561 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000562 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000563 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000564 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000565 C.EmitReport(R);
566 }
Anna Zaksb319e022012-02-08 20:13:28 +0000567 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000568 }
569
570 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000571 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000572 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
573 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000574}
575
Ted Kremenek9c378f72011-08-12 23:37:29 +0000576bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000577 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
578 os << "an integer (" << IntVal->getValue() << ")";
579 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
580 os << "a constant address (" << ConstAddr->getValue() << ")";
581 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000582 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000583 else
584 return false;
585
586 return true;
587}
588
Ted Kremenek9c378f72011-08-12 23:37:29 +0000589bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000590 const MemRegion *MR) {
591 switch (MR->getKind()) {
592 case MemRegion::FunctionTextRegionKind: {
593 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
594 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000595 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000596 else
597 os << "the address of a function";
598 return true;
599 }
600 case MemRegion::BlockTextRegionKind:
601 os << "block text";
602 return true;
603 case MemRegion::BlockDataRegionKind:
604 // FIXME: where the block came from?
605 os << "a block";
606 return true;
607 default: {
608 const MemSpaceRegion *MS = MR->getMemorySpace();
609
Anna Zakseb31a762012-01-04 23:54:01 +0000610 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000611 const VarRegion *VR = dyn_cast<VarRegion>(MR);
612 const VarDecl *VD;
613 if (VR)
614 VD = VR->getDecl();
615 else
616 VD = NULL;
617
618 if (VD)
619 os << "the address of the local variable '" << VD->getName() << "'";
620 else
621 os << "the address of a local stack variable";
622 return true;
623 }
Anna Zakseb31a762012-01-04 23:54:01 +0000624
625 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000626 const VarRegion *VR = dyn_cast<VarRegion>(MR);
627 const VarDecl *VD;
628 if (VR)
629 VD = VR->getDecl();
630 else
631 VD = NULL;
632
633 if (VD)
634 os << "the address of the parameter '" << VD->getName() << "'";
635 else
636 os << "the address of a parameter";
637 return true;
638 }
Anna Zakseb31a762012-01-04 23:54:01 +0000639
640 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000641 const VarRegion *VR = dyn_cast<VarRegion>(MR);
642 const VarDecl *VD;
643 if (VR)
644 VD = VR->getDecl();
645 else
646 VD = NULL;
647
648 if (VD) {
649 if (VD->isStaticLocal())
650 os << "the address of the static variable '" << VD->getName() << "'";
651 else
652 os << "the address of the global variable '" << VD->getName() << "'";
653 } else
654 os << "the address of a global variable";
655 return true;
656 }
Anna Zakseb31a762012-01-04 23:54:01 +0000657
658 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000659 }
660 }
661}
662
663void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000664 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000665 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000666 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000667 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000668
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000669 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000670 llvm::raw_svector_ostream os(buf);
671
672 const MemRegion *MR = ArgVal.getAsRegion();
673 if (MR) {
674 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
675 MR = ER->getSuperRegion();
676
677 // Special case for alloca()
678 if (isa<AllocaRegion>(MR))
679 os << "Argument to free() was allocated by alloca(), not malloc()";
680 else {
681 os << "Argument to free() is ";
682 if (SummarizeRegion(os, MR))
683 os << ", which is not memory allocated by malloc()";
684 else
685 os << "not memory allocated by malloc()";
686 }
687 } else {
688 os << "Argument to free() is ";
689 if (SummarizeValue(os, ArgVal))
690 os << ", which is not memory allocated by malloc()";
691 else
692 os << "not memory allocated by malloc()";
693 }
694
Anna Zakse172e8b2011-08-17 23:00:25 +0000695 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000696 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000697 R->addRange(range);
698 C.EmitReport(R);
699 }
700}
701
Anna Zaks87cb5be2012-02-22 19:24:52 +0000702ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
703 const CallExpr *CE,
704 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000705 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000706 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000707 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000708 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
709 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000710 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000711 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000712
Ted Kremenek846eabd2010-12-01 21:28:31 +0000713 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000714
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000715 DefinedOrUnknownSVal PtrEQ =
716 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000717
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000718 // Get the size argument. If there is no size arg then give up.
719 const Expr *Arg1 = CE->getArg(1);
720 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000721 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000722
723 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000724 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
725 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000726 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000727 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000728
729 // Compare the size argument to 0.
730 DefinedOrUnknownSVal SizeZero =
731 svalBuilder.evalEQ(state, Arg1Val,
732 svalBuilder.makeIntValWithPtrWidth(0, false));
733
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000734 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
735 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
736 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
737 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
738 // We only assume exceptional states if they are definitely true; if the
739 // state is under-constrained, assume regular realloc behavior.
740 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
741 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
742
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000743 // If the ptr is NULL and the size is not 0, the call is equivalent to
744 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000745 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000746 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000747 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000748 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000749 }
750
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000751 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000752 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000753
Anna Zaks30838b92012-02-13 20:57:07 +0000754 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000755 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000756 SymbolRef FromPtr = arg0Val.getAsSymbol();
757 SVal RetVal = state->getSVal(CE, LCtx);
758 SymbolRef ToPtr = RetVal.getAsSymbol();
759 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000760 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000761
762 // If the size is 0, free the memory.
763 if (SizeIsZero)
764 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000765 // The semantics of the return value are:
766 // If size was equal to 0, either NULL or a pointer suitable to be passed
767 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000768 stateFree = stateFree->set<ReallocPairs>(ToPtr,
769 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000770 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000771 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000772 }
773
774 // Default behavior.
775 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
776 // FIXME: We should copy the content of the original buffer.
777 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
778 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000779 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000780 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000781 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
782 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000783 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000784 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000785 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000786 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000787}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000788
Anna Zaks87cb5be2012-02-22 19:24:52 +0000789ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Ted Kremenek8bef8232012-01-26 21:29:00 +0000790 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000791 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000792 const LocationContext *LCtx = C.getLocationContext();
793 SVal count = state->getSVal(CE->getArg(0), LCtx);
794 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000795 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
796 svalBuilder.getContext().getSizeType());
797 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000798
Anna Zaks87cb5be2012-02-22 19:24:52 +0000799 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000800}
801
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000802LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000803MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
804 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000805 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000806 // Walk the ExplodedGraph backwards and find the first node that referred to
807 // the tracked symbol.
808 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000809 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000810
811 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000812 ProgramStateRef State = N->getState();
813 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000814 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000815
816 // Find the most recent expression bound to the symbol in the current
817 // context.
818 ProgramPoint L = N->getLocation();
819 if (!ReferenceRegion) {
820 const MemRegion *MR = C.getLocationRegionIfPostStore(N);
821 if (MR) {
822 SVal Val = State->getSVal(MR);
823 if (Val.getAsLocSymbol() == Sym)
824 ReferenceRegion = MR;
825 }
826 }
827
Anna Zaks7752d292012-02-27 23:40:55 +0000828 // Allocation node, is the last node in the current context in which the
829 // symbol was tracked.
830 if (N->getLocationContext() == LeakContext)
831 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000832 N = N->pred_empty() ? NULL : *(N->pred_begin());
833 }
834
835 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000836 const Stmt *AllocationStmt = 0;
837 if (isa<StmtPoint>(P))
838 AllocationStmt = cast<StmtPoint>(P).getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +0000839
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000840 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +0000841}
842
Anna Zaksda046772012-02-11 21:02:40 +0000843void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
844 CheckerContext &C) const {
845 assert(N);
846 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000847 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000848 // Leaks should not be reported if they are post-dominated by a sink:
849 // (1) Sinks are higher importance bugs.
850 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
851 // with __noreturn functions such as assert() or exit(). We choose not
852 // to report leaks on such paths.
853 BT_Leak->setSuppressOnSink(true);
854 }
855
Anna Zaksca8e36e2012-02-23 21:38:21 +0000856 // Most bug reports are cached at the location where they occurred.
857 // With leaks, we want to unique them by the location where they were
858 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000859 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000860 const Stmt *AllocStmt = 0;
861 const MemRegion *Region = 0;
862 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
863 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +0000864 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
865 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000866
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000867 SmallString<200> buf;
868 llvm::raw_svector_ostream os(buf);
869 os << "Memory is never released; potential leak";
870 if (Region) {
871 os << " of memory pointed to by '";
872 Region->dumpPretty(os);
873 os <<'\'';
874 }
875
876 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000877 R->markInteresting(Sym);
Jordy Rose393f98b2012-03-18 07:43:35 +0000878 // FIXME: This is a hack to make sure the MallocBugVisitor gets to look at
879 // the ExplodedNode chain first, in order to mark any failed realloc symbols
880 // as interesting for ConditionBRVisitor.
881 R->addVisitor(new ConditionBRVisitor());
Anna Zaksda046772012-02-11 21:02:40 +0000882 R->addVisitor(new MallocBugVisitor(Sym));
883 C.EmitReport(R);
884}
885
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000886void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
887 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000888{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000889 if (!SymReaper.hasDeadSymbols())
890 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000891
Ted Kremenek8bef8232012-01-26 21:29:00 +0000892 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000893 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000894 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000895
Ted Kremenek217470e2011-07-28 23:07:51 +0000896 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000897 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000898 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
899 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000900 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000901 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000902 Errors.push_back(I->first);
903 }
Jordy Rose90760142010-08-18 04:33:47 +0000904 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000905 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000906
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000907 }
908 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000909
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000910 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000911 ReallocMap RP = state->get<ReallocPairs>();
912 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
913 if (SymReaper.isDead(I->first) ||
914 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000915 state = state->remove<ReallocPairs>(I->first);
916 }
917 }
918
Anna Zaksca8e36e2012-02-23 21:38:21 +0000919 // Generate leak node.
920 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
921 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000922
Anna Zaksca8e36e2012-02-23 21:38:21 +0000923 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000924 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000925 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
926 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000927 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000928 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000929 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000930}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000931
Anna Zaksda046772012-02-11 21:02:40 +0000932void MallocChecker::checkEndPath(CheckerContext &C) const {
933 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000934 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000935
Anna Zaksa19581a2012-02-20 22:25:23 +0000936 // If inside inlined call, skip it.
937 if (C.getLocationContext()->getParent() != 0)
938 return;
939
Jordy Rose09cef092010-08-18 04:26:59 +0000940 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000941 RefState RS = I->second;
942 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000943 ExplodedNode *N = C.addTransition(state);
944 if (N)
945 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000946 }
947 }
948}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000949
Anna Zaks91c2a112012-02-08 23:16:56 +0000950bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
951 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000952 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000953 const RefState *RS = state->get<RegionState>(Sym);
954 if (!RS)
955 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000956
Anna Zaks91c2a112012-02-08 23:16:56 +0000957 if (RS->isAllocated()) {
958 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
959 C.addTransition(state);
960 return true;
961 }
962 return false;
963}
964
Anna Zaks66c40402012-02-14 21:55:24 +0000965void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
966 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
967 return;
968
969 // Check use after free, when a freed pointer is passed to a call.
970 ProgramStateRef State = C.getState();
971 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
972 E = CE->arg_end(); I != E; ++I) {
973 const Expr *A = *I;
974 if (A->getType().getTypePtr()->isAnyPointerType()) {
975 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
976 if (!Sym)
977 continue;
978 if (checkUseAfterFree(Sym, C, A))
979 return;
980 }
981 }
982}
983
Anna Zaks91c2a112012-02-08 23:16:56 +0000984void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
985 const Expr *E = S->getRetValue();
986 if (!E)
987 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000988
989 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +0000990 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
991 SymbolRef Sym = RetVal.getAsSymbol();
992 if (!Sym)
993 // If we are returning a field of the allocated struct or an array element,
994 // the callee could still free the memory.
995 // TODO: This logic should be a part of generic symbol escape callback.
996 if (const MemRegion *MR = RetVal.getAsRegion())
997 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
998 if (const SymbolicRegion *BMR =
999 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1000 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001001 if (!Sym)
1002 return;
1003
Anna Zaks0860cd02012-02-11 21:44:39 +00001004 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +00001005 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +00001006 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001007
Anna Zaksa19581a2012-02-20 22:25:23 +00001008 // If this function body is not inlined, check if the symbol is escaping.
1009 if (C.getLocationContext()->getParent() == 0)
1010 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001011}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001012
Anna Zaks91c2a112012-02-08 23:16:56 +00001013bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1014 const Stmt *S) const {
1015 assert(Sym);
1016 const RefState *RS = C.getState()->get<RegionState>(Sym);
1017 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001018 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001019 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001020 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001021
Anna Zaksfebdc322012-02-16 22:26:12 +00001022 BugReport *R = new BugReport(*BT_UseFree,
1023 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001024 if (S)
1025 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001026 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001027 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001028 C.EmitReport(R);
1029 return true;
1030 }
1031 }
1032 return false;
1033}
1034
Zhongxing Xuc8023782010-03-10 04:58:55 +00001035// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001036void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1037 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001038 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001039 if (Sym)
1040 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001041}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001042
Anna Zaks4fb54872012-02-11 21:02:35 +00001043//===----------------------------------------------------------------------===//
1044// Check various ways a symbol can be invalidated.
1045// TODO: This logic (the next 3 functions) is copied/similar to the
1046// RetainRelease checker. We might want to factor this out.
1047//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001048
Anna Zaks4fb54872012-02-11 21:02:35 +00001049// Stop tracking symbols when a value escapes as a result of checkBind.
1050// A value escapes in three possible cases:
1051// (1) we are binding to something that is not a memory region.
1052// (2) we are binding to a memregion that does not have stack storage
1053// (3) we are binding to a memregion with stack storage that the store
1054// does not understand.
1055void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1056 CheckerContext &C) const {
1057 // Are we storing to something that causes the value to "escape"?
1058 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001059 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001060
Anna Zaks4fb54872012-02-11 21:02:35 +00001061 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1062 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001063
Anna Zaks4fb54872012-02-11 21:02:35 +00001064 if (!escapes) {
1065 // To test (3), generate a new state with the binding added. If it is
1066 // the same state, then it escapes (since the store cannot represent
1067 // the binding).
1068 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001069 }
Anna Zaksac593002012-02-16 03:40:57 +00001070 if (!escapes) {
1071 // Case 4: We do not currently model what happens when a symbol is
1072 // assigned to a struct field, so be conservative here and let the symbol
1073 // go. TODO: This could definitely be improved upon.
1074 escapes = !isa<VarRegion>(regionLoc->getRegion());
1075 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001076 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001077
1078 // If our store can represent the binding and we aren't storing to something
1079 // that doesn't have local storage then just return and have the simulation
1080 // state continue as is.
1081 if (!escapes)
1082 return;
1083
1084 // Otherwise, find all symbols referenced by 'val' that we are tracking
1085 // and stop tracking them.
1086 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1087 C.addTransition(state);
1088}
1089
1090// If a symbolic region is assumed to NULL (or another constant), stop tracking
1091// it - assuming that allocation failed on this path.
1092ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1093 SVal Cond,
1094 bool Assumption) const {
1095 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001096 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1097 // If the symbol is assumed to NULL or another constant, this will
1098 // return an APSInt*.
1099 if (state->getSymVal(I.getKey()))
1100 state = state->remove<RegionState>(I.getKey());
1101 }
1102
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001103 // Realloc returns 0 when reallocation fails, which means that we should
1104 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001105 ReallocMap RP = state->get<ReallocPairs>();
1106 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001107 // If the symbol is assumed to NULL or another constant, this will
1108 // return an APSInt*.
1109 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001110 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1111 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001112 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001113 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1114 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001115 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001116 }
1117 state = state->remove<ReallocPairs>(I.getKey());
1118 }
1119 }
1120
Anna Zaks4fb54872012-02-11 21:02:35 +00001121 return state;
1122}
1123
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001124// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001125// conservatively assume it can free/reallocate it's pointer arguments.
1126// (We assume that the pointers cannot escape through calls to system
1127// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001128bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1129 ProgramStateRef State) const {
1130 if (!Call)
1131 return false;
1132
1133 // For now, assume that any C++ call can free memory.
1134 // TODO: If we want to be more optimistic here, we'll need to make sure that
1135 // regions escape to C++ containers. They seem to do that even now, but for
1136 // mysterious reasons.
1137 if (Call->isCXXCall())
1138 return false;
1139
1140 const Decl *D = Call->getDecl();
1141 if (!D)
1142 return false;
1143
Anna Zaks66c40402012-02-14 21:55:24 +00001144 ASTContext &ASTC = State->getStateManager().getContext();
1145
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001146 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001147 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001148 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1149 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001150 }
1151
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001152 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001153 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001154 if (!SM.isInSystemHeader(D->getLocation()))
1155 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001156
Anna Zaks07d39a42012-02-28 01:54:22 +00001157 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001158 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001159 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001160 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001161 if (!II)
1162 return true;
1163 StringRef FName = II->getName();
1164
1165 // White list thread local storage.
1166 if (FName.equals("pthread_setspecific"))
1167 return false;
1168
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001169 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001170 if (FName.endswith("NoCopy")) {
1171 // Look for the deallocator argument. We know that the memory ownership
1172 // is not transfered only if the deallocator argument is
1173 // 'kCFAllocatorNull'.
1174 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1175 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1176 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1177 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1178 if (DeallocatorName == "kCFAllocatorNull")
1179 return true;
1180 }
1181 }
1182 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001183 }
1184
Anna Zaksca23eb22012-02-29 18:42:47 +00001185 // PR12101
1186 // Many CoreFoundation and CoreGraphics might allow a tracked object
1187 // to escape.
1188 if (Call->isCFCGAllowingEscape(FName))
1189 return false;
1190
1191 // Associating streams with malloced buffers. The pointer can escape if
1192 // 'closefn' is specified (and if that function does free memory).
1193 // Currently, we do not inspect the 'closefn' function (PR12101).
1194 if (FName == "funopen")
1195 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1196 return false;
1197
1198 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1199 // these leaks might be intentional when setting the buffer for stdio.
1200 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1201 if (FName == "setbuf" || FName =="setbuffer" ||
1202 FName == "setlinebuf" || FName == "setvbuf") {
1203 if (Call->getNumArgs() >= 1)
1204 if (const DeclRefExpr *Arg =
1205 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1206 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1207 if (D->getCanonicalDecl()->getName().find("std")
1208 != StringRef::npos)
1209 return false;
1210 }
1211
1212 // A bunch of other functions, which take ownership of a pointer (See retain
1213 // release checker). Not all the parameters here are invalidated, but the
1214 // Malloc checker cannot differentiate between them. The right way of doing
1215 // this would be to implement a pointer escapes callback.
1216 if (FName == "CVPixelBufferCreateWithBytes" ||
1217 FName == "CGBitmapContextCreateWithData" ||
1218 FName == "CVPixelBufferCreateWithPlanarBytes") {
1219 return false;
1220 }
1221
Anna Zaks0d389b82012-02-23 01:05:27 +00001222 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001223 // Most system calls, do not free the memory.
1224 return true;
1225
1226 // Process ObjC functions.
1227 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1228 Selector S = ObjCD->getSelector();
1229
1230 // White list the ObjC functions which do free memory.
1231 // - Anything containing 'freeWhenDone' param set to 1.
1232 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1233 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1234 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1235 if (Call->getArgSVal(i).isConstant(1))
1236 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001237 else
1238 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001239 }
1240 }
1241
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001242 // If the first selector ends with NoCopy, assume that the ownership is
1243 // transfered as well.
1244 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1245 if (S.getNameForSlot(0).endswith("NoCopy")) {
1246 return false;
1247 }
1248
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001249 // Otherwise, assume that the function does not free memory.
1250 // Most system calls, do not free the memory.
1251 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001252 }
1253
1254 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001255 return false;
1256
Anna Zaks66c40402012-02-14 21:55:24 +00001257}
1258
Anna Zaks4fb54872012-02-11 21:02:35 +00001259// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1260// escapes, when we are tracking p), do not track the symbol as we cannot reason
1261// about it anymore.
1262ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001263MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001264 const StoreManager::InvalidatedSymbols *invalidated,
1265 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001266 ArrayRef<const MemRegion *> Regions,
1267 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001268 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001269 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001270 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001271
Anna Zaks66c40402012-02-14 21:55:24 +00001272 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001273 // regions (explicit and implicit) escaped.
1274
1275 // Otherwise, whitelist explicit pointers; we still can track them.
1276 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001277 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1278 E = ExplicitRegions.end(); I != E; ++I) {
1279 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1280 WhitelistedSymbols.insert(R->getSymbol());
1281 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001282 }
1283
1284 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1285 E = invalidated->end(); I!=E; ++I) {
1286 SymbolRef sym = *I;
1287 if (WhitelistedSymbols.count(sym))
1288 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001289 // The symbol escaped.
1290 if (const RefState *RS = State->get<RegionState>(sym))
1291 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001292 }
Anna Zaks66c40402012-02-14 21:55:24 +00001293 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001294}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001295
Jordy Rose393f98b2012-03-18 07:43:35 +00001296static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1297 ProgramStateRef prevState) {
1298 ReallocMap currMap = currState->get<ReallocPairs>();
1299 ReallocMap prevMap = prevState->get<ReallocPairs>();
1300
1301 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1302 I != E; ++I) {
1303 SymbolRef sym = I.getKey();
1304 if (!currMap.lookup(sym))
1305 return sym;
1306 }
1307
1308 return NULL;
1309}
1310
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001311PathDiagnosticPiece *
1312MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1313 const ExplodedNode *PrevN,
1314 BugReporterContext &BRC,
1315 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001316 ProgramStateRef state = N->getState();
1317 ProgramStateRef statePrev = PrevN->getState();
1318
1319 const RefState *RS = state->get<RegionState>(Sym);
1320 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001321 if (!RS && !RSPrev)
1322 return 0;
1323
Anna Zaksfe571602012-02-16 22:26:07 +00001324 const Stmt *S = 0;
1325 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001326 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001327
1328 // Retrieve the associated statement.
1329 ProgramPoint ProgLoc = N->getLocation();
1330 if (isa<StmtPoint>(ProgLoc))
1331 S = cast<StmtPoint>(ProgLoc).getStmt();
1332 // If an assumption was made on a branch, it should be caught
1333 // here by looking at the state transition.
1334 if (isa<BlockEdge>(ProgLoc)) {
1335 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1336 S = srcBlk->getTerminator();
1337 }
1338 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001339 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001340
1341 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001342 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001343 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001344 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001345 StackHint = new StackHintGeneratorForSymbol(Sym,
1346 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001347 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001348 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001349 StackHint = new StackHintGeneratorForSymbol(Sym,
1350 "Returned released memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001351 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001352 Mode = ReallocationFailed;
1353 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001354 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001355 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001356
1357 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev))
1358 BR.markInteresting(sym);
Anna Zaksfe571602012-02-16 22:26:07 +00001359 }
1360
1361 // We are in a special mode if a reallocation failed later in the path.
1362 } else if (Mode == ReallocationFailed) {
1363 // Generate a special diagnostic for the first realloc we find.
1364 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1365 return 0;
1366
1367 // Check that the name of the function is realloc.
1368 const CallExpr *CE = dyn_cast<CallExpr>(S);
1369 if (!CE)
1370 return 0;
1371 const FunctionDecl *funDecl = CE->getDirectCallee();
1372 if (!funDecl)
1373 return 0;
1374 StringRef FunName = funDecl->getName();
1375 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1376 return 0;
1377 Msg = "Attempt to reallocate memory";
Anna Zaksfbd58742012-03-16 23:44:28 +00001378 StackHint = new StackHintGeneratorForSymbol(Sym,
1379 "Returned reallocated memory");
Anna Zaksfe571602012-02-16 22:26:07 +00001380 Mode = Normal;
1381 }
1382
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001383 if (!Msg)
1384 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001385 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001386
1387 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001388 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001389 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001390 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001391}
1392
1393
Anna Zaks231361a2012-02-08 23:16:52 +00001394#define REGISTER_CHECKER(name) \
1395void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001396 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001397 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001398}
Anna Zaks231361a2012-02-08 23:16:52 +00001399
1400REGISTER_CHECKER(MallocPessimistic)
1401REGISTER_CHECKER(MallocOptimistic)