blob: d6dc97a82c1908abce44ffe1103d83a638c0e30d [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; }
Chris Lattnerfae96222010-09-03 04:34:38 +000045 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000046 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000047 //bool isEscaped() const { return K == Escaped; }
48 //bool isRelinquished() const { return K == Relinquished; }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000049 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000050
51 bool operator==(const RefState &X) const {
52 return K == X.K && S == X.S;
53 }
54
Zhongxing Xub94b81a2009-12-31 06:13:07 +000055 static RefState getAllocateUnchecked(const Stmt *s) {
56 return RefState(AllocateUnchecked, s);
57 }
58 static RefState getAllocateFailed() {
59 return RefState(AllocateFailed, 0);
60 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000061 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
62 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000063 static RefState getRelinquished(const Stmt *s) {
64 return RefState(Relinquished, s);
65 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000066
67 void Profile(llvm::FoldingSetNodeID &ID) const {
68 ID.AddInteger(K);
69 ID.AddPointer(S);
70 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000071};
72
Anna Zaks40add292012-02-15 00:11:25 +000073struct ReallocPair {
74 SymbolRef ReallocatedSym;
75 bool IsFreeOnFailure;
76 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
77 void Profile(llvm::FoldingSetNodeID &ID) const {
78 ID.AddInteger(IsFreeOnFailure);
79 ID.AddPointer(ReallocatedSym);
80 }
81 bool operator==(const ReallocPair &X) const {
82 return ReallocatedSym == X.ReallocatedSym &&
83 IsFreeOnFailure == X.IsFreeOnFailure;
84 }
85};
86
Anna Zaksb319e022012-02-08 20:13:28 +000087class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000088 check::EndPath,
89 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000090 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000091 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000092 check::Location,
93 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000094 eval::Assume,
95 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000096{
Anna Zaksfebdc322012-02-16 22:26:12 +000097 mutable OwningPtr<BugType> BT_DoubleFree;
98 mutable OwningPtr<BugType> BT_Leak;
99 mutable OwningPtr<BugType> BT_UseFree;
100 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000101 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000102 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
103
104 static const unsigned InvalidArgIndex = UINT_MAX;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000105
106public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000107 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000108 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000109
110 /// In pessimistic mode, the checker assumes that it does not know which
111 /// functions might free the memory.
112 struct ChecksFilter {
113 DefaultBool CMallocPessimistic;
114 DefaultBool CMallocOptimistic;
115 };
116
117 ChecksFilter Filter;
118
Anna Zaks66c40402012-02-14 21:55:24 +0000119 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000120 void checkPostStmt(const CallExpr *CE, 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.
183 bool hasUnknownBehavior(const FunctionDecl *FD, ProgramStateRef State) const;
184
Ted Kremenek9c378f72011-08-12 23:37:29 +0000185 static bool SummarizeValue(raw_ostream &os, SVal V);
186 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000187 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000188
Anna Zaksca8e36e2012-02-23 21:38:21 +0000189 /// Find the location of the allocation for Sym on the path leading to the
190 /// exploded node N.
191 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
192 CheckerContext &C) const;
193
Anna Zaksda046772012-02-11 21:02:40 +0000194 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
195
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000196 /// The bug visitor which allows us to print extra diagnostics along the
197 /// BugReport path. For example, showing the allocation site of the leaked
198 /// region.
199 class MallocBugVisitor : public BugReporterVisitor {
200 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000201 enum NotificationMode {
202 Normal,
203 Complete,
204 ReallocationFailed
205 };
206
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000207 // The allocated region symbol tracked by the main analysis.
208 SymbolRef Sym;
Anna Zaksfe571602012-02-16 22:26:07 +0000209 NotificationMode Mode;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000210
211 public:
Anna Zaksfe571602012-02-16 22:26:07 +0000212 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000213 virtual ~MallocBugVisitor() {}
214
215 void Profile(llvm::FoldingSetNodeID &ID) const {
216 static int X = 0;
217 ID.AddPointer(&X);
218 ID.AddPointer(Sym);
219 }
220
Anna Zaksfe571602012-02-16 22:26:07 +0000221 inline bool isAllocated(const RefState *S, const RefState *SPrev,
222 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000223 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000224 return (Stmt && isa<CallExpr>(Stmt) &&
225 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000226 }
227
Anna Zaksfe571602012-02-16 22:26:07 +0000228 inline bool isReleased(const RefState *S, const RefState *SPrev,
229 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000230 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000231 return (Stmt && isa<CallExpr>(Stmt) &&
232 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
233 }
234
235 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
236 const Stmt *Stmt) {
237 // If the expression is not a call, and the state change is
238 // released -> allocated, it must be the realloc return value
239 // check. If we have to handle more cases here, it might be cleaner just
240 // to track this extra bit in the state itself.
241 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
242 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000243 }
244
245 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
246 const ExplodedNode *PrevN,
247 BugReporterContext &BRC,
248 BugReport &BR);
249 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000250};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000251} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000252
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000253typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000254typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000255class RegionState {};
256class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000257namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000258namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000259 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000260 struct ProgramStateTrait<RegionState>
261 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000262 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000263 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000264
265 template <>
266 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000267 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000268 static void *GDMIndex() { static int x; return &x; }
269 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000270}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000271}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000272
Anna Zaks4fb54872012-02-11 21:02:35 +0000273namespace {
274class StopTrackingCallback : public SymbolVisitor {
275 ProgramStateRef state;
276public:
277 StopTrackingCallback(ProgramStateRef st) : state(st) {}
278 ProgramStateRef getState() const { return state; }
279
280 bool VisitSymbol(SymbolRef sym) {
281 state = state->remove<RegionState>(sym);
282 return true;
283 }
284};
285} // end anonymous namespace
286
Anna Zaks66c40402012-02-14 21:55:24 +0000287void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000288 if (!II_malloc)
289 II_malloc = &Ctx.Idents.get("malloc");
290 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000291 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000292 if (!II_realloc)
293 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000294 if (!II_reallocf)
295 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000296 if (!II_calloc)
297 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000298 if (!II_valloc)
299 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaks60a1fa42012-02-22 03:14:20 +0000300 if (!II_strdup)
301 II_strdup = &Ctx.Idents.get("strdup");
302 if (!II_strndup)
303 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000304}
305
Anna Zaks66c40402012-02-14 21:55:24 +0000306bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000307 if (!FD)
308 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000309 IdentifierInfo *FunI = FD->getIdentifier();
310 if (!FunI)
311 return false;
312
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000313 initIdentifierInfo(C);
314
Anna Zaks40add292012-02-15 00:11:25 +0000315 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000316 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
317 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000318 return true;
319
320 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
321 FD->specific_attr_begin<OwnershipAttr>() !=
322 FD->specific_attr_end<OwnershipAttr>())
323 return true;
324
325
326 return false;
327}
328
Anna Zaksb319e022012-02-08 20:13:28 +0000329void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
330 const FunctionDecl *FD = C.getCalleeDecl(CE);
331 if (!FD)
332 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000333
Anna Zaksb16ce452012-02-15 00:11:22 +0000334 initIdentifierInfo(C.getASTContext());
335 IdentifierInfo *FunI = FD->getIdentifier();
336 if (!FunI)
337 return;
338
Anna Zaks87cb5be2012-02-22 19:24:52 +0000339 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000340 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000341 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000342 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000343 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000344 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000345 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000346 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000347 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000348 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000349 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000350 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000351 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000352 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000353 State = MallocUpdateRefState(C, CE, State);
354 } else if (Filter.CMallocOptimistic) {
355 // Check all the attributes, if there are any.
356 // There can be multiple of these attributes.
357 if (FD->hasAttrs())
358 for (specific_attr_iterator<OwnershipAttr>
359 i = FD->specific_attr_begin<OwnershipAttr>(),
360 e = FD->specific_attr_end<OwnershipAttr>();
361 i != e; ++i) {
362 switch ((*i)->getOwnKind()) {
363 case OwnershipAttr::Returns:
364 State = MallocMemReturnsAttr(C, CE, *i);
365 break;
366 case OwnershipAttr::Takes:
367 case OwnershipAttr::Holds:
368 State = FreeMemAttr(C, CE, *i);
369 break;
370 }
371 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000372 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000373 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000374}
375
Anna Zaks87cb5be2012-02-22 19:24:52 +0000376ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
377 const CallExpr *CE,
378 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000379 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000380 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000381
Sean Huntcf807c42010-08-18 23:23:40 +0000382 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000383 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000384 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000385 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000386 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000387}
388
Anna Zaksb319e022012-02-08 20:13:28 +0000389ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000390 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000391 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000392 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000393 // Get the return value.
394 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000395
Anna Zaksb16ce452012-02-15 00:11:22 +0000396 // We expect the malloc functions to return a pointer.
397 if (!isa<Loc>(retVal))
398 return 0;
399
Jordy Rose32f26562010-07-04 00:00:41 +0000400 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000401 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000402
Jordy Rose32f26562010-07-04 00:00:41 +0000403 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000404 const SymbolicRegion *R =
405 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000406 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000407 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000408 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000409 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000410 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
411 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
412 DefinedOrUnknownSVal extentMatchesSize =
413 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000414
Anna Zaks60a1fa42012-02-22 03:14:20 +0000415 state = state->assume(extentMatchesSize, true);
416 assert(state);
417 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000418
Anna Zaks87cb5be2012-02-22 19:24:52 +0000419 return MallocUpdateRefState(C, CE, state);
420}
421
422ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
423 const CallExpr *CE,
424 ProgramStateRef state) {
425 // Get the return value.
426 SVal retVal = state->getSVal(CE, C.getLocationContext());
427
428 // We expect the malloc functions to return a pointer.
429 if (!isa<Loc>(retVal))
430 return 0;
431
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000432 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000433 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000434
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000435 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000436 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000437
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000438}
439
Anna Zaks87cb5be2012-02-22 19:24:52 +0000440ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
441 const CallExpr *CE,
442 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000443 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000444 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000445
Sean Huntcf807c42010-08-18 23:23:40 +0000446 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
447 I != E; ++I) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000448 return FreeMemAux(C, CE, C.getState(), *I,
449 Att->getOwnKind() == OwnershipAttr::Holds);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000450 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000451 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000452}
453
Ted Kremenek8bef8232012-01-26 21:29:00 +0000454ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000455 const CallExpr *CE,
456 ProgramStateRef state,
457 unsigned Num,
458 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000459 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000460 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000461 if (!isa<DefinedOrUnknownSVal>(ArgVal))
462 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000463 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
464
465 // Check for null dereferences.
466 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000467 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000468
Anna Zaksb276bd92012-02-14 00:26:13 +0000469 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000470 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000471 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000472 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000473 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000474
Jordy Rose43859f62010-06-07 19:32:37 +0000475 // Unknown values could easily be okay
476 // Undefined values are handled elsewhere
477 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000478 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000479
Jordy Rose43859f62010-06-07 19:32:37 +0000480 const MemRegion *R = ArgVal.getAsRegion();
481
482 // Nonlocs can't be freed, of course.
483 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
484 if (!R) {
485 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000486 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000487 }
488
489 R = R->StripCasts();
490
491 // Blocks might show up as heap data, but should not be free()d
492 if (isa<BlockDataRegion>(R)) {
493 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000494 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000495 }
496
497 const MemSpaceRegion *MS = R->getMemorySpace();
498
499 // Parameters, locals, statics, and globals shouldn't be freed.
500 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
501 // FIXME: at the time this code was written, malloc() regions were
502 // represented by conjured symbols, which are all in UnknownSpaceRegion.
503 // This means that there isn't actually anything from HeapSpaceRegion
504 // that should be freed, even though we allow it here.
505 // Of course, free() can work on memory allocated outside the current
506 // function, so UnknownSpaceRegion is always a possibility.
507 // False negatives are better than false positives.
508
509 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000510 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000511 }
512
513 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
514 // Various cases could lead to non-symbol values here.
515 // For now, ignore them.
516 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000517 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000518
519 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000520 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000521
522 // If the symbol has not been tracked, return. This is possible when free() is
523 // called on a pointer that does not get its pointee directly from malloc().
524 // Full support of this requires inter-procedural analysis.
525 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000526 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000527
528 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000529 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000530 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000531 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000532 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000533 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000534 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000535 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000536 R->addRange(ArgExpr->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000537 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000538 C.EmitReport(R);
539 }
Anna Zaksb319e022012-02-08 20:13:28 +0000540 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000541 }
542
543 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000544 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000545 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
546 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000547}
548
Ted Kremenek9c378f72011-08-12 23:37:29 +0000549bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000550 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
551 os << "an integer (" << IntVal->getValue() << ")";
552 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
553 os << "a constant address (" << ConstAddr->getValue() << ")";
554 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000555 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000556 else
557 return false;
558
559 return true;
560}
561
Ted Kremenek9c378f72011-08-12 23:37:29 +0000562bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000563 const MemRegion *MR) {
564 switch (MR->getKind()) {
565 case MemRegion::FunctionTextRegionKind: {
566 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
567 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000568 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000569 else
570 os << "the address of a function";
571 return true;
572 }
573 case MemRegion::BlockTextRegionKind:
574 os << "block text";
575 return true;
576 case MemRegion::BlockDataRegionKind:
577 // FIXME: where the block came from?
578 os << "a block";
579 return true;
580 default: {
581 const MemSpaceRegion *MS = MR->getMemorySpace();
582
Anna Zakseb31a762012-01-04 23:54:01 +0000583 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000584 const VarRegion *VR = dyn_cast<VarRegion>(MR);
585 const VarDecl *VD;
586 if (VR)
587 VD = VR->getDecl();
588 else
589 VD = NULL;
590
591 if (VD)
592 os << "the address of the local variable '" << VD->getName() << "'";
593 else
594 os << "the address of a local stack variable";
595 return true;
596 }
Anna Zakseb31a762012-01-04 23:54:01 +0000597
598 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000599 const VarRegion *VR = dyn_cast<VarRegion>(MR);
600 const VarDecl *VD;
601 if (VR)
602 VD = VR->getDecl();
603 else
604 VD = NULL;
605
606 if (VD)
607 os << "the address of the parameter '" << VD->getName() << "'";
608 else
609 os << "the address of a parameter";
610 return true;
611 }
Anna Zakseb31a762012-01-04 23:54:01 +0000612
613 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000614 const VarRegion *VR = dyn_cast<VarRegion>(MR);
615 const VarDecl *VD;
616 if (VR)
617 VD = VR->getDecl();
618 else
619 VD = NULL;
620
621 if (VD) {
622 if (VD->isStaticLocal())
623 os << "the address of the static variable '" << VD->getName() << "'";
624 else
625 os << "the address of the global variable '" << VD->getName() << "'";
626 } else
627 os << "the address of a global variable";
628 return true;
629 }
Anna Zakseb31a762012-01-04 23:54:01 +0000630
631 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000632 }
633 }
634}
635
636void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000637 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000638 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000639 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000640 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000641
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000642 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000643 llvm::raw_svector_ostream os(buf);
644
645 const MemRegion *MR = ArgVal.getAsRegion();
646 if (MR) {
647 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
648 MR = ER->getSuperRegion();
649
650 // Special case for alloca()
651 if (isa<AllocaRegion>(MR))
652 os << "Argument to free() was allocated by alloca(), not malloc()";
653 else {
654 os << "Argument to free() is ";
655 if (SummarizeRegion(os, MR))
656 os << ", which is not memory allocated by malloc()";
657 else
658 os << "not memory allocated by malloc()";
659 }
660 } else {
661 os << "Argument to free() is ";
662 if (SummarizeValue(os, ArgVal))
663 os << ", which is not memory allocated by malloc()";
664 else
665 os << "not memory allocated by malloc()";
666 }
667
Anna Zakse172e8b2011-08-17 23:00:25 +0000668 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000669 R->addRange(range);
670 C.EmitReport(R);
671 }
672}
673
Anna Zaks87cb5be2012-02-22 19:24:52 +0000674ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
675 const CallExpr *CE,
676 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000677 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000678 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000679 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000680 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
681 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000682 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000683 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000684
Ted Kremenek846eabd2010-12-01 21:28:31 +0000685 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000686
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000687 DefinedOrUnknownSVal PtrEQ =
688 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000689
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000690 // Get the size argument. If there is no size arg then give up.
691 const Expr *Arg1 = CE->getArg(1);
692 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000693 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000694
695 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000696 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
697 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000698 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000699 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000700
701 // Compare the size argument to 0.
702 DefinedOrUnknownSVal SizeZero =
703 svalBuilder.evalEQ(state, Arg1Val,
704 svalBuilder.makeIntValWithPtrWidth(0, false));
705
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000706 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
707 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
708 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
709 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
710 // We only assume exceptional states if they are definitely true; if the
711 // state is under-constrained, assume regular realloc behavior.
712 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
713 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
714
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000715 // If the ptr is NULL and the size is not 0, the call is equivalent to
716 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000717 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000718 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000719 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000720 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000721 }
722
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000723 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000724 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000725
Anna Zaks30838b92012-02-13 20:57:07 +0000726 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000727 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000728 SymbolRef FromPtr = arg0Val.getAsSymbol();
729 SVal RetVal = state->getSVal(CE, LCtx);
730 SymbolRef ToPtr = RetVal.getAsSymbol();
731 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000732 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000733
734 // If the size is 0, free the memory.
735 if (SizeIsZero)
736 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000737 // The semantics of the return value are:
738 // If size was equal to 0, either NULL or a pointer suitable to be passed
739 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000740 stateFree = stateFree->set<ReallocPairs>(ToPtr,
741 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000742 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000743 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000744 }
745
746 // Default behavior.
747 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
748 // FIXME: We should copy the content of the original buffer.
749 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
750 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000751 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000752 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000753 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
754 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000755 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000756 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000757 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000758 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000759}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000760
Anna Zaks87cb5be2012-02-22 19:24:52 +0000761ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Ted Kremenek8bef8232012-01-26 21:29:00 +0000762 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000763 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000764 const LocationContext *LCtx = C.getLocationContext();
765 SVal count = state->getSVal(CE->getArg(0), LCtx);
766 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000767 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
768 svalBuilder.getContext().getSizeType());
769 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000770
Anna Zaks87cb5be2012-02-22 19:24:52 +0000771 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000772}
773
Anna Zaksca8e36e2012-02-23 21:38:21 +0000774const Stmt *
775MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
776 CheckerContext &C) const {
777 // Walk the ExplodedGraph backwards and find the first node that referred to
778 // the tracked symbol.
779 const ExplodedNode *AllocNode = N;
780
781 while (N) {
782 if (!N->getState()->get<RegionState>(Sym))
783 break;
784 AllocNode = N;
785 N = N->pred_empty() ? NULL : *(N->pred_begin());
786 }
787
788 ProgramPoint P = AllocNode->getLocation();
789 return cast<clang::PostStmt>(P).getStmt();
790}
791
Anna Zaksda046772012-02-11 21:02:40 +0000792void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
793 CheckerContext &C) const {
794 assert(N);
795 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000796 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000797 // Leaks should not be reported if they are post-dominated by a sink:
798 // (1) Sinks are higher importance bugs.
799 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
800 // with __noreturn functions such as assert() or exit(). We choose not
801 // to report leaks on such paths.
802 BT_Leak->setSuppressOnSink(true);
803 }
804
Anna Zaksca8e36e2012-02-23 21:38:21 +0000805 // Most bug reports are cached at the location where they occurred.
806 // With leaks, we want to unique them by the location where they were
807 // allocated, and only report a single path.
808 const Stmt *AllocStmt = getAllocationSite(N, Sym, C);
809 PathDiagnosticLocation LocUsedForUniqueing =
810 PathDiagnosticLocation::createBegin(AllocStmt, C.getSourceManager(),
811 N->getLocationContext());
812
Anna Zaksfebdc322012-02-16 22:26:12 +0000813 BugReport *R = new BugReport(*BT_Leak,
Anna Zaksca8e36e2012-02-23 21:38:21 +0000814 "Memory is never released; potential memory leak", N, LocUsedForUniqueing);
Anna Zaksda046772012-02-11 21:02:40 +0000815 R->addVisitor(new MallocBugVisitor(Sym));
816 C.EmitReport(R);
817}
818
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000819void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
820 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000821{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000822 if (!SymReaper.hasDeadSymbols())
823 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000824
Ted Kremenek8bef8232012-01-26 21:29:00 +0000825 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000826 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000827 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000828
Ted Kremenek217470e2011-07-28 23:07:51 +0000829 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000830 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000831 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
832 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000833 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000834 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000835 Errors.push_back(I->first);
836 }
Jordy Rose90760142010-08-18 04:33:47 +0000837 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000838 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000839
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000840 }
841 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000842
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000843 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000844 ReallocMap RP = state->get<ReallocPairs>();
845 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
846 if (SymReaper.isDead(I->first) ||
847 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000848 state = state->remove<ReallocPairs>(I->first);
849 }
850 }
851
Anna Zaksca8e36e2012-02-23 21:38:21 +0000852 // Generate leak node.
853 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
854 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000855
Anna Zaksca8e36e2012-02-23 21:38:21 +0000856 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000857 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000858 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
859 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000860 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000861 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000862 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000863}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000864
Anna Zaksda046772012-02-11 21:02:40 +0000865void MallocChecker::checkEndPath(CheckerContext &C) const {
866 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000867 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000868
Anna Zaksa19581a2012-02-20 22:25:23 +0000869 // If inside inlined call, skip it.
870 if (C.getLocationContext()->getParent() != 0)
871 return;
872
Jordy Rose09cef092010-08-18 04:26:59 +0000873 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000874 RefState RS = I->second;
875 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000876 ExplodedNode *N = C.addTransition(state);
877 if (N)
878 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000879 }
880 }
881}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000882
Anna Zaks91c2a112012-02-08 23:16:56 +0000883bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
884 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000885 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000886 const RefState *RS = state->get<RegionState>(Sym);
887 if (!RS)
888 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000889
Anna Zaks91c2a112012-02-08 23:16:56 +0000890 if (RS->isAllocated()) {
891 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
892 C.addTransition(state);
893 return true;
894 }
895 return false;
896}
897
Anna Zaks66c40402012-02-14 21:55:24 +0000898void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
899 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
900 return;
901
902 // Check use after free, when a freed pointer is passed to a call.
903 ProgramStateRef State = C.getState();
904 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
905 E = CE->arg_end(); I != E; ++I) {
906 const Expr *A = *I;
907 if (A->getType().getTypePtr()->isAnyPointerType()) {
908 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
909 if (!Sym)
910 continue;
911 if (checkUseAfterFree(Sym, C, A))
912 return;
913 }
914 }
915}
916
Anna Zaks91c2a112012-02-08 23:16:56 +0000917void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
918 const Expr *E = S->getRetValue();
919 if (!E)
920 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000921
922 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +0000923 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
924 SymbolRef Sym = RetVal.getAsSymbol();
925 if (!Sym)
926 // If we are returning a field of the allocated struct or an array element,
927 // the callee could still free the memory.
928 // TODO: This logic should be a part of generic symbol escape callback.
929 if (const MemRegion *MR = RetVal.getAsRegion())
930 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
931 if (const SymbolicRegion *BMR =
932 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
933 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000934 if (!Sym)
935 return;
936
Anna Zaks0860cd02012-02-11 21:44:39 +0000937 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +0000938 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +0000939 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000940
Anna Zaksa19581a2012-02-20 22:25:23 +0000941 // If this function body is not inlined, check if the symbol is escaping.
942 if (C.getLocationContext()->getParent() == 0)
943 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000944}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000945
Anna Zaks91c2a112012-02-08 23:16:56 +0000946bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
947 const Stmt *S) const {
948 assert(Sym);
949 const RefState *RS = C.getState()->get<RegionState>(Sym);
950 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000951 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000952 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000953 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +0000954
Anna Zaksfebdc322012-02-16 22:26:12 +0000955 BugReport *R = new BugReport(*BT_UseFree,
956 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +0000957 if (S)
958 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000959 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000960 C.EmitReport(R);
961 return true;
962 }
963 }
964 return false;
965}
966
Zhongxing Xuc8023782010-03-10 04:58:55 +0000967// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000968void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
969 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000970 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000971 if (Sym)
972 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000973}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000974
Anna Zaks4fb54872012-02-11 21:02:35 +0000975//===----------------------------------------------------------------------===//
976// Check various ways a symbol can be invalidated.
977// TODO: This logic (the next 3 functions) is copied/similar to the
978// RetainRelease checker. We might want to factor this out.
979//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000980
Anna Zaks4fb54872012-02-11 21:02:35 +0000981// Stop tracking symbols when a value escapes as a result of checkBind.
982// A value escapes in three possible cases:
983// (1) we are binding to something that is not a memory region.
984// (2) we are binding to a memregion that does not have stack storage
985// (3) we are binding to a memregion with stack storage that the store
986// does not understand.
987void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
988 CheckerContext &C) const {
989 // Are we storing to something that causes the value to "escape"?
990 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000991 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000992
Anna Zaks4fb54872012-02-11 21:02:35 +0000993 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
994 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000995
Anna Zaks4fb54872012-02-11 21:02:35 +0000996 if (!escapes) {
997 // To test (3), generate a new state with the binding added. If it is
998 // the same state, then it escapes (since the store cannot represent
999 // the binding).
1000 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001001 }
Anna Zaksac593002012-02-16 03:40:57 +00001002 if (!escapes) {
1003 // Case 4: We do not currently model what happens when a symbol is
1004 // assigned to a struct field, so be conservative here and let the symbol
1005 // go. TODO: This could definitely be improved upon.
1006 escapes = !isa<VarRegion>(regionLoc->getRegion());
1007 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001008 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001009
1010 // If our store can represent the binding and we aren't storing to something
1011 // that doesn't have local storage then just return and have the simulation
1012 // state continue as is.
1013 if (!escapes)
1014 return;
1015
1016 // Otherwise, find all symbols referenced by 'val' that we are tracking
1017 // and stop tracking them.
1018 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1019 C.addTransition(state);
1020}
1021
1022// If a symbolic region is assumed to NULL (or another constant), stop tracking
1023// it - assuming that allocation failed on this path.
1024ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1025 SVal Cond,
1026 bool Assumption) const {
1027 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001028 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1029 // If the symbol is assumed to NULL or another constant, this will
1030 // return an APSInt*.
1031 if (state->getSymVal(I.getKey()))
1032 state = state->remove<RegionState>(I.getKey());
1033 }
1034
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001035 // Realloc returns 0 when reallocation fails, which means that we should
1036 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001037 ReallocMap RP = state->get<ReallocPairs>();
1038 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001039 // If the symbol is assumed to NULL or another constant, this will
1040 // return an APSInt*.
1041 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001042 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1043 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001044 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001045 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1046 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001047 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001048 }
1049 state = state->remove<ReallocPairs>(I.getKey());
1050 }
1051 }
1052
Anna Zaks4fb54872012-02-11 21:02:35 +00001053 return state;
1054}
1055
Anna Zaks66c40402012-02-14 21:55:24 +00001056// Check if the function is not known to us. So, for example, we could
1057// conservatively assume it can free/reallocate it's pointer arguments.
1058// (We assume that the pointers cannot escape through calls to system
1059// functions not handled by this checker.)
1060bool MallocChecker::hasUnknownBehavior(const FunctionDecl *FD,
1061 ProgramStateRef State) const {
1062 ASTContext &ASTC = State->getStateManager().getContext();
1063
1064 // If it's one of the allocation functions we can reason about, we model it's
1065 // behavior explicitly.
1066 if (isMemFunction(FD, ASTC)) {
1067 return false;
1068 }
1069
Anna Zaks0d389b82012-02-23 01:05:27 +00001070 // Most system calls, do not free the memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001071 SourceManager &SM = ASTC.getSourceManager();
1072 if (SM.isInSystemHeader(FD->getLocation())) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001073 const IdentifierInfo *II = FD->getIdentifier();
1074
1075 // White list the system functions whose arguments escape.
1076 if (II) {
1077 StringRef FName = II->getName();
1078 if (FName.equals("pthread_setspecific"))
1079 return true;
1080 }
1081
1082 // Otherwise, assume that the function does not free memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001083 return false;
1084 }
1085
1086 // Otherwise, assume that the function can free memory.
1087 return true;
1088}
1089
Anna Zaks4fb54872012-02-11 21:02:35 +00001090// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1091// escapes, when we are tracking p), do not track the symbol as we cannot reason
1092// about it anymore.
1093ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001094MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001095 const StoreManager::InvalidatedSymbols *invalidated,
1096 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001097 ArrayRef<const MemRegion *> Regions,
1098 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001099 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001100 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001101 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001102
Anna Zaks1d6cc6a2012-02-15 02:12:00 +00001103 const FunctionDecl *FD = (Call ?
1104 dyn_cast_or_null<FunctionDecl>(Call->getDecl()) :0);
Anna Zaks66c40402012-02-14 21:55:24 +00001105
1106 // If it's a call which might free or reallocate memory, we assume that all
1107 // regions (explicit and implicit) escaped. Otherwise, whitelist explicit
1108 // pointers; we still can track them.
1109 if (!(FD && hasUnknownBehavior(FD, State))) {
1110 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1111 E = ExplicitRegions.end(); I != E; ++I) {
1112 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1113 WhitelistedSymbols.insert(R->getSymbol());
1114 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001115 }
1116
1117 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1118 E = invalidated->end(); I!=E; ++I) {
1119 SymbolRef sym = *I;
1120 if (WhitelistedSymbols.count(sym))
1121 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001122 // The symbol escaped.
1123 if (const RefState *RS = State->get<RegionState>(sym))
1124 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001125 }
Anna Zaks66c40402012-02-14 21:55:24 +00001126 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001127}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001128
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001129PathDiagnosticPiece *
1130MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1131 const ExplodedNode *PrevN,
1132 BugReporterContext &BRC,
1133 BugReport &BR) {
1134 const RefState *RS = N->getState()->get<RegionState>(Sym);
1135 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1136 if (!RS && !RSPrev)
1137 return 0;
1138
Anna Zaksfe571602012-02-16 22:26:07 +00001139 const Stmt *S = 0;
1140 const char *Msg = 0;
1141
1142 // Retrieve the associated statement.
1143 ProgramPoint ProgLoc = N->getLocation();
1144 if (isa<StmtPoint>(ProgLoc))
1145 S = cast<StmtPoint>(ProgLoc).getStmt();
1146 // If an assumption was made on a branch, it should be caught
1147 // here by looking at the state transition.
1148 if (isa<BlockEdge>(ProgLoc)) {
1149 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1150 S = srcBlk->getTerminator();
1151 }
1152 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001153 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001154
1155 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001156 if (Mode == Normal) {
1157 if (isAllocated(RS, RSPrev, S))
1158 Msg = "Memory is allocated";
1159 else if (isReleased(RS, RSPrev, S))
1160 Msg = "Memory is released";
1161 else if (isReallocFailedCheck(RS, RSPrev, S)) {
1162 Mode = ReallocationFailed;
1163 Msg = "Reallocation failed";
1164 }
1165
1166 // We are in a special mode if a reallocation failed later in the path.
1167 } else if (Mode == ReallocationFailed) {
1168 // Generate a special diagnostic for the first realloc we find.
1169 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1170 return 0;
1171
1172 // Check that the name of the function is realloc.
1173 const CallExpr *CE = dyn_cast<CallExpr>(S);
1174 if (!CE)
1175 return 0;
1176 const FunctionDecl *funDecl = CE->getDirectCallee();
1177 if (!funDecl)
1178 return 0;
1179 StringRef FunName = funDecl->getName();
1180 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1181 return 0;
1182 Msg = "Attempt to reallocate memory";
1183 Mode = Normal;
1184 }
1185
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001186 if (!Msg)
1187 return 0;
1188
1189 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001190 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001191 N->getLocationContext());
1192 return new PathDiagnosticEventPiece(Pos, Msg);
1193}
1194
1195
Anna Zaks231361a2012-02-08 23:16:52 +00001196#define REGISTER_CHECKER(name) \
1197void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001198 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001199 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001200}
Anna Zaks231361a2012-02-08 23:16:52 +00001201
1202REGISTER_CHECKER(MallocPessimistic)
1203REGISTER_CHECKER(MallocOptimistic)