blob: 8bce88a769771c068922ea490e206844f4c6a681 [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 Zaks259052d2012-04-10 23:41:11 +0000371 if (CE->getNumArgs() < 1)
372 return;
Anna Zaks87cb5be2012-02-22 19:24:52 +0000373 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000374 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000375 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000376 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000377 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000378 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000379 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000380 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000381 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000382 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000383 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000384 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000385 State = MallocUpdateRefState(C, CE, State);
386 } else if (Filter.CMallocOptimistic) {
387 // Check all the attributes, if there are any.
388 // There can be multiple of these attributes.
389 if (FD->hasAttrs())
390 for (specific_attr_iterator<OwnershipAttr>
391 i = FD->specific_attr_begin<OwnershipAttr>(),
392 e = FD->specific_attr_end<OwnershipAttr>();
393 i != e; ++i) {
394 switch ((*i)->getOwnKind()) {
395 case OwnershipAttr::Returns:
396 State = MallocMemReturnsAttr(C, CE, *i);
397 break;
398 case OwnershipAttr::Takes:
399 case OwnershipAttr::Holds:
400 State = FreeMemAttr(C, CE, *i);
401 break;
402 }
403 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000404 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000405 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000406}
407
Anna Zaks87cb5be2012-02-22 19:24:52 +0000408ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
409 const CallExpr *CE,
410 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000411 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000412 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000413
Sean Huntcf807c42010-08-18 23:23:40 +0000414 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000415 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000416 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000417 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000418 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000419}
420
Anna Zaksb319e022012-02-08 20:13:28 +0000421ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000422 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000423 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000424 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000425 // Get the return value.
426 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000427
Anna Zaksb16ce452012-02-15 00:11:22 +0000428 // We expect the malloc functions to return a pointer.
429 if (!isa<Loc>(retVal))
430 return 0;
431
Jordy Rose32f26562010-07-04 00:00:41 +0000432 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000433 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000434
Jordy Rose32f26562010-07-04 00:00:41 +0000435 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000436 const SymbolicRegion *R =
437 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000438 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000439 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000440 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000441 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000442 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
443 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
444 DefinedOrUnknownSVal extentMatchesSize =
445 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000446
Anna Zaks60a1fa42012-02-22 03:14:20 +0000447 state = state->assume(extentMatchesSize, true);
448 assert(state);
449 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000450
Anna Zaks87cb5be2012-02-22 19:24:52 +0000451 return MallocUpdateRefState(C, CE, state);
452}
453
454ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
455 const CallExpr *CE,
456 ProgramStateRef state) {
457 // Get the return value.
458 SVal retVal = state->getSVal(CE, C.getLocationContext());
459
460 // We expect the malloc functions to return a pointer.
461 if (!isa<Loc>(retVal))
462 return 0;
463
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000464 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000465 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000466
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000467 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000468 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000469
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000470}
471
Anna Zaks87cb5be2012-02-22 19:24:52 +0000472ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
473 const CallExpr *CE,
474 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000475 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000476 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000477
Anna Zaksb3d72752012-03-01 22:06:06 +0000478 ProgramStateRef State = C.getState();
479
Sean Huntcf807c42010-08-18 23:23:40 +0000480 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
481 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000482 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
483 Att->getOwnKind() == OwnershipAttr::Holds);
484 if (StateI)
485 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000486 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000487 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000488}
489
Ted Kremenek8bef8232012-01-26 21:29:00 +0000490ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000491 const CallExpr *CE,
492 ProgramStateRef state,
493 unsigned Num,
494 bool Hold) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000495 if (CE->getNumArgs() < (Num + 1))
496 return 0;
497
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000498 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000499 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000500 if (!isa<DefinedOrUnknownSVal>(ArgVal))
501 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000502 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
503
504 // Check for null dereferences.
505 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000506 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000507
Anna Zaksb276bd92012-02-14 00:26:13 +0000508 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000509 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000510 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000511 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000512 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000513
Jordy Rose43859f62010-06-07 19:32:37 +0000514 // Unknown values could easily be okay
515 // Undefined values are handled elsewhere
516 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000517 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000518
Jordy Rose43859f62010-06-07 19:32:37 +0000519 const MemRegion *R = ArgVal.getAsRegion();
520
521 // Nonlocs can't be freed, of course.
522 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
523 if (!R) {
524 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000525 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000526 }
527
528 R = R->StripCasts();
529
530 // Blocks might show up as heap data, but should not be free()d
531 if (isa<BlockDataRegion>(R)) {
532 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000533 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000534 }
535
536 const MemSpaceRegion *MS = R->getMemorySpace();
537
538 // Parameters, locals, statics, and globals shouldn't be freed.
539 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
540 // FIXME: at the time this code was written, malloc() regions were
541 // represented by conjured symbols, which are all in UnknownSpaceRegion.
542 // This means that there isn't actually anything from HeapSpaceRegion
543 // that should be freed, even though we allow it here.
544 // Of course, free() can work on memory allocated outside the current
545 // function, so UnknownSpaceRegion is always a possibility.
546 // False negatives are better than false positives.
547
548 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000549 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000550 }
551
552 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
553 // Various cases could lead to non-symbol values here.
554 // For now, ignore them.
555 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000556 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000557
558 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000559 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000560
561 // If the symbol has not been tracked, return. This is possible when free() is
562 // called on a pointer that does not get its pointee directly from malloc().
563 // Full support of this requires inter-procedural analysis.
564 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000565 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000566
567 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000568 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000569 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000570 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000571 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000572 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000573 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000574 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000575 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000576 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000577 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000578 C.EmitReport(R);
579 }
Anna Zaksb319e022012-02-08 20:13:28 +0000580 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000581 }
582
583 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000584 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000585 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
586 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000587}
588
Ted Kremenek9c378f72011-08-12 23:37:29 +0000589bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000590 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
591 os << "an integer (" << IntVal->getValue() << ")";
592 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
593 os << "a constant address (" << ConstAddr->getValue() << ")";
594 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000595 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000596 else
597 return false;
598
599 return true;
600}
601
Ted Kremenek9c378f72011-08-12 23:37:29 +0000602bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000603 const MemRegion *MR) {
604 switch (MR->getKind()) {
605 case MemRegion::FunctionTextRegionKind: {
606 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
607 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000608 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000609 else
610 os << "the address of a function";
611 return true;
612 }
613 case MemRegion::BlockTextRegionKind:
614 os << "block text";
615 return true;
616 case MemRegion::BlockDataRegionKind:
617 // FIXME: where the block came from?
618 os << "a block";
619 return true;
620 default: {
621 const MemSpaceRegion *MS = MR->getMemorySpace();
622
Anna Zakseb31a762012-01-04 23:54:01 +0000623 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000624 const VarRegion *VR = dyn_cast<VarRegion>(MR);
625 const VarDecl *VD;
626 if (VR)
627 VD = VR->getDecl();
628 else
629 VD = NULL;
630
631 if (VD)
632 os << "the address of the local variable '" << VD->getName() << "'";
633 else
634 os << "the address of a local stack variable";
635 return true;
636 }
Anna Zakseb31a762012-01-04 23:54:01 +0000637
638 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000639 const VarRegion *VR = dyn_cast<VarRegion>(MR);
640 const VarDecl *VD;
641 if (VR)
642 VD = VR->getDecl();
643 else
644 VD = NULL;
645
646 if (VD)
647 os << "the address of the parameter '" << VD->getName() << "'";
648 else
649 os << "the address of a parameter";
650 return true;
651 }
Anna Zakseb31a762012-01-04 23:54:01 +0000652
653 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000654 const VarRegion *VR = dyn_cast<VarRegion>(MR);
655 const VarDecl *VD;
656 if (VR)
657 VD = VR->getDecl();
658 else
659 VD = NULL;
660
661 if (VD) {
662 if (VD->isStaticLocal())
663 os << "the address of the static variable '" << VD->getName() << "'";
664 else
665 os << "the address of the global variable '" << VD->getName() << "'";
666 } else
667 os << "the address of a global variable";
668 return true;
669 }
Anna Zakseb31a762012-01-04 23:54:01 +0000670
671 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000672 }
673 }
674}
675
676void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000677 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000678 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000679 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000680 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000681
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000682 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000683 llvm::raw_svector_ostream os(buf);
684
685 const MemRegion *MR = ArgVal.getAsRegion();
686 if (MR) {
687 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
688 MR = ER->getSuperRegion();
689
690 // Special case for alloca()
691 if (isa<AllocaRegion>(MR))
692 os << "Argument to free() was allocated by alloca(), not malloc()";
693 else {
694 os << "Argument to free() is ";
695 if (SummarizeRegion(os, MR))
696 os << ", which is not memory allocated by malloc()";
697 else
698 os << "not memory allocated by malloc()";
699 }
700 } else {
701 os << "Argument to free() is ";
702 if (SummarizeValue(os, ArgVal))
703 os << ", which is not memory allocated by malloc()";
704 else
705 os << "not memory allocated by malloc()";
706 }
707
Anna Zakse172e8b2011-08-17 23:00:25 +0000708 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000709 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000710 R->addRange(range);
711 C.EmitReport(R);
712 }
713}
714
Anna Zaks87cb5be2012-02-22 19:24:52 +0000715ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
716 const CallExpr *CE,
717 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000718 if (CE->getNumArgs() < 2)
719 return 0;
720
Ted Kremenek8bef8232012-01-26 21:29:00 +0000721 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000722 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000723 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000724 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
725 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000726 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000727 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000728
Ted Kremenek846eabd2010-12-01 21:28:31 +0000729 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000730
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000731 DefinedOrUnknownSVal PtrEQ =
732 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000733
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000734 // Get the size argument. If there is no size arg then give up.
735 const Expr *Arg1 = CE->getArg(1);
736 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000737 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000738
739 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000740 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
741 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000742 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000743 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000744
745 // Compare the size argument to 0.
746 DefinedOrUnknownSVal SizeZero =
747 svalBuilder.evalEQ(state, Arg1Val,
748 svalBuilder.makeIntValWithPtrWidth(0, false));
749
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000750 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
751 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
752 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
753 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
754 // We only assume exceptional states if they are definitely true; if the
755 // state is under-constrained, assume regular realloc behavior.
756 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
757 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
758
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000759 // If the ptr is NULL and the size is not 0, the call is equivalent to
760 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000761 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000762 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000763 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000764 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000765 }
766
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000767 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000768 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000769
Anna Zaks30838b92012-02-13 20:57:07 +0000770 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000771 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000772 SymbolRef FromPtr = arg0Val.getAsSymbol();
773 SVal RetVal = state->getSVal(CE, LCtx);
774 SymbolRef ToPtr = RetVal.getAsSymbol();
775 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000776 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000777
778 // If the size is 0, free the memory.
779 if (SizeIsZero)
780 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000781 // The semantics of the return value are:
782 // If size was equal to 0, either NULL or a pointer suitable to be passed
783 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000784 stateFree = stateFree->set<ReallocPairs>(ToPtr,
785 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000786 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000787 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000788 }
789
790 // Default behavior.
791 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
792 // FIXME: We should copy the content of the original buffer.
793 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
794 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000795 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000796 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000797 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
798 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000799 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000800 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000801 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000802 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000803}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000804
Anna Zaks87cb5be2012-02-22 19:24:52 +0000805ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000806 if (CE->getNumArgs() < 2)
807 return 0;
808
Ted Kremenek8bef8232012-01-26 21:29:00 +0000809 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000810 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000811 const LocationContext *LCtx = C.getLocationContext();
812 SVal count = state->getSVal(CE->getArg(0), LCtx);
813 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000814 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
815 svalBuilder.getContext().getSizeType());
816 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000817
Anna Zaks87cb5be2012-02-22 19:24:52 +0000818 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000819}
820
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000821LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000822MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
823 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000824 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000825 // Walk the ExplodedGraph backwards and find the first node that referred to
826 // the tracked symbol.
827 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000828 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000829
830 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000831 ProgramStateRef State = N->getState();
832 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000833 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000834
835 // Find the most recent expression bound to the symbol in the current
836 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000837 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000838 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
839 SVal Val = State->getSVal(MR);
840 if (Val.getAsLocSymbol() == Sym)
841 ReferenceRegion = MR;
842 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000843 }
844
Anna Zaks7752d292012-02-27 23:40:55 +0000845 // Allocation node, is the last node in the current context in which the
846 // symbol was tracked.
847 if (N->getLocationContext() == LeakContext)
848 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000849 N = N->pred_empty() ? NULL : *(N->pred_begin());
850 }
851
852 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000853 const Stmt *AllocationStmt = 0;
854 if (isa<StmtPoint>(P))
855 AllocationStmt = cast<StmtPoint>(P).getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +0000856
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000857 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +0000858}
859
Anna Zaksda046772012-02-11 21:02:40 +0000860void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
861 CheckerContext &C) const {
862 assert(N);
863 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000864 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000865 // Leaks should not be reported if they are post-dominated by a sink:
866 // (1) Sinks are higher importance bugs.
867 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
868 // with __noreturn functions such as assert() or exit(). We choose not
869 // to report leaks on such paths.
870 BT_Leak->setSuppressOnSink(true);
871 }
872
Anna Zaksca8e36e2012-02-23 21:38:21 +0000873 // Most bug reports are cached at the location where they occurred.
874 // With leaks, we want to unique them by the location where they were
875 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000876 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000877 const Stmt *AllocStmt = 0;
878 const MemRegion *Region = 0;
879 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
880 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +0000881 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
882 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000883
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000884 SmallString<200> buf;
885 llvm::raw_svector_ostream os(buf);
886 os << "Memory is never released; potential leak";
887 if (Region) {
888 os << " of memory pointed to by '";
889 Region->dumpPretty(os);
890 os <<'\'';
891 }
892
893 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000894 R->markInteresting(Sym);
Anna Zaksda046772012-02-11 21:02:40 +0000895 R->addVisitor(new MallocBugVisitor(Sym));
896 C.EmitReport(R);
897}
898
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000899void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
900 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000901{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000902 if (!SymReaper.hasDeadSymbols())
903 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000904
Ted Kremenek8bef8232012-01-26 21:29:00 +0000905 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000906 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000907 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000908
Ted Kremenek217470e2011-07-28 23:07:51 +0000909 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000910 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000911 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
912 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000913 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000914 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000915 Errors.push_back(I->first);
916 }
Jordy Rose90760142010-08-18 04:33:47 +0000917 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000918 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000919
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000920 }
921 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000922
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000923 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000924 ReallocMap RP = state->get<ReallocPairs>();
925 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
926 if (SymReaper.isDead(I->first) ||
927 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000928 state = state->remove<ReallocPairs>(I->first);
929 }
930 }
931
Anna Zaksca8e36e2012-02-23 21:38:21 +0000932 // Generate leak node.
933 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
934 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000935
Anna Zaksca8e36e2012-02-23 21:38:21 +0000936 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000937 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000938 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
939 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000940 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000941 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000942 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000943}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000944
Anna Zaksda046772012-02-11 21:02:40 +0000945void MallocChecker::checkEndPath(CheckerContext &C) const {
946 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000947 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000948
Anna Zaksa19581a2012-02-20 22:25:23 +0000949 // If inside inlined call, skip it.
950 if (C.getLocationContext()->getParent() != 0)
951 return;
952
Jordy Rose09cef092010-08-18 04:26:59 +0000953 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000954 RefState RS = I->second;
955 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000956 ExplodedNode *N = C.addTransition(state);
957 if (N)
958 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000959 }
960 }
961}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000962
Anna Zaks91c2a112012-02-08 23:16:56 +0000963bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
964 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000965 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000966 const RefState *RS = state->get<RegionState>(Sym);
967 if (!RS)
968 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000969
Anna Zaks91c2a112012-02-08 23:16:56 +0000970 if (RS->isAllocated()) {
971 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
972 C.addTransition(state);
973 return true;
974 }
975 return false;
976}
977
Anna Zaks66c40402012-02-14 21:55:24 +0000978void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
979 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
980 return;
981
982 // Check use after free, when a freed pointer is passed to a call.
983 ProgramStateRef State = C.getState();
984 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
985 E = CE->arg_end(); I != E; ++I) {
986 const Expr *A = *I;
987 if (A->getType().getTypePtr()->isAnyPointerType()) {
988 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
989 if (!Sym)
990 continue;
991 if (checkUseAfterFree(Sym, C, A))
992 return;
993 }
994 }
995}
996
Anna Zaks91c2a112012-02-08 23:16:56 +0000997void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
998 const Expr *E = S->getRetValue();
999 if (!E)
1000 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001001
1002 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001003 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
1004 SymbolRef Sym = RetVal.getAsSymbol();
1005 if (!Sym)
1006 // If we are returning a field of the allocated struct or an array element,
1007 // the callee could still free the memory.
1008 // TODO: This logic should be a part of generic symbol escape callback.
1009 if (const MemRegion *MR = RetVal.getAsRegion())
1010 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1011 if (const SymbolicRegion *BMR =
1012 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1013 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001014 if (!Sym)
1015 return;
1016
Anna Zaks0860cd02012-02-11 21:44:39 +00001017 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +00001018 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +00001019 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001020
Anna Zaksa19581a2012-02-20 22:25:23 +00001021 // If this function body is not inlined, check if the symbol is escaping.
1022 if (C.getLocationContext()->getParent() == 0)
1023 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001024}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001025
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001026// TODO: Blocks should be either inlined or should call invalidate regions
1027// upon invocation. After that's in place, special casing here will not be
1028// needed.
1029void MallocChecker::checkPostStmt(const BlockExpr *BE,
1030 CheckerContext &C) const {
1031
1032 // Scan the BlockDecRefExprs for any object the retain count checker
1033 // may be tracking.
1034 if (!BE->getBlockDecl()->hasCaptures())
1035 return;
1036
1037 ProgramStateRef state = C.getState();
1038 const BlockDataRegion *R =
1039 cast<BlockDataRegion>(state->getSVal(BE,
1040 C.getLocationContext()).getAsRegion());
1041
1042 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1043 E = R->referenced_vars_end();
1044
1045 if (I == E)
1046 return;
1047
1048 SmallVector<const MemRegion*, 10> Regions;
1049 const LocationContext *LC = C.getLocationContext();
1050 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1051
1052 for ( ; I != E; ++I) {
1053 const VarRegion *VR = *I;
1054 if (VR->getSuperRegion() == R) {
1055 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1056 }
1057 Regions.push_back(VR);
1058 }
1059
1060 state =
1061 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1062 Regions.data() + Regions.size()).getState();
1063 C.addTransition(state);
1064}
1065
Anna Zaks91c2a112012-02-08 23:16:56 +00001066bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1067 const Stmt *S) const {
1068 assert(Sym);
1069 const RefState *RS = C.getState()->get<RegionState>(Sym);
1070 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001071 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001072 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001073 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001074
Anna Zaksfebdc322012-02-16 22:26:12 +00001075 BugReport *R = new BugReport(*BT_UseFree,
1076 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001077 if (S)
1078 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001079 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001080 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001081 C.EmitReport(R);
1082 return true;
1083 }
1084 }
1085 return false;
1086}
1087
Zhongxing Xuc8023782010-03-10 04:58:55 +00001088// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001089void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1090 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001091 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001092 if (Sym)
1093 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001094}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001095
Anna Zaks4fb54872012-02-11 21:02:35 +00001096//===----------------------------------------------------------------------===//
1097// Check various ways a symbol can be invalidated.
1098// TODO: This logic (the next 3 functions) is copied/similar to the
1099// RetainRelease checker. We might want to factor this out.
1100//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001101
Anna Zaks4fb54872012-02-11 21:02:35 +00001102// Stop tracking symbols when a value escapes as a result of checkBind.
1103// A value escapes in three possible cases:
1104// (1) we are binding to something that is not a memory region.
1105// (2) we are binding to a memregion that does not have stack storage
1106// (3) we are binding to a memregion with stack storage that the store
1107// does not understand.
1108void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1109 CheckerContext &C) const {
1110 // Are we storing to something that causes the value to "escape"?
1111 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001112 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001113
Anna Zaks4fb54872012-02-11 21:02:35 +00001114 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1115 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001116
Anna Zaks4fb54872012-02-11 21:02:35 +00001117 if (!escapes) {
1118 // To test (3), generate a new state with the binding added. If it is
1119 // the same state, then it escapes (since the store cannot represent
1120 // the binding).
1121 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001122 }
Anna Zaksac593002012-02-16 03:40:57 +00001123 if (!escapes) {
1124 // Case 4: We do not currently model what happens when a symbol is
1125 // assigned to a struct field, so be conservative here and let the symbol
1126 // go. TODO: This could definitely be improved upon.
1127 escapes = !isa<VarRegion>(regionLoc->getRegion());
1128 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001129 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001130
1131 // If our store can represent the binding and we aren't storing to something
1132 // that doesn't have local storage then just return and have the simulation
1133 // state continue as is.
1134 if (!escapes)
1135 return;
1136
1137 // Otherwise, find all symbols referenced by 'val' that we are tracking
1138 // and stop tracking them.
1139 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1140 C.addTransition(state);
1141}
1142
1143// If a symbolic region is assumed to NULL (or another constant), stop tracking
1144// it - assuming that allocation failed on this path.
1145ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1146 SVal Cond,
1147 bool Assumption) const {
1148 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001149 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1150 // If the symbol is assumed to NULL or another constant, this will
1151 // return an APSInt*.
1152 if (state->getSymVal(I.getKey()))
1153 state = state->remove<RegionState>(I.getKey());
1154 }
1155
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001156 // Realloc returns 0 when reallocation fails, which means that we should
1157 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001158 ReallocMap RP = state->get<ReallocPairs>();
1159 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001160 // If the symbol is assumed to NULL or another constant, this will
1161 // return an APSInt*.
1162 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001163 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1164 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001165 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001166 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1167 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001168 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001169 }
1170 state = state->remove<ReallocPairs>(I.getKey());
1171 }
1172 }
1173
Anna Zaks4fb54872012-02-11 21:02:35 +00001174 return state;
1175}
1176
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001177// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001178// conservatively assume it can free/reallocate it's pointer arguments.
1179// (We assume that the pointers cannot escape through calls to system
1180// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001181bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1182 ProgramStateRef State) const {
1183 if (!Call)
1184 return false;
1185
1186 // For now, assume that any C++ call can free memory.
1187 // TODO: If we want to be more optimistic here, we'll need to make sure that
1188 // regions escape to C++ containers. They seem to do that even now, but for
1189 // mysterious reasons.
1190 if (Call->isCXXCall())
1191 return false;
1192
1193 const Decl *D = Call->getDecl();
1194 if (!D)
1195 return false;
1196
Anna Zaks66c40402012-02-14 21:55:24 +00001197 ASTContext &ASTC = State->getStateManager().getContext();
1198
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001199 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001200 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001201 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1202 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001203 }
1204
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001205 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001206 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001207 if (!SM.isInSystemHeader(D->getLocation()))
1208 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001209
Anna Zaks07d39a42012-02-28 01:54:22 +00001210 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001211 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001212 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001213 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001214 if (!II)
1215 return true;
1216 StringRef FName = II->getName();
1217
1218 // White list thread local storage.
1219 if (FName.equals("pthread_setspecific"))
1220 return false;
1221
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001222 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001223 if (FName.endswith("NoCopy")) {
1224 // Look for the deallocator argument. We know that the memory ownership
1225 // is not transfered only if the deallocator argument is
1226 // 'kCFAllocatorNull'.
1227 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1228 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1229 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1230 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1231 if (DeallocatorName == "kCFAllocatorNull")
1232 return true;
1233 }
1234 }
1235 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001236 }
1237
Anna Zaksca23eb22012-02-29 18:42:47 +00001238 // PR12101
1239 // Many CoreFoundation and CoreGraphics might allow a tracked object
1240 // to escape.
1241 if (Call->isCFCGAllowingEscape(FName))
1242 return false;
1243
1244 // Associating streams with malloced buffers. The pointer can escape if
1245 // 'closefn' is specified (and if that function does free memory).
1246 // Currently, we do not inspect the 'closefn' function (PR12101).
1247 if (FName == "funopen")
1248 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1249 return false;
1250
1251 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1252 // these leaks might be intentional when setting the buffer for stdio.
1253 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1254 if (FName == "setbuf" || FName =="setbuffer" ||
1255 FName == "setlinebuf" || FName == "setvbuf") {
1256 if (Call->getNumArgs() >= 1)
1257 if (const DeclRefExpr *Arg =
1258 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1259 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1260 if (D->getCanonicalDecl()->getName().find("std")
1261 != StringRef::npos)
1262 return false;
1263 }
1264
1265 // A bunch of other functions, which take ownership of a pointer (See retain
1266 // release checker). Not all the parameters here are invalidated, but the
1267 // Malloc checker cannot differentiate between them. The right way of doing
1268 // this would be to implement a pointer escapes callback.
1269 if (FName == "CVPixelBufferCreateWithBytes" ||
1270 FName == "CGBitmapContextCreateWithData" ||
Anna Zaks4cd7edf2012-03-26 18:18:39 +00001271 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1272 FName == "OSAtomicEnqueue") {
Anna Zaksca23eb22012-02-29 18:42:47 +00001273 return false;
1274 }
1275
Anna Zaks62a5c342012-03-30 05:48:16 +00001276 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1277 // be deallocated by NSMapRemove.
1278 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
1279 return false;
1280
Anna Zaks0d389b82012-02-23 01:05:27 +00001281 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001282 // Most system calls, do not free the memory.
1283 return true;
1284
1285 // Process ObjC functions.
1286 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1287 Selector S = ObjCD->getSelector();
1288
1289 // White list the ObjC functions which do free memory.
1290 // - Anything containing 'freeWhenDone' param set to 1.
1291 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1292 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1293 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1294 if (Call->getArgSVal(i).isConstant(1))
1295 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001296 else
1297 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001298 }
1299 }
1300
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001301 // If the first selector ends with NoCopy, assume that the ownership is
1302 // transfered as well.
1303 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1304 if (S.getNameForSlot(0).endswith("NoCopy")) {
1305 return false;
1306 }
1307
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001308 // Otherwise, assume that the function does not free memory.
1309 // Most system calls, do not free the memory.
1310 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001311 }
1312
1313 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001314 return false;
1315
Anna Zaks66c40402012-02-14 21:55:24 +00001316}
1317
Anna Zaks4fb54872012-02-11 21:02:35 +00001318// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1319// escapes, when we are tracking p), do not track the symbol as we cannot reason
1320// about it anymore.
1321ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001322MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001323 const StoreManager::InvalidatedSymbols *invalidated,
1324 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001325 ArrayRef<const MemRegion *> Regions,
1326 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001327 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001328 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001329 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001330
Anna Zaks66c40402012-02-14 21:55:24 +00001331 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001332 // regions (explicit and implicit) escaped.
1333
1334 // Otherwise, whitelist explicit pointers; we still can track them.
1335 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001336 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1337 E = ExplicitRegions.end(); I != E; ++I) {
1338 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1339 WhitelistedSymbols.insert(R->getSymbol());
1340 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001341 }
1342
1343 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1344 E = invalidated->end(); I!=E; ++I) {
1345 SymbolRef sym = *I;
1346 if (WhitelistedSymbols.count(sym))
1347 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001348 // The symbol escaped.
1349 if (const RefState *RS = State->get<RegionState>(sym))
1350 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001351 }
Anna Zaks66c40402012-02-14 21:55:24 +00001352 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001353}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001354
Jordy Rose393f98b2012-03-18 07:43:35 +00001355static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1356 ProgramStateRef prevState) {
1357 ReallocMap currMap = currState->get<ReallocPairs>();
1358 ReallocMap prevMap = prevState->get<ReallocPairs>();
1359
1360 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1361 I != E; ++I) {
1362 SymbolRef sym = I.getKey();
1363 if (!currMap.lookup(sym))
1364 return sym;
1365 }
1366
1367 return NULL;
1368}
1369
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001370PathDiagnosticPiece *
1371MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1372 const ExplodedNode *PrevN,
1373 BugReporterContext &BRC,
1374 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001375 ProgramStateRef state = N->getState();
1376 ProgramStateRef statePrev = PrevN->getState();
1377
1378 const RefState *RS = state->get<RegionState>(Sym);
1379 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001380 if (!RS && !RSPrev)
1381 return 0;
1382
Anna Zaksfe571602012-02-16 22:26:07 +00001383 const Stmt *S = 0;
1384 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001385 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001386
1387 // Retrieve the associated statement.
1388 ProgramPoint ProgLoc = N->getLocation();
1389 if (isa<StmtPoint>(ProgLoc))
1390 S = cast<StmtPoint>(ProgLoc).getStmt();
1391 // If an assumption was made on a branch, it should be caught
1392 // here by looking at the state transition.
1393 if (isa<BlockEdge>(ProgLoc)) {
1394 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1395 S = srcBlk->getTerminator();
1396 }
1397 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001398 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001399
1400 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001401 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001402 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001403 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001404 StackHint = new StackHintGeneratorForSymbol(Sym,
1405 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001406 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001407 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001408 StackHint = new StackHintGeneratorForSymbol(Sym,
1409 "Returned released memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001410 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001411 Mode = ReallocationFailed;
1412 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001413 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001414 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001415
Jordy Roseb000fb52012-03-24 03:15:09 +00001416 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1417 // Is it possible to fail two reallocs WITHOUT testing in between?
1418 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1419 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001420 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001421 FailedReallocSymbol = sym;
1422 }
Anna Zaksfe571602012-02-16 22:26:07 +00001423 }
1424
1425 // We are in a special mode if a reallocation failed later in the path.
1426 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001427 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001428
Jordy Roseb000fb52012-03-24 03:15:09 +00001429 // Is this is the first appearance of the reallocated symbol?
1430 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
1431 // If we ever hit this assert, that means BugReporter has decided to skip
1432 // node pairs or visit them out of order.
1433 assert(state->get<RegionState>(FailedReallocSymbol) &&
1434 "Missed the reallocation point");
1435
1436 // We're at the reallocation point.
1437 Msg = "Attempt to reallocate memory";
1438 StackHint = new StackHintGeneratorForSymbol(Sym,
1439 "Returned reallocated memory");
1440 FailedReallocSymbol = NULL;
1441 Mode = Normal;
1442 }
Anna Zaksfe571602012-02-16 22:26:07 +00001443 }
1444
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001445 if (!Msg)
1446 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001447 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001448
1449 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001450 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001451 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001452 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001453}
1454
1455
Anna Zaks231361a2012-02-08 23:16:52 +00001456#define REGISTER_CHECKER(name) \
1457void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001458 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001459 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001460}
Anna Zaks231361a2012-02-08 23:16:52 +00001461
1462REGISTER_CHECKER(MallocPessimistic)
1463REGISTER_CHECKER(MallocOptimistic)