blob: 7b9adb7c157d5e6164552917537e34bf0197c773 [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>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +000092 check::PostStmt<BlockExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000093 check::Location,
94 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000095 eval::Assume,
96 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000097{
Anna Zaksfebdc322012-02-16 22:26:12 +000098 mutable OwningPtr<BugType> BT_DoubleFree;
99 mutable OwningPtr<BugType> BT_Leak;
100 mutable OwningPtr<BugType> BT_UseFree;
101 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000102 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000103 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
104
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000105public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000106 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000107 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000108
109 /// In pessimistic mode, the checker assumes that it does not know which
110 /// functions might free the memory.
111 struct ChecksFilter {
112 DefaultBool CMallocPessimistic;
113 DefaultBool CMallocOptimistic;
114 };
115
116 ChecksFilter Filter;
117
Anna Zaks66c40402012-02-14 21:55:24 +0000118 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000119 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000120 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000121 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000122 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000123 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000124 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000125 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000126 void checkLocation(SVal l, bool isLoad, const Stmt *S,
127 CheckerContext &C) const;
128 void checkBind(SVal location, SVal val, const Stmt*S,
129 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000130 ProgramStateRef
131 checkRegionChanges(ProgramStateRef state,
132 const StoreManager::InvalidatedSymbols *invalidated,
133 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000134 ArrayRef<const MemRegion *> Regions,
135 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000136 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
137 return true;
138 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000139
Zhongxing Xu7b760962009-11-13 07:25:27 +0000140private:
Anna Zaks66c40402012-02-14 21:55:24 +0000141 void initIdentifierInfo(ASTContext &C) const;
142
143 /// Check if this is one of the functions which can allocate/reallocate memory
144 /// pointed to by one of its arguments.
145 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
146
Anna Zaks87cb5be2012-02-22 19:24:52 +0000147 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
148 const CallExpr *CE,
149 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000150 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000151 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000152 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000153 return MallocMemAux(C, CE,
154 state->getSVal(SizeEx, C.getLocationContext()),
155 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000156 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000157
Ted Kremenek8bef8232012-01-26 21:29:00 +0000158 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000159 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000160 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000161
Anna Zaks87cb5be2012-02-22 19:24:52 +0000162 /// Update the RefState to reflect the new memory allocation.
163 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
164 const CallExpr *CE,
165 ProgramStateRef state);
166
167 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
168 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000169 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
170 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000171 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000172
Anna Zaks87cb5be2012-02-22 19:24:52 +0000173 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
174 bool FreesMemOnFailure) const;
175 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000176
Anna Zaks91c2a112012-02-08 23:16:56 +0000177 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
178 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
179 const Stmt *S = 0) const;
180
Anna Zaks66c40402012-02-14 21:55:24 +0000181 /// Check if the function is not known to us. So, for example, we could
182 /// conservatively assume it can free/reallocate it's pointer arguments.
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000183 bool doesNotFreeMemory(const CallOrObjCMessage *Call,
184 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000185
Ted Kremenek9c378f72011-08-12 23:37:29 +0000186 static bool SummarizeValue(raw_ostream &os, SVal V);
187 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000188 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000189
Anna Zaksca8e36e2012-02-23 21:38:21 +0000190 /// Find the location of the allocation for Sym on the path leading to the
191 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000192 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
193 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000194
Anna Zaksda046772012-02-11 21:02:40 +0000195 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
196
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000197 /// The bug visitor which allows us to print extra diagnostics along the
198 /// BugReport path. For example, showing the allocation site of the leaked
199 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000200 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000201 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000202 enum NotificationMode {
203 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000204 ReallocationFailed
205 };
206
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000207 // The allocated region symbol tracked by the main analysis.
208 SymbolRef Sym;
209
Jordy Roseb000fb52012-03-24 03:15:09 +0000210 // The mode we are in, i.e. what kind of diagnostics will be emitted.
211 NotificationMode Mode;
212
213 // A symbol from when the primary region should have been reallocated.
214 SymbolRef FailedReallocSymbol;
215
216 public:
217 MallocBugVisitor(SymbolRef S)
218 : Sym(S), Mode(Normal), FailedReallocSymbol(0) {}
219
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000220 virtual ~MallocBugVisitor() {}
221
222 void Profile(llvm::FoldingSetNodeID &ID) const {
223 static int X = 0;
224 ID.AddPointer(&X);
225 ID.AddPointer(Sym);
226 }
227
Anna Zaksfe571602012-02-16 22:26:07 +0000228 inline bool isAllocated(const RefState *S, const RefState *SPrev,
229 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000230 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000231 return (Stmt && isa<CallExpr>(Stmt) &&
232 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000233 }
234
Anna Zaksfe571602012-02-16 22:26:07 +0000235 inline bool isReleased(const RefState *S, const RefState *SPrev,
236 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000237 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000238 return (Stmt && isa<CallExpr>(Stmt) &&
239 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
240 }
241
242 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
243 const Stmt *Stmt) {
244 // If the expression is not a call, and the state change is
245 // released -> allocated, it must be the realloc return value
246 // check. If we have to handle more cases here, it might be cleaner just
247 // to track this extra bit in the state itself.
248 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
249 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000250 }
251
252 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
253 const ExplodedNode *PrevN,
254 BugReporterContext &BRC,
255 BugReport &BR);
Anna Zaks56a938f2012-03-16 23:24:20 +0000256 private:
257 class StackHintGeneratorForReallocationFailed
258 : public StackHintGeneratorForSymbol {
259 public:
260 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
261 : StackHintGeneratorForSymbol(S, M) {}
262
263 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
264 SmallString<200> buf;
265 llvm::raw_svector_ostream os(buf);
266
Anna Zaksfbd58742012-03-16 23:44:28 +0000267 os << "Reallocation of ";
Anna Zaks56a938f2012-03-16 23:24:20 +0000268 // Printed parameters start at 1, not 0.
269 printOrdinal(++ArgIndex, os);
270 os << " parameter failed";
271
272 return os.str();
273 }
274
275 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000276 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000277 }
278 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000279 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000280};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000281} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000282
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000283typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000284typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000285class RegionState {};
286class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000287namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000288namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000289 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000290 struct ProgramStateTrait<RegionState>
291 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000292 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000293 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000294
295 template <>
296 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000297 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000298 static void *GDMIndex() { static int x; return &x; }
299 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000300}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000301}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000302
Anna Zaks4fb54872012-02-11 21:02:35 +0000303namespace {
304class StopTrackingCallback : public SymbolVisitor {
305 ProgramStateRef state;
306public:
307 StopTrackingCallback(ProgramStateRef st) : state(st) {}
308 ProgramStateRef getState() const { return state; }
309
310 bool VisitSymbol(SymbolRef sym) {
311 state = state->remove<RegionState>(sym);
312 return true;
313 }
314};
315} // end anonymous namespace
316
Anna Zaks66c40402012-02-14 21:55:24 +0000317void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000318 if (!II_malloc)
319 II_malloc = &Ctx.Idents.get("malloc");
320 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000321 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000322 if (!II_realloc)
323 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000324 if (!II_reallocf)
325 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000326 if (!II_calloc)
327 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000328 if (!II_valloc)
329 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaks60a1fa42012-02-22 03:14:20 +0000330 if (!II_strdup)
331 II_strdup = &Ctx.Idents.get("strdup");
332 if (!II_strndup)
333 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000334}
335
Anna Zaks66c40402012-02-14 21:55:24 +0000336bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000337 if (!FD)
338 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000339 IdentifierInfo *FunI = FD->getIdentifier();
340 if (!FunI)
341 return false;
342
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000343 initIdentifierInfo(C);
344
Anna Zaks40add292012-02-15 00:11:25 +0000345 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000346 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
347 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000348 return true;
349
350 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
351 FD->specific_attr_begin<OwnershipAttr>() !=
352 FD->specific_attr_end<OwnershipAttr>())
353 return true;
354
355
356 return false;
357}
358
Anna Zaksb319e022012-02-08 20:13:28 +0000359void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
360 const FunctionDecl *FD = C.getCalleeDecl(CE);
361 if (!FD)
362 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000363
Anna Zaksb16ce452012-02-15 00:11:22 +0000364 initIdentifierInfo(C.getASTContext());
365 IdentifierInfo *FunI = FD->getIdentifier();
366 if (!FunI)
367 return;
368
Anna Zaks87cb5be2012-02-22 19:24:52 +0000369 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000370 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000371 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000372 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000373 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000374 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000375 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000376 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000377 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000378 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000379 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000380 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000381 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000382 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000383 State = MallocUpdateRefState(C, CE, State);
384 } else if (Filter.CMallocOptimistic) {
385 // Check all the attributes, if there are any.
386 // There can be multiple of these attributes.
387 if (FD->hasAttrs())
388 for (specific_attr_iterator<OwnershipAttr>
389 i = FD->specific_attr_begin<OwnershipAttr>(),
390 e = FD->specific_attr_end<OwnershipAttr>();
391 i != e; ++i) {
392 switch ((*i)->getOwnKind()) {
393 case OwnershipAttr::Returns:
394 State = MallocMemReturnsAttr(C, CE, *i);
395 break;
396 case OwnershipAttr::Takes:
397 case OwnershipAttr::Holds:
398 State = FreeMemAttr(C, CE, *i);
399 break;
400 }
401 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000402 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000403 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000404}
405
Anna Zaks87cb5be2012-02-22 19:24:52 +0000406ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
407 const CallExpr *CE,
408 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000409 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000410 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000411
Sean Huntcf807c42010-08-18 23:23:40 +0000412 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000413 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000414 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000415 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000416 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000417}
418
Anna Zaksb319e022012-02-08 20:13:28 +0000419ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000420 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000421 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000422 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000423 // Get the return value.
424 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000425
Anna Zaksb16ce452012-02-15 00:11:22 +0000426 // We expect the malloc functions to return a pointer.
427 if (!isa<Loc>(retVal))
428 return 0;
429
Jordy Rose32f26562010-07-04 00:00:41 +0000430 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000431 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000432
Jordy Rose32f26562010-07-04 00:00:41 +0000433 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000434 const SymbolicRegion *R =
435 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000436 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000437 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000438 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000439 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000440 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
441 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
442 DefinedOrUnknownSVal extentMatchesSize =
443 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000444
Anna Zaks60a1fa42012-02-22 03:14:20 +0000445 state = state->assume(extentMatchesSize, true);
446 assert(state);
447 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000448
Anna Zaks87cb5be2012-02-22 19:24:52 +0000449 return MallocUpdateRefState(C, CE, state);
450}
451
452ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
453 const CallExpr *CE,
454 ProgramStateRef state) {
455 // Get the return value.
456 SVal retVal = state->getSVal(CE, C.getLocationContext());
457
458 // We expect the malloc functions to return a pointer.
459 if (!isa<Loc>(retVal))
460 return 0;
461
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000462 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000463 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000464
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000465 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000466 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000467
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000468}
469
Anna Zaks87cb5be2012-02-22 19:24:52 +0000470ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
471 const CallExpr *CE,
472 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000473 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000474 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000475
Anna Zaksb3d72752012-03-01 22:06:06 +0000476 ProgramStateRef State = C.getState();
477
Sean Huntcf807c42010-08-18 23:23:40 +0000478 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
479 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000480 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
481 Att->getOwnKind() == OwnershipAttr::Holds);
482 if (StateI)
483 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000484 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000485 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000486}
487
Ted Kremenek8bef8232012-01-26 21:29:00 +0000488ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000489 const CallExpr *CE,
490 ProgramStateRef state,
491 unsigned Num,
492 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000493 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000494 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000495 if (!isa<DefinedOrUnknownSVal>(ArgVal))
496 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000497 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
498
499 // Check for null dereferences.
500 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000501 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000502
Anna Zaksb276bd92012-02-14 00:26:13 +0000503 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000504 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000505 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000506 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000507 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000508
Jordy Rose43859f62010-06-07 19:32:37 +0000509 // Unknown values could easily be okay
510 // Undefined values are handled elsewhere
511 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000512 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000513
Jordy Rose43859f62010-06-07 19:32:37 +0000514 const MemRegion *R = ArgVal.getAsRegion();
515
516 // Nonlocs can't be freed, of course.
517 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
518 if (!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 R = R->StripCasts();
524
525 // Blocks might show up as heap data, but should not be free()d
526 if (isa<BlockDataRegion>(R)) {
527 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000528 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000529 }
530
531 const MemSpaceRegion *MS = R->getMemorySpace();
532
533 // Parameters, locals, statics, and globals shouldn't be freed.
534 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
535 // FIXME: at the time this code was written, malloc() regions were
536 // represented by conjured symbols, which are all in UnknownSpaceRegion.
537 // This means that there isn't actually anything from HeapSpaceRegion
538 // that should be freed, even though we allow it here.
539 // Of course, free() can work on memory allocated outside the current
540 // function, so UnknownSpaceRegion is always a possibility.
541 // False negatives are better than false positives.
542
543 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000544 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000545 }
546
547 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
548 // Various cases could lead to non-symbol values here.
549 // For now, ignore them.
550 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000551 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000552
553 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000554 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000555
556 // If the symbol has not been tracked, return. This is possible when free() is
557 // called on a pointer that does not get its pointee directly from malloc().
558 // Full support of this requires inter-procedural analysis.
559 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000560 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000561
562 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000563 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000564 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000565 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000566 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000567 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000568 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000569 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000570 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000571 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000572 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000573 C.EmitReport(R);
574 }
Anna Zaksb319e022012-02-08 20:13:28 +0000575 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000576 }
577
578 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000579 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000580 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
581 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000582}
583
Ted Kremenek9c378f72011-08-12 23:37:29 +0000584bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000585 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
586 os << "an integer (" << IntVal->getValue() << ")";
587 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
588 os << "a constant address (" << ConstAddr->getValue() << ")";
589 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000590 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000591 else
592 return false;
593
594 return true;
595}
596
Ted Kremenek9c378f72011-08-12 23:37:29 +0000597bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000598 const MemRegion *MR) {
599 switch (MR->getKind()) {
600 case MemRegion::FunctionTextRegionKind: {
601 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
602 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000603 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000604 else
605 os << "the address of a function";
606 return true;
607 }
608 case MemRegion::BlockTextRegionKind:
609 os << "block text";
610 return true;
611 case MemRegion::BlockDataRegionKind:
612 // FIXME: where the block came from?
613 os << "a block";
614 return true;
615 default: {
616 const MemSpaceRegion *MS = MR->getMemorySpace();
617
Anna Zakseb31a762012-01-04 23:54:01 +0000618 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000619 const VarRegion *VR = dyn_cast<VarRegion>(MR);
620 const VarDecl *VD;
621 if (VR)
622 VD = VR->getDecl();
623 else
624 VD = NULL;
625
626 if (VD)
627 os << "the address of the local variable '" << VD->getName() << "'";
628 else
629 os << "the address of a local stack variable";
630 return true;
631 }
Anna Zakseb31a762012-01-04 23:54:01 +0000632
633 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000634 const VarRegion *VR = dyn_cast<VarRegion>(MR);
635 const VarDecl *VD;
636 if (VR)
637 VD = VR->getDecl();
638 else
639 VD = NULL;
640
641 if (VD)
642 os << "the address of the parameter '" << VD->getName() << "'";
643 else
644 os << "the address of a parameter";
645 return true;
646 }
Anna Zakseb31a762012-01-04 23:54:01 +0000647
648 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000649 const VarRegion *VR = dyn_cast<VarRegion>(MR);
650 const VarDecl *VD;
651 if (VR)
652 VD = VR->getDecl();
653 else
654 VD = NULL;
655
656 if (VD) {
657 if (VD->isStaticLocal())
658 os << "the address of the static variable '" << VD->getName() << "'";
659 else
660 os << "the address of the global variable '" << VD->getName() << "'";
661 } else
662 os << "the address of a global variable";
663 return true;
664 }
Anna Zakseb31a762012-01-04 23:54:01 +0000665
666 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000667 }
668 }
669}
670
671void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000672 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000673 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000674 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000675 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000676
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000677 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000678 llvm::raw_svector_ostream os(buf);
679
680 const MemRegion *MR = ArgVal.getAsRegion();
681 if (MR) {
682 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
683 MR = ER->getSuperRegion();
684
685 // Special case for alloca()
686 if (isa<AllocaRegion>(MR))
687 os << "Argument to free() was allocated by alloca(), not malloc()";
688 else {
689 os << "Argument to free() is ";
690 if (SummarizeRegion(os, MR))
691 os << ", which is not memory allocated by malloc()";
692 else
693 os << "not memory allocated by malloc()";
694 }
695 } else {
696 os << "Argument to free() is ";
697 if (SummarizeValue(os, ArgVal))
698 os << ", which is not memory allocated by malloc()";
699 else
700 os << "not memory allocated by malloc()";
701 }
702
Anna Zakse172e8b2011-08-17 23:00:25 +0000703 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000704 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000705 R->addRange(range);
706 C.EmitReport(R);
707 }
708}
709
Anna Zaks87cb5be2012-02-22 19:24:52 +0000710ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
711 const CallExpr *CE,
712 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000713 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000714 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000715 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000716 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
717 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000718 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000719 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000720
Ted Kremenek846eabd2010-12-01 21:28:31 +0000721 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000722
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000723 DefinedOrUnknownSVal PtrEQ =
724 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000725
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000726 // Get the size argument. If there is no size arg then give up.
727 const Expr *Arg1 = CE->getArg(1);
728 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000729 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000730
731 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000732 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
733 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000734 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000735 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000736
737 // Compare the size argument to 0.
738 DefinedOrUnknownSVal SizeZero =
739 svalBuilder.evalEQ(state, Arg1Val,
740 svalBuilder.makeIntValWithPtrWidth(0, false));
741
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000742 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
743 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
744 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
745 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
746 // We only assume exceptional states if they are definitely true; if the
747 // state is under-constrained, assume regular realloc behavior.
748 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
749 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
750
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000751 // If the ptr is NULL and the size is not 0, the call is equivalent to
752 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000753 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000754 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000755 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000756 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000757 }
758
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000759 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000760 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000761
Anna Zaks30838b92012-02-13 20:57:07 +0000762 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000763 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000764 SymbolRef FromPtr = arg0Val.getAsSymbol();
765 SVal RetVal = state->getSVal(CE, LCtx);
766 SymbolRef ToPtr = RetVal.getAsSymbol();
767 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000768 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000769
770 // If the size is 0, free the memory.
771 if (SizeIsZero)
772 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000773 // The semantics of the return value are:
774 // If size was equal to 0, either NULL or a pointer suitable to be passed
775 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000776 stateFree = stateFree->set<ReallocPairs>(ToPtr,
777 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000778 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000779 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000780 }
781
782 // Default behavior.
783 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
784 // FIXME: We should copy the content of the original buffer.
785 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
786 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000787 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000788 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000789 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
790 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000791 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000792 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000793 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000794 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000795}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000796
Anna Zaks87cb5be2012-02-22 19:24:52 +0000797ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Ted Kremenek8bef8232012-01-26 21:29:00 +0000798 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000799 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000800 const LocationContext *LCtx = C.getLocationContext();
801 SVal count = state->getSVal(CE->getArg(0), LCtx);
802 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000803 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
804 svalBuilder.getContext().getSizeType());
805 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000806
Anna Zaks87cb5be2012-02-22 19:24:52 +0000807 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000808}
809
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000810LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000811MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
812 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000813 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000814 // Walk the ExplodedGraph backwards and find the first node that referred to
815 // the tracked symbol.
816 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000817 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000818
819 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000820 ProgramStateRef State = N->getState();
821 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000822 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000823
824 // Find the most recent expression bound to the symbol in the current
825 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000826 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000827 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
828 SVal Val = State->getSVal(MR);
829 if (Val.getAsLocSymbol() == Sym)
830 ReferenceRegion = MR;
831 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000832 }
833
Anna Zaks7752d292012-02-27 23:40:55 +0000834 // Allocation node, is the last node in the current context in which the
835 // symbol was tracked.
836 if (N->getLocationContext() == LeakContext)
837 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000838 N = N->pred_empty() ? NULL : *(N->pred_begin());
839 }
840
841 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000842 const Stmt *AllocationStmt = 0;
843 if (isa<StmtPoint>(P))
844 AllocationStmt = cast<StmtPoint>(P).getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +0000845
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000846 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +0000847}
848
Anna Zaksda046772012-02-11 21:02:40 +0000849void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
850 CheckerContext &C) const {
851 assert(N);
852 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000853 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000854 // Leaks should not be reported if they are post-dominated by a sink:
855 // (1) Sinks are higher importance bugs.
856 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
857 // with __noreturn functions such as assert() or exit(). We choose not
858 // to report leaks on such paths.
859 BT_Leak->setSuppressOnSink(true);
860 }
861
Anna Zaksca8e36e2012-02-23 21:38:21 +0000862 // Most bug reports are cached at the location where they occurred.
863 // With leaks, we want to unique them by the location where they were
864 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000865 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000866 const Stmt *AllocStmt = 0;
867 const MemRegion *Region = 0;
868 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
869 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +0000870 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
871 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000872
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000873 SmallString<200> buf;
874 llvm::raw_svector_ostream os(buf);
875 os << "Memory is never released; potential leak";
876 if (Region) {
877 os << " of memory pointed to by '";
878 Region->dumpPretty(os);
879 os <<'\'';
880 }
881
882 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000883 R->markInteresting(Sym);
Anna Zaksda046772012-02-11 21:02:40 +0000884 R->addVisitor(new MallocBugVisitor(Sym));
885 C.EmitReport(R);
886}
887
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000888void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
889 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000890{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000891 if (!SymReaper.hasDeadSymbols())
892 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000893
Ted Kremenek8bef8232012-01-26 21:29:00 +0000894 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000895 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000896 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000897
Ted Kremenek217470e2011-07-28 23:07:51 +0000898 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000899 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000900 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
901 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000902 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000903 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000904 Errors.push_back(I->first);
905 }
Jordy Rose90760142010-08-18 04:33:47 +0000906 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000907 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000908
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000909 }
910 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000911
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000912 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000913 ReallocMap RP = state->get<ReallocPairs>();
914 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
915 if (SymReaper.isDead(I->first) ||
916 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000917 state = state->remove<ReallocPairs>(I->first);
918 }
919 }
920
Anna Zaksca8e36e2012-02-23 21:38:21 +0000921 // Generate leak node.
922 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
923 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000924
Anna Zaksca8e36e2012-02-23 21:38:21 +0000925 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000926 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000927 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
928 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000929 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000930 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000931 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000932}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000933
Anna Zaksda046772012-02-11 21:02:40 +0000934void MallocChecker::checkEndPath(CheckerContext &C) const {
935 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000936 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000937
Anna Zaksa19581a2012-02-20 22:25:23 +0000938 // If inside inlined call, skip it.
939 if (C.getLocationContext()->getParent() != 0)
940 return;
941
Jordy Rose09cef092010-08-18 04:26:59 +0000942 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000943 RefState RS = I->second;
944 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000945 ExplodedNode *N = C.addTransition(state);
946 if (N)
947 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000948 }
949 }
950}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000951
Anna Zaks91c2a112012-02-08 23:16:56 +0000952bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
953 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000954 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000955 const RefState *RS = state->get<RegionState>(Sym);
956 if (!RS)
957 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000958
Anna Zaks91c2a112012-02-08 23:16:56 +0000959 if (RS->isAllocated()) {
960 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
961 C.addTransition(state);
962 return true;
963 }
964 return false;
965}
966
Anna Zaks66c40402012-02-14 21:55:24 +0000967void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
968 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
969 return;
970
971 // Check use after free, when a freed pointer is passed to a call.
972 ProgramStateRef State = C.getState();
973 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
974 E = CE->arg_end(); I != E; ++I) {
975 const Expr *A = *I;
976 if (A->getType().getTypePtr()->isAnyPointerType()) {
977 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
978 if (!Sym)
979 continue;
980 if (checkUseAfterFree(Sym, C, A))
981 return;
982 }
983 }
984}
985
Anna Zaks91c2a112012-02-08 23:16:56 +0000986void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
987 const Expr *E = S->getRetValue();
988 if (!E)
989 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000990
991 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +0000992 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
993 SymbolRef Sym = RetVal.getAsSymbol();
994 if (!Sym)
995 // If we are returning a field of the allocated struct or an array element,
996 // the callee could still free the memory.
997 // TODO: This logic should be a part of generic symbol escape callback.
998 if (const MemRegion *MR = RetVal.getAsRegion())
999 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1000 if (const SymbolicRegion *BMR =
1001 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1002 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001003 if (!Sym)
1004 return;
1005
Anna Zaks0860cd02012-02-11 21:44:39 +00001006 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +00001007 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +00001008 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001009
Anna Zaksa19581a2012-02-20 22:25:23 +00001010 // If this function body is not inlined, check if the symbol is escaping.
1011 if (C.getLocationContext()->getParent() == 0)
1012 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001013}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001014
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001015// TODO: Blocks should be either inlined or should call invalidate regions
1016// upon invocation. After that's in place, special casing here will not be
1017// needed.
1018void MallocChecker::checkPostStmt(const BlockExpr *BE,
1019 CheckerContext &C) const {
1020
1021 // Scan the BlockDecRefExprs for any object the retain count checker
1022 // may be tracking.
1023 if (!BE->getBlockDecl()->hasCaptures())
1024 return;
1025
1026 ProgramStateRef state = C.getState();
1027 const BlockDataRegion *R =
1028 cast<BlockDataRegion>(state->getSVal(BE,
1029 C.getLocationContext()).getAsRegion());
1030
1031 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1032 E = R->referenced_vars_end();
1033
1034 if (I == E)
1035 return;
1036
1037 SmallVector<const MemRegion*, 10> Regions;
1038 const LocationContext *LC = C.getLocationContext();
1039 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1040
1041 for ( ; I != E; ++I) {
1042 const VarRegion *VR = *I;
1043 if (VR->getSuperRegion() == R) {
1044 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1045 }
1046 Regions.push_back(VR);
1047 }
1048
1049 state =
1050 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1051 Regions.data() + Regions.size()).getState();
1052 C.addTransition(state);
1053}
1054
Anna Zaks91c2a112012-02-08 23:16:56 +00001055bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1056 const Stmt *S) const {
1057 assert(Sym);
1058 const RefState *RS = C.getState()->get<RegionState>(Sym);
1059 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001060 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001061 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001062 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001063
Anna Zaksfebdc322012-02-16 22:26:12 +00001064 BugReport *R = new BugReport(*BT_UseFree,
1065 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001066 if (S)
1067 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001068 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001069 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001070 C.EmitReport(R);
1071 return true;
1072 }
1073 }
1074 return false;
1075}
1076
Zhongxing Xuc8023782010-03-10 04:58:55 +00001077// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001078void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1079 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001080 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001081 if (Sym)
1082 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001083}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001084
Anna Zaks4fb54872012-02-11 21:02:35 +00001085//===----------------------------------------------------------------------===//
1086// Check various ways a symbol can be invalidated.
1087// TODO: This logic (the next 3 functions) is copied/similar to the
1088// RetainRelease checker. We might want to factor this out.
1089//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001090
Anna Zaks4fb54872012-02-11 21:02:35 +00001091// Stop tracking symbols when a value escapes as a result of checkBind.
1092// A value escapes in three possible cases:
1093// (1) we are binding to something that is not a memory region.
1094// (2) we are binding to a memregion that does not have stack storage
1095// (3) we are binding to a memregion with stack storage that the store
1096// does not understand.
1097void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1098 CheckerContext &C) const {
1099 // Are we storing to something that causes the value to "escape"?
1100 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001101 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001102
Anna Zaks4fb54872012-02-11 21:02:35 +00001103 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1104 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001105
Anna Zaks4fb54872012-02-11 21:02:35 +00001106 if (!escapes) {
1107 // To test (3), generate a new state with the binding added. If it is
1108 // the same state, then it escapes (since the store cannot represent
1109 // the binding).
1110 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001111 }
Anna Zaksac593002012-02-16 03:40:57 +00001112 if (!escapes) {
1113 // Case 4: We do not currently model what happens when a symbol is
1114 // assigned to a struct field, so be conservative here and let the symbol
1115 // go. TODO: This could definitely be improved upon.
1116 escapes = !isa<VarRegion>(regionLoc->getRegion());
1117 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001118 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001119
1120 // If our store can represent the binding and we aren't storing to something
1121 // that doesn't have local storage then just return and have the simulation
1122 // state continue as is.
1123 if (!escapes)
1124 return;
1125
1126 // Otherwise, find all symbols referenced by 'val' that we are tracking
1127 // and stop tracking them.
1128 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1129 C.addTransition(state);
1130}
1131
1132// If a symbolic region is assumed to NULL (or another constant), stop tracking
1133// it - assuming that allocation failed on this path.
1134ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1135 SVal Cond,
1136 bool Assumption) const {
1137 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001138 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1139 // If the symbol is assumed to NULL or another constant, this will
1140 // return an APSInt*.
1141 if (state->getSymVal(I.getKey()))
1142 state = state->remove<RegionState>(I.getKey());
1143 }
1144
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001145 // Realloc returns 0 when reallocation fails, which means that we should
1146 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001147 ReallocMap RP = state->get<ReallocPairs>();
1148 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001149 // If the symbol is assumed to NULL or another constant, this will
1150 // return an APSInt*.
1151 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001152 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1153 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001154 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001155 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1156 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001157 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001158 }
1159 state = state->remove<ReallocPairs>(I.getKey());
1160 }
1161 }
1162
Anna Zaks4fb54872012-02-11 21:02:35 +00001163 return state;
1164}
1165
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001166// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001167// conservatively assume it can free/reallocate it's pointer arguments.
1168// (We assume that the pointers cannot escape through calls to system
1169// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001170bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1171 ProgramStateRef State) const {
1172 if (!Call)
1173 return false;
1174
1175 // For now, assume that any C++ call can free memory.
1176 // TODO: If we want to be more optimistic here, we'll need to make sure that
1177 // regions escape to C++ containers. They seem to do that even now, but for
1178 // mysterious reasons.
1179 if (Call->isCXXCall())
1180 return false;
1181
1182 const Decl *D = Call->getDecl();
1183 if (!D)
1184 return false;
1185
Anna Zaks66c40402012-02-14 21:55:24 +00001186 ASTContext &ASTC = State->getStateManager().getContext();
1187
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001188 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001189 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001190 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1191 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001192 }
1193
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001194 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001195 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001196 if (!SM.isInSystemHeader(D->getLocation()))
1197 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001198
Anna Zaks07d39a42012-02-28 01:54:22 +00001199 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001200 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001201 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001202 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001203 if (!II)
1204 return true;
1205 StringRef FName = II->getName();
1206
1207 // White list thread local storage.
1208 if (FName.equals("pthread_setspecific"))
1209 return false;
1210
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001211 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001212 if (FName.endswith("NoCopy")) {
1213 // Look for the deallocator argument. We know that the memory ownership
1214 // is not transfered only if the deallocator argument is
1215 // 'kCFAllocatorNull'.
1216 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1217 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1218 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1219 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1220 if (DeallocatorName == "kCFAllocatorNull")
1221 return true;
1222 }
1223 }
1224 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001225 }
1226
Anna Zaksca23eb22012-02-29 18:42:47 +00001227 // PR12101
1228 // Many CoreFoundation and CoreGraphics might allow a tracked object
1229 // to escape.
1230 if (Call->isCFCGAllowingEscape(FName))
1231 return false;
1232
1233 // Associating streams with malloced buffers. The pointer can escape if
1234 // 'closefn' is specified (and if that function does free memory).
1235 // Currently, we do not inspect the 'closefn' function (PR12101).
1236 if (FName == "funopen")
1237 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1238 return false;
1239
1240 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1241 // these leaks might be intentional when setting the buffer for stdio.
1242 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1243 if (FName == "setbuf" || FName =="setbuffer" ||
1244 FName == "setlinebuf" || FName == "setvbuf") {
1245 if (Call->getNumArgs() >= 1)
1246 if (const DeclRefExpr *Arg =
1247 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1248 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1249 if (D->getCanonicalDecl()->getName().find("std")
1250 != StringRef::npos)
1251 return false;
1252 }
1253
1254 // A bunch of other functions, which take ownership of a pointer (See retain
1255 // release checker). Not all the parameters here are invalidated, but the
1256 // Malloc checker cannot differentiate between them. The right way of doing
1257 // this would be to implement a pointer escapes callback.
1258 if (FName == "CVPixelBufferCreateWithBytes" ||
1259 FName == "CGBitmapContextCreateWithData" ||
Anna Zaks4cd7edf2012-03-26 18:18:39 +00001260 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1261 FName == "OSAtomicEnqueue") {
Anna Zaksca23eb22012-02-29 18:42:47 +00001262 return false;
1263 }
1264
Anna Zaks0d389b82012-02-23 01:05:27 +00001265 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001266 // Most system calls, do not free the memory.
1267 return true;
1268
1269 // Process ObjC functions.
1270 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1271 Selector S = ObjCD->getSelector();
1272
1273 // White list the ObjC functions which do free memory.
1274 // - Anything containing 'freeWhenDone' param set to 1.
1275 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1276 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1277 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1278 if (Call->getArgSVal(i).isConstant(1))
1279 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001280 else
1281 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001282 }
1283 }
1284
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001285 // If the first selector ends with NoCopy, assume that the ownership is
1286 // transfered as well.
1287 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1288 if (S.getNameForSlot(0).endswith("NoCopy")) {
1289 return false;
1290 }
1291
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001292 // Otherwise, assume that the function does not free memory.
1293 // Most system calls, do not free the memory.
1294 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001295 }
1296
1297 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001298 return false;
1299
Anna Zaks66c40402012-02-14 21:55:24 +00001300}
1301
Anna Zaks4fb54872012-02-11 21:02:35 +00001302// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1303// escapes, when we are tracking p), do not track the symbol as we cannot reason
1304// about it anymore.
1305ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001306MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001307 const StoreManager::InvalidatedSymbols *invalidated,
1308 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001309 ArrayRef<const MemRegion *> Regions,
1310 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001311 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001312 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001313 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001314
Anna Zaks66c40402012-02-14 21:55:24 +00001315 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001316 // regions (explicit and implicit) escaped.
1317
1318 // Otherwise, whitelist explicit pointers; we still can track them.
1319 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001320 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1321 E = ExplicitRegions.end(); I != E; ++I) {
1322 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1323 WhitelistedSymbols.insert(R->getSymbol());
1324 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001325 }
1326
1327 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1328 E = invalidated->end(); I!=E; ++I) {
1329 SymbolRef sym = *I;
1330 if (WhitelistedSymbols.count(sym))
1331 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001332 // The symbol escaped.
1333 if (const RefState *RS = State->get<RegionState>(sym))
1334 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001335 }
Anna Zaks66c40402012-02-14 21:55:24 +00001336 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001337}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001338
Jordy Rose393f98b2012-03-18 07:43:35 +00001339static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1340 ProgramStateRef prevState) {
1341 ReallocMap currMap = currState->get<ReallocPairs>();
1342 ReallocMap prevMap = prevState->get<ReallocPairs>();
1343
1344 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1345 I != E; ++I) {
1346 SymbolRef sym = I.getKey();
1347 if (!currMap.lookup(sym))
1348 return sym;
1349 }
1350
1351 return NULL;
1352}
1353
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001354PathDiagnosticPiece *
1355MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1356 const ExplodedNode *PrevN,
1357 BugReporterContext &BRC,
1358 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001359 ProgramStateRef state = N->getState();
1360 ProgramStateRef statePrev = PrevN->getState();
1361
1362 const RefState *RS = state->get<RegionState>(Sym);
1363 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001364 if (!RS && !RSPrev)
1365 return 0;
1366
Anna Zaksfe571602012-02-16 22:26:07 +00001367 const Stmt *S = 0;
1368 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001369 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001370
1371 // Retrieve the associated statement.
1372 ProgramPoint ProgLoc = N->getLocation();
1373 if (isa<StmtPoint>(ProgLoc))
1374 S = cast<StmtPoint>(ProgLoc).getStmt();
1375 // If an assumption was made on a branch, it should be caught
1376 // here by looking at the state transition.
1377 if (isa<BlockEdge>(ProgLoc)) {
1378 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1379 S = srcBlk->getTerminator();
1380 }
1381 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001382 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001383
1384 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001385 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001386 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001387 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001388 StackHint = new StackHintGeneratorForSymbol(Sym,
1389 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001390 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001391 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001392 StackHint = new StackHintGeneratorForSymbol(Sym,
1393 "Returned released memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001394 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001395 Mode = ReallocationFailed;
1396 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001397 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001398 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001399
Jordy Roseb000fb52012-03-24 03:15:09 +00001400 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1401 // Is it possible to fail two reallocs WITHOUT testing in between?
1402 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1403 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001404 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001405 FailedReallocSymbol = sym;
1406 }
Anna Zaksfe571602012-02-16 22:26:07 +00001407 }
1408
1409 // We are in a special mode if a reallocation failed later in the path.
1410 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001411 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001412
Jordy Roseb000fb52012-03-24 03:15:09 +00001413 // Is this is the first appearance of the reallocated symbol?
1414 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
1415 // If we ever hit this assert, that means BugReporter has decided to skip
1416 // node pairs or visit them out of order.
1417 assert(state->get<RegionState>(FailedReallocSymbol) &&
1418 "Missed the reallocation point");
1419
1420 // We're at the reallocation point.
1421 Msg = "Attempt to reallocate memory";
1422 StackHint = new StackHintGeneratorForSymbol(Sym,
1423 "Returned reallocated memory");
1424 FailedReallocSymbol = NULL;
1425 Mode = Normal;
1426 }
Anna Zaksfe571602012-02-16 22:26:07 +00001427 }
1428
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001429 if (!Msg)
1430 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001431 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001432
1433 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001434 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001435 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001436 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001437}
1438
1439
Anna Zaks231361a2012-02-08 23:16:52 +00001440#define REGISTER_CHECKER(name) \
1441void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001442 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001443 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001444}
Anna Zaks231361a2012-02-08 23:16:52 +00001445
1446REGISTER_CHECKER(MallocPessimistic)
1447REGISTER_CHECKER(MallocOptimistic)