blob: 38044d1aa9c5e28dcc5b1a12c1814108bd9732ef [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"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000029using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000030using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000031
32namespace {
33
Zhongxing Xu7fb14642009-12-11 00:55:44 +000034class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000035 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
36 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000037 const Stmt *S;
38
Zhongxing Xu7fb14642009-12-11 00:55:44 +000039public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000040 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
41
Zhongxing Xub94b81a2009-12-31 06:13:07 +000042 bool isAllocated() const { return K == AllocateUnchecked; }
Chris Lattnerfae96222010-09-03 04:34:38 +000043 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000044 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000045 //bool isEscaped() const { return K == Escaped; }
46 //bool isRelinquished() const { return K == Relinquished; }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000047 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000048
49 bool operator==(const RefState &X) const {
50 return K == X.K && S == X.S;
51 }
52
Zhongxing Xub94b81a2009-12-31 06:13:07 +000053 static RefState getAllocateUnchecked(const Stmt *s) {
54 return RefState(AllocateUnchecked, s);
55 }
56 static RefState getAllocateFailed() {
57 return RefState(AllocateFailed, 0);
58 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000059 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
60 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000061 static RefState getRelinquished(const Stmt *s) {
62 return RefState(Relinquished, s);
63 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064
65 void Profile(llvm::FoldingSetNodeID &ID) const {
66 ID.AddInteger(K);
67 ID.AddPointer(S);
68 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000069};
70
Anna Zaks40add292012-02-15 00:11:25 +000071struct ReallocPair {
72 SymbolRef ReallocatedSym;
73 bool IsFreeOnFailure;
74 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
75 void Profile(llvm::FoldingSetNodeID &ID) const {
76 ID.AddInteger(IsFreeOnFailure);
77 ID.AddPointer(ReallocatedSym);
78 }
79 bool operator==(const ReallocPair &X) const {
80 return ReallocatedSym == X.ReallocatedSym &&
81 IsFreeOnFailure == X.IsFreeOnFailure;
82 }
83};
84
Anna Zaksb319e022012-02-08 20:13:28 +000085class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000086 check::EndPath,
87 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000088 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000089 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000090 check::Location,
91 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000092 eval::Assume,
93 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000094{
Anna Zaksfebdc322012-02-16 22:26:12 +000095 mutable OwningPtr<BugType> BT_DoubleFree;
96 mutable OwningPtr<BugType> BT_Leak;
97 mutable OwningPtr<BugType> BT_UseFree;
98 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +000099 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks40add292012-02-15 00:11:25 +0000100 *II_valloc, *II_reallocf;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000101
102public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000103 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks40add292012-02-15 00:11:25 +0000104 II_valloc(0), II_reallocf(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000105
106 /// In pessimistic mode, the checker assumes that it does not know which
107 /// functions might free the memory.
108 struct ChecksFilter {
109 DefaultBool CMallocPessimistic;
110 DefaultBool CMallocOptimistic;
111 };
112
113 ChecksFilter Filter;
114
Anna Zaks66c40402012-02-14 21:55:24 +0000115 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000116 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000117 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000118 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000119 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000120 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000121 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000122 void checkLocation(SVal l, bool isLoad, const Stmt *S,
123 CheckerContext &C) const;
124 void checkBind(SVal location, SVal val, const Stmt*S,
125 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000126 ProgramStateRef
127 checkRegionChanges(ProgramStateRef state,
128 const StoreManager::InvalidatedSymbols *invalidated,
129 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000130 ArrayRef<const MemRegion *> Regions,
131 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000132 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
133 return true;
134 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000135
Zhongxing Xu7b760962009-11-13 07:25:27 +0000136private:
Anna Zaks66c40402012-02-14 21:55:24 +0000137 void initIdentifierInfo(ASTContext &C) const;
138
139 /// Check if this is one of the functions which can allocate/reallocate memory
140 /// pointed to by one of its arguments.
141 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
142
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000143 static void MallocMem(CheckerContext &C, const CallExpr *CE);
144 static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
145 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000146 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000147 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000148 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000149 return MallocMemAux(C, CE,
150 state->getSVal(SizeEx, C.getLocationContext()),
151 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000152 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000153 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000154 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000155 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000156
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000157 void FreeMem(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose2a479922010-08-12 08:54:03 +0000158 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000159 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000160 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
161 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000162 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000163
Anna Zaks40add292012-02-15 00:11:25 +0000164 void ReallocMem(CheckerContext &C, const CallExpr *CE,
165 bool FreesMemOnFailure) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000166 static void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000167
Anna Zaks91c2a112012-02-08 23:16:56 +0000168 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
169 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
170 const Stmt *S = 0) const;
171
Anna Zaks66c40402012-02-14 21:55:24 +0000172 /// Check if the function is not known to us. So, for example, we could
173 /// conservatively assume it can free/reallocate it's pointer arguments.
174 bool hasUnknownBehavior(const FunctionDecl *FD, ProgramStateRef State) const;
175
Ted Kremenek9c378f72011-08-12 23:37:29 +0000176 static bool SummarizeValue(raw_ostream &os, SVal V);
177 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000178 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000179
Anna Zaksda046772012-02-11 21:02:40 +0000180 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
181
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000182 /// The bug visitor which allows us to print extra diagnostics along the
183 /// BugReport path. For example, showing the allocation site of the leaked
184 /// region.
185 class MallocBugVisitor : public BugReporterVisitor {
186 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000187 enum NotificationMode {
188 Normal,
189 Complete,
190 ReallocationFailed
191 };
192
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000193 // The allocated region symbol tracked by the main analysis.
194 SymbolRef Sym;
Anna Zaksfe571602012-02-16 22:26:07 +0000195 NotificationMode Mode;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000196
197 public:
Anna Zaksfe571602012-02-16 22:26:07 +0000198 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000199 virtual ~MallocBugVisitor() {}
200
201 void Profile(llvm::FoldingSetNodeID &ID) const {
202 static int X = 0;
203 ID.AddPointer(&X);
204 ID.AddPointer(Sym);
205 }
206
Anna Zaksfe571602012-02-16 22:26:07 +0000207 inline bool isAllocated(const RefState *S, const RefState *SPrev,
208 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000209 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000210 return (Stmt && isa<CallExpr>(Stmt) &&
211 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000212 }
213
Anna Zaksfe571602012-02-16 22:26:07 +0000214 inline bool isReleased(const RefState *S, const RefState *SPrev,
215 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000216 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000217 return (Stmt && isa<CallExpr>(Stmt) &&
218 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
219 }
220
221 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
222 const Stmt *Stmt) {
223 // If the expression is not a call, and the state change is
224 // released -> allocated, it must be the realloc return value
225 // check. If we have to handle more cases here, it might be cleaner just
226 // to track this extra bit in the state itself.
227 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
228 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000229 }
230
231 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
232 const ExplodedNode *PrevN,
233 BugReporterContext &BRC,
234 BugReport &BR);
235 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000236};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000237} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000238
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000239typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000240typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000241class RegionState {};
242class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000243namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000244namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000245 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000246 struct ProgramStateTrait<RegionState>
247 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000248 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000249 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000250
251 template <>
252 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000253 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000254 static void *GDMIndex() { static int x; return &x; }
255 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000256}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000257}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000258
Anna Zaks4fb54872012-02-11 21:02:35 +0000259namespace {
260class StopTrackingCallback : public SymbolVisitor {
261 ProgramStateRef state;
262public:
263 StopTrackingCallback(ProgramStateRef st) : state(st) {}
264 ProgramStateRef getState() const { return state; }
265
266 bool VisitSymbol(SymbolRef sym) {
267 state = state->remove<RegionState>(sym);
268 return true;
269 }
270};
271} // end anonymous namespace
272
Anna Zaks66c40402012-02-14 21:55:24 +0000273void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000274 if (!II_malloc)
275 II_malloc = &Ctx.Idents.get("malloc");
276 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000277 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000278 if (!II_realloc)
279 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000280 if (!II_reallocf)
281 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000282 if (!II_calloc)
283 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000284 if (!II_valloc)
285 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000286}
287
Anna Zaks66c40402012-02-14 21:55:24 +0000288bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000289 if (!FD)
290 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000291 IdentifierInfo *FunI = FD->getIdentifier();
292 if (!FunI)
293 return false;
294
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000295 initIdentifierInfo(C);
296
Anna Zaks66c40402012-02-14 21:55:24 +0000297 // TODO: Add more here : ex: reallocf!
Anna Zaks40add292012-02-15 00:11:25 +0000298 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
299 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc)
Anna Zaks66c40402012-02-14 21:55:24 +0000300 return true;
301
302 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
303 FD->specific_attr_begin<OwnershipAttr>() !=
304 FD->specific_attr_end<OwnershipAttr>())
305 return true;
306
307
308 return false;
309}
310
Anna Zaksb319e022012-02-08 20:13:28 +0000311void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
312 const FunctionDecl *FD = C.getCalleeDecl(CE);
313 if (!FD)
314 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000315
Anna Zaksb16ce452012-02-15 00:11:22 +0000316 initIdentifierInfo(C.getASTContext());
317 IdentifierInfo *FunI = FD->getIdentifier();
318 if (!FunI)
319 return;
320
321 if (FunI == II_malloc || FunI == II_valloc) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000322 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000323 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000324 } else if (FunI == II_realloc) {
Anna Zaks40add292012-02-15 00:11:25 +0000325 ReallocMem(C, CE, false);
326 return;
327 } else if (FunI == II_reallocf) {
328 ReallocMem(C, CE, true);
Anna Zaksb319e022012-02-08 20:13:28 +0000329 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000330 } else if (FunI == II_calloc) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000331 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000332 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000333 }else if (FunI == II_free) {
Anna Zaksb319e022012-02-08 20:13:28 +0000334 FreeMem(C, CE);
335 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000336 }
337
Anna Zaks91c2a112012-02-08 23:16:56 +0000338 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000339 // Check all the attributes, if there are any.
340 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000341 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000342 for (specific_attr_iterator<OwnershipAttr>
343 i = FD->specific_attr_begin<OwnershipAttr>(),
344 e = FD->specific_attr_end<OwnershipAttr>();
345 i != e; ++i) {
346 switch ((*i)->getOwnKind()) {
347 case OwnershipAttr::Returns: {
348 MallocMemReturnsAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000349 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000350 }
351 case OwnershipAttr::Takes:
352 case OwnershipAttr::Holds: {
353 FreeMemAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000354 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000355 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000356 }
357 }
358 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000359}
360
361void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000362 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000363 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000364 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000365}
366
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000367void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
368 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000369 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000370 return;
371
Sean Huntcf807c42010-08-18 23:23:40 +0000372 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000373 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000374 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000375 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000376 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000377 return;
378 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000379 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000380 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000381 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000382}
383
Anna Zaksb319e022012-02-08 20:13:28 +0000384ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000385 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000386 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000387 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000388 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000389
Anna Zaksb319e022012-02-08 20:13:28 +0000390 // Get the return value.
391 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000392
Anna Zaksb16ce452012-02-15 00:11:22 +0000393 // We expect the malloc functions to return a pointer.
394 if (!isa<Loc>(retVal))
395 return 0;
396
Jordy Rose32f26562010-07-04 00:00:41 +0000397 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000398 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000399
Jordy Rose32f26562010-07-04 00:00:41 +0000400 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000401 const SymbolicRegion *R =
402 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
403 if (!R || !isa<DefinedOrUnknownSVal>(Size))
404 return 0;
405
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000406 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000407 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000408 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000409 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000410
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000411 state = state->assume(extentMatchesSize, true);
412 assert(state);
413
414 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000415 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000416
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000417 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000418 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000419}
420
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000421void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000422 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000423
424 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000425 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000426}
427
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000428void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000429 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000430 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000431 return;
432
Sean Huntcf807c42010-08-18 23:23:40 +0000433 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
434 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000435 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000436 FreeMemAux(C, CE, C.getState(), *I,
437 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000438 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000439 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000440 }
441}
442
Ted Kremenek8bef8232012-01-26 21:29:00 +0000443ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000444 const CallExpr *CE,
445 ProgramStateRef state,
446 unsigned Num,
447 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000448 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000449 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000450 if (!isa<DefinedOrUnknownSVal>(ArgVal))
451 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000452 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
453
454 // Check for null dereferences.
455 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000456 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000457
Anna Zaksb276bd92012-02-14 00:26:13 +0000458 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000459 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000460 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000461 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000462 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000463
Jordy Rose43859f62010-06-07 19:32:37 +0000464 // Unknown values could easily be okay
465 // Undefined values are handled elsewhere
466 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000467 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000468
Jordy Rose43859f62010-06-07 19:32:37 +0000469 const MemRegion *R = ArgVal.getAsRegion();
470
471 // Nonlocs can't be freed, of course.
472 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
473 if (!R) {
474 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000475 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000476 }
477
478 R = R->StripCasts();
479
480 // Blocks might show up as heap data, but should not be free()d
481 if (isa<BlockDataRegion>(R)) {
482 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000483 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000484 }
485
486 const MemSpaceRegion *MS = R->getMemorySpace();
487
488 // Parameters, locals, statics, and globals shouldn't be freed.
489 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
490 // FIXME: at the time this code was written, malloc() regions were
491 // represented by conjured symbols, which are all in UnknownSpaceRegion.
492 // This means that there isn't actually anything from HeapSpaceRegion
493 // that should be freed, even though we allow it here.
494 // Of course, free() can work on memory allocated outside the current
495 // function, so UnknownSpaceRegion is always a possibility.
496 // False negatives are better than false positives.
497
498 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000499 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000500 }
501
502 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
503 // Various cases could lead to non-symbol values here.
504 // For now, ignore them.
505 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000506 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000507
508 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000509 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000510
511 // If the symbol has not been tracked, return. This is possible when free() is
512 // called on a pointer that does not get its pointee directly from malloc().
513 // Full support of this requires inter-procedural analysis.
514 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000515 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000516
517 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000518 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000519 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000520 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000521 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000522 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000523 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000524 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000525 R->addRange(ArgExpr->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000526 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000527 C.EmitReport(R);
528 }
Anna Zaksb319e022012-02-08 20:13:28 +0000529 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000530 }
531
532 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000533 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000534 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
535 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000536}
537
Ted Kremenek9c378f72011-08-12 23:37:29 +0000538bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000539 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
540 os << "an integer (" << IntVal->getValue() << ")";
541 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
542 os << "a constant address (" << ConstAddr->getValue() << ")";
543 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000544 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000545 else
546 return false;
547
548 return true;
549}
550
Ted Kremenek9c378f72011-08-12 23:37:29 +0000551bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000552 const MemRegion *MR) {
553 switch (MR->getKind()) {
554 case MemRegion::FunctionTextRegionKind: {
555 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
556 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000557 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000558 else
559 os << "the address of a function";
560 return true;
561 }
562 case MemRegion::BlockTextRegionKind:
563 os << "block text";
564 return true;
565 case MemRegion::BlockDataRegionKind:
566 // FIXME: where the block came from?
567 os << "a block";
568 return true;
569 default: {
570 const MemSpaceRegion *MS = MR->getMemorySpace();
571
Anna Zakseb31a762012-01-04 23:54:01 +0000572 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000573 const VarRegion *VR = dyn_cast<VarRegion>(MR);
574 const VarDecl *VD;
575 if (VR)
576 VD = VR->getDecl();
577 else
578 VD = NULL;
579
580 if (VD)
581 os << "the address of the local variable '" << VD->getName() << "'";
582 else
583 os << "the address of a local stack variable";
584 return true;
585 }
Anna Zakseb31a762012-01-04 23:54:01 +0000586
587 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000588 const VarRegion *VR = dyn_cast<VarRegion>(MR);
589 const VarDecl *VD;
590 if (VR)
591 VD = VR->getDecl();
592 else
593 VD = NULL;
594
595 if (VD)
596 os << "the address of the parameter '" << VD->getName() << "'";
597 else
598 os << "the address of a parameter";
599 return true;
600 }
Anna Zakseb31a762012-01-04 23:54:01 +0000601
602 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000603 const VarRegion *VR = dyn_cast<VarRegion>(MR);
604 const VarDecl *VD;
605 if (VR)
606 VD = VR->getDecl();
607 else
608 VD = NULL;
609
610 if (VD) {
611 if (VD->isStaticLocal())
612 os << "the address of the static variable '" << VD->getName() << "'";
613 else
614 os << "the address of the global variable '" << VD->getName() << "'";
615 } else
616 os << "the address of a global variable";
617 return true;
618 }
Anna Zakseb31a762012-01-04 23:54:01 +0000619
620 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000621 }
622 }
623}
624
625void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000626 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000627 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000628 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000629 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000630
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000631 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000632 llvm::raw_svector_ostream os(buf);
633
634 const MemRegion *MR = ArgVal.getAsRegion();
635 if (MR) {
636 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
637 MR = ER->getSuperRegion();
638
639 // Special case for alloca()
640 if (isa<AllocaRegion>(MR))
641 os << "Argument to free() was allocated by alloca(), not malloc()";
642 else {
643 os << "Argument to free() is ";
644 if (SummarizeRegion(os, MR))
645 os << ", which is not memory allocated by malloc()";
646 else
647 os << "not memory allocated by malloc()";
648 }
649 } else {
650 os << "Argument to free() is ";
651 if (SummarizeValue(os, ArgVal))
652 os << ", which is not memory allocated by malloc()";
653 else
654 os << "not memory allocated by malloc()";
655 }
656
Anna Zakse172e8b2011-08-17 23:00:25 +0000657 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000658 R->addRange(range);
659 C.EmitReport(R);
660 }
661}
662
Anna Zaks40add292012-02-15 00:11:25 +0000663void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE,
664 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000665 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000666 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000667 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000668 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
669 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
670 return;
671 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000672
Ted Kremenek846eabd2010-12-01 21:28:31 +0000673 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000674
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000675 DefinedOrUnknownSVal PtrEQ =
676 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000677
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000678 // Get the size argument. If there is no size arg then give up.
679 const Expr *Arg1 = CE->getArg(1);
680 if (!Arg1)
681 return;
682
683 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000684 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
685 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
686 return;
687 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000688
689 // Compare the size argument to 0.
690 DefinedOrUnknownSVal SizeZero =
691 svalBuilder.evalEQ(state, Arg1Val,
692 svalBuilder.makeIntValWithPtrWidth(0, false));
693
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000694 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
695 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
696 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
697 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
698 // We only assume exceptional states if they are definitely true; if the
699 // state is under-constrained, assume regular realloc behavior.
700 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
701 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
702
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000703 // If the ptr is NULL and the size is not 0, the call is equivalent to
704 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000705 if ( PrtIsNull && !SizeIsZero) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000706 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000707 UndefinedVal(), StatePtrIsNull);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000708 C.addTransition(stateMalloc);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000709 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000710 }
711
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000712 if (PrtIsNull && SizeIsZero)
713 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000714
Anna Zaks30838b92012-02-13 20:57:07 +0000715 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000716 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000717 SymbolRef FromPtr = arg0Val.getAsSymbol();
718 SVal RetVal = state->getSVal(CE, LCtx);
719 SymbolRef ToPtr = RetVal.getAsSymbol();
720 if (!FromPtr || !ToPtr)
721 return;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000722
723 // If the size is 0, free the memory.
724 if (SizeIsZero)
725 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000726 // The semantics of the return value are:
727 // If size was equal to 0, either NULL or a pointer suitable to be passed
728 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000729 stateFree = stateFree->set<ReallocPairs>(ToPtr,
730 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000731 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks30838b92012-02-13 20:57:07 +0000732 C.addTransition(stateFree);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000733 return;
734 }
735
736 // Default behavior.
737 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
738 // FIXME: We should copy the content of the original buffer.
739 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
740 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000741 if (!stateRealloc)
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000742 return;
Anna Zaks40add292012-02-15 00:11:25 +0000743 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
744 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000745 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000746 C.addTransition(stateRealloc);
747 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000748 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000749}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000750
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000751void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000752 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000753 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000754 const LocationContext *LCtx = C.getLocationContext();
755 SVal count = state->getSVal(CE->getArg(0), LCtx);
756 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000757 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
758 svalBuilder.getContext().getSizeType());
759 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000760
Anna Zaks0bd6b112011-10-26 21:06:34 +0000761 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000762}
763
Anna Zaksda046772012-02-11 21:02:40 +0000764void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
765 CheckerContext &C) const {
766 assert(N);
767 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000768 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000769 // Leaks should not be reported if they are post-dominated by a sink:
770 // (1) Sinks are higher importance bugs.
771 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
772 // with __noreturn functions such as assert() or exit(). We choose not
773 // to report leaks on such paths.
774 BT_Leak->setSuppressOnSink(true);
775 }
776
Anna Zaksfebdc322012-02-16 22:26:12 +0000777 BugReport *R = new BugReport(*BT_Leak,
778 "Memory is never released; potential memory leak", N);
Anna Zaksda046772012-02-11 21:02:40 +0000779 R->addVisitor(new MallocBugVisitor(Sym));
780 C.EmitReport(R);
781}
782
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000783void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
784 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000785{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000786 if (!SymReaper.hasDeadSymbols())
787 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000788
Ted Kremenek8bef8232012-01-26 21:29:00 +0000789 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000790 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000791 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000792
Ted Kremenek217470e2011-07-28 23:07:51 +0000793 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000794 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000795 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
796 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000797 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000798 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000799 Errors.push_back(I->first);
800 }
Jordy Rose90760142010-08-18 04:33:47 +0000801 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000802 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000803
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000804 }
805 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000806
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000807 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000808 ReallocMap RP = state->get<ReallocPairs>();
809 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
810 if (SymReaper.isDead(I->first) ||
811 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000812 state = state->remove<ReallocPairs>(I->first);
813 }
814 }
815
Anna Zaks0bd6b112011-10-26 21:06:34 +0000816 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000817
Ted Kremenek217470e2011-07-28 23:07:51 +0000818 if (N && generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000819 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000820 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
821 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000822 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000823 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000824}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000825
Anna Zaksda046772012-02-11 21:02:40 +0000826void MallocChecker::checkEndPath(CheckerContext &C) const {
827 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000828 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000829
Jordy Rose09cef092010-08-18 04:26:59 +0000830 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000831 RefState RS = I->second;
832 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000833 ExplodedNode *N = C.addTransition(state);
834 if (N)
835 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000836 }
837 }
838}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000839
Anna Zaks91c2a112012-02-08 23:16:56 +0000840bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
841 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000842 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000843 const RefState *RS = state->get<RegionState>(Sym);
844 if (!RS)
845 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000846
Anna Zaks91c2a112012-02-08 23:16:56 +0000847 if (RS->isAllocated()) {
848 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
849 C.addTransition(state);
850 return true;
851 }
852 return false;
853}
854
Anna Zaks66c40402012-02-14 21:55:24 +0000855void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
856 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
857 return;
858
859 // Check use after free, when a freed pointer is passed to a call.
860 ProgramStateRef State = C.getState();
861 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
862 E = CE->arg_end(); I != E; ++I) {
863 const Expr *A = *I;
864 if (A->getType().getTypePtr()->isAnyPointerType()) {
865 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
866 if (!Sym)
867 continue;
868 if (checkUseAfterFree(Sym, C, A))
869 return;
870 }
871 }
872}
873
Anna Zaks91c2a112012-02-08 23:16:56 +0000874void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
875 const Expr *E = S->getRetValue();
876 if (!E)
877 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000878
879 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000880 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000881 if (!Sym)
882 return;
883
Anna Zaks0860cd02012-02-11 21:44:39 +0000884 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +0000885 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +0000886 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000887
888 // Check if the symbol is escaping.
Anna Zaksfe571602012-02-16 22:26:07 +0000889 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000890}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000891
Anna Zaks91c2a112012-02-08 23:16:56 +0000892bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
893 const Stmt *S) const {
894 assert(Sym);
895 const RefState *RS = C.getState()->get<RegionState>(Sym);
896 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000897 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000898 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000899 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +0000900
Anna Zaksfebdc322012-02-16 22:26:12 +0000901 BugReport *R = new BugReport(*BT_UseFree,
902 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +0000903 if (S)
904 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000905 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000906 C.EmitReport(R);
907 return true;
908 }
909 }
910 return false;
911}
912
Zhongxing Xuc8023782010-03-10 04:58:55 +0000913// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000914void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
915 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000916 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000917 if (Sym)
918 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000919}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000920
Anna Zaks4fb54872012-02-11 21:02:35 +0000921//===----------------------------------------------------------------------===//
922// Check various ways a symbol can be invalidated.
923// TODO: This logic (the next 3 functions) is copied/similar to the
924// RetainRelease checker. We might want to factor this out.
925//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000926
Anna Zaks4fb54872012-02-11 21:02:35 +0000927// Stop tracking symbols when a value escapes as a result of checkBind.
928// A value escapes in three possible cases:
929// (1) we are binding to something that is not a memory region.
930// (2) we are binding to a memregion that does not have stack storage
931// (3) we are binding to a memregion with stack storage that the store
932// does not understand.
933void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
934 CheckerContext &C) const {
935 // Are we storing to something that causes the value to "escape"?
936 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000937 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000938
Anna Zaks4fb54872012-02-11 21:02:35 +0000939 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
940 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000941
Anna Zaks4fb54872012-02-11 21:02:35 +0000942 if (!escapes) {
943 // To test (3), generate a new state with the binding added. If it is
944 // the same state, then it escapes (since the store cannot represent
945 // the binding).
946 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000947 }
Anna Zaksac593002012-02-16 03:40:57 +0000948 if (!escapes) {
949 // Case 4: We do not currently model what happens when a symbol is
950 // assigned to a struct field, so be conservative here and let the symbol
951 // go. TODO: This could definitely be improved upon.
952 escapes = !isa<VarRegion>(regionLoc->getRegion());
953 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000954 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000955
956 // If our store can represent the binding and we aren't storing to something
957 // that doesn't have local storage then just return and have the simulation
958 // state continue as is.
959 if (!escapes)
960 return;
961
962 // Otherwise, find all symbols referenced by 'val' that we are tracking
963 // and stop tracking them.
964 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
965 C.addTransition(state);
966}
967
968// If a symbolic region is assumed to NULL (or another constant), stop tracking
969// it - assuming that allocation failed on this path.
970ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
971 SVal Cond,
972 bool Assumption) const {
973 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +0000974 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
975 // If the symbol is assumed to NULL or another constant, this will
976 // return an APSInt*.
977 if (state->getSymVal(I.getKey()))
978 state = state->remove<RegionState>(I.getKey());
979 }
980
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000981 // Realloc returns 0 when reallocation fails, which means that we should
982 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000983 ReallocMap RP = state->get<ReallocPairs>();
984 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000985 // If the symbol is assumed to NULL or another constant, this will
986 // return an APSInt*.
987 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +0000988 SymbolRef ReallocSym = I.getData().ReallocatedSym;
989 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000990 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +0000991 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
992 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000993 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000994 }
995 state = state->remove<ReallocPairs>(I.getKey());
996 }
997 }
998
Anna Zaks4fb54872012-02-11 21:02:35 +0000999 return state;
1000}
1001
Anna Zaks66c40402012-02-14 21:55:24 +00001002// Check if the function is not known to us. So, for example, we could
1003// conservatively assume it can free/reallocate it's pointer arguments.
1004// (We assume that the pointers cannot escape through calls to system
1005// functions not handled by this checker.)
1006bool MallocChecker::hasUnknownBehavior(const FunctionDecl *FD,
1007 ProgramStateRef State) const {
1008 ASTContext &ASTC = State->getStateManager().getContext();
1009
1010 // If it's one of the allocation functions we can reason about, we model it's
1011 // behavior explicitly.
1012 if (isMemFunction(FD, ASTC)) {
1013 return false;
1014 }
1015
1016 // If it's a system call, we know it does not free the memory.
1017 SourceManager &SM = ASTC.getSourceManager();
1018 if (SM.isInSystemHeader(FD->getLocation())) {
1019 return false;
1020 }
1021
1022 // Otherwise, assume that the function can free memory.
1023 return true;
1024}
1025
Anna Zaks4fb54872012-02-11 21:02:35 +00001026// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1027// escapes, when we are tracking p), do not track the symbol as we cannot reason
1028// about it anymore.
1029ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001030MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001031 const StoreManager::InvalidatedSymbols *invalidated,
1032 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001033 ArrayRef<const MemRegion *> Regions,
1034 const CallOrObjCMessage *Call) const {
Anna Zaks4fb54872012-02-11 21:02:35 +00001035 if (!invalidated)
Anna Zaks66c40402012-02-14 21:55:24 +00001036 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001037 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001038
Anna Zaks1d6cc6a2012-02-15 02:12:00 +00001039 const FunctionDecl *FD = (Call ?
1040 dyn_cast_or_null<FunctionDecl>(Call->getDecl()) :0);
Anna Zaks66c40402012-02-14 21:55:24 +00001041
1042 // If it's a call which might free or reallocate memory, we assume that all
1043 // regions (explicit and implicit) escaped. Otherwise, whitelist explicit
1044 // pointers; we still can track them.
1045 if (!(FD && hasUnknownBehavior(FD, State))) {
1046 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1047 E = ExplicitRegions.end(); I != E; ++I) {
1048 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1049 WhitelistedSymbols.insert(R->getSymbol());
1050 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001051 }
1052
1053 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1054 E = invalidated->end(); I!=E; ++I) {
1055 SymbolRef sym = *I;
1056 if (WhitelistedSymbols.count(sym))
1057 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001058 // The symbol escaped.
1059 if (const RefState *RS = State->get<RegionState>(sym))
1060 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001061 }
Anna Zaks66c40402012-02-14 21:55:24 +00001062 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001063}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001064
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001065PathDiagnosticPiece *
1066MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1067 const ExplodedNode *PrevN,
1068 BugReporterContext &BRC,
1069 BugReport &BR) {
1070 const RefState *RS = N->getState()->get<RegionState>(Sym);
1071 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1072 if (!RS && !RSPrev)
1073 return 0;
1074
Anna Zaksfe571602012-02-16 22:26:07 +00001075 const Stmt *S = 0;
1076 const char *Msg = 0;
1077
1078 // Retrieve the associated statement.
1079 ProgramPoint ProgLoc = N->getLocation();
1080 if (isa<StmtPoint>(ProgLoc))
1081 S = cast<StmtPoint>(ProgLoc).getStmt();
1082 // If an assumption was made on a branch, it should be caught
1083 // here by looking at the state transition.
1084 if (isa<BlockEdge>(ProgLoc)) {
1085 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1086 S = srcBlk->getTerminator();
1087 }
1088 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001089 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001090
1091 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001092 if (Mode == Normal) {
1093 if (isAllocated(RS, RSPrev, S))
1094 Msg = "Memory is allocated";
1095 else if (isReleased(RS, RSPrev, S))
1096 Msg = "Memory is released";
1097 else if (isReallocFailedCheck(RS, RSPrev, S)) {
1098 Mode = ReallocationFailed;
1099 Msg = "Reallocation failed";
1100 }
1101
1102 // We are in a special mode if a reallocation failed later in the path.
1103 } else if (Mode == ReallocationFailed) {
1104 // Generate a special diagnostic for the first realloc we find.
1105 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1106 return 0;
1107
1108 // Check that the name of the function is realloc.
1109 const CallExpr *CE = dyn_cast<CallExpr>(S);
1110 if (!CE)
1111 return 0;
1112 const FunctionDecl *funDecl = CE->getDirectCallee();
1113 if (!funDecl)
1114 return 0;
1115 StringRef FunName = funDecl->getName();
1116 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1117 return 0;
1118 Msg = "Attempt to reallocate memory";
1119 Mode = Normal;
1120 }
1121
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001122 if (!Msg)
1123 return 0;
1124
1125 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001126 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001127 N->getLocationContext());
1128 return new PathDiagnosticEventPiece(Pos, Msg);
1129}
1130
1131
Anna Zaks231361a2012-02-08 23:16:52 +00001132#define REGISTER_CHECKER(name) \
1133void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001134 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001135 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001136}
Anna Zaks231361a2012-02-08 23:16:52 +00001137
1138REGISTER_CHECKER(MallocPessimistic)
1139REGISTER_CHECKER(MallocOptimistic)