blob: 1489aab32035c354f178a8c5af99142ebc39e017 [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"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaks66c40402012-02-14 21:55:24 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Anna Zaks15d0ae12012-02-11 23:46:36 +000024#include "clang/Basic/SourceManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000025#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000026#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000027#include "llvm/ADT/STLExtras.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000028using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000029using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000030
31namespace {
32
Zhongxing Xu7fb14642009-12-11 00:55:44 +000033class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000034 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
35 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000036 const Stmt *S;
37
Zhongxing Xu7fb14642009-12-11 00:55:44 +000038public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000039 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
40
Zhongxing Xub94b81a2009-12-31 06:13:07 +000041 bool isAllocated() const { return K == AllocateUnchecked; }
Chris Lattnerfae96222010-09-03 04:34:38 +000042 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000043 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000044 //bool isEscaped() const { return K == Escaped; }
45 //bool isRelinquished() const { return K == Relinquished; }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000046 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000047
48 bool operator==(const RefState &X) const {
49 return K == X.K && S == X.S;
50 }
51
Zhongxing Xub94b81a2009-12-31 06:13:07 +000052 static RefState getAllocateUnchecked(const Stmt *s) {
53 return RefState(AllocateUnchecked, s);
54 }
55 static RefState getAllocateFailed() {
56 return RefState(AllocateFailed, 0);
57 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000058 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
59 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000060 static RefState getRelinquished(const Stmt *s) {
61 return RefState(Relinquished, s);
62 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000063
64 void Profile(llvm::FoldingSetNodeID &ID) const {
65 ID.AddInteger(K);
66 ID.AddPointer(S);
67 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000068};
69
Anna Zaks40add292012-02-15 00:11:25 +000070struct ReallocPair {
71 SymbolRef ReallocatedSym;
72 bool IsFreeOnFailure;
73 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
74 void Profile(llvm::FoldingSetNodeID &ID) const {
75 ID.AddInteger(IsFreeOnFailure);
76 ID.AddPointer(ReallocatedSym);
77 }
78 bool operator==(const ReallocPair &X) const {
79 return ReallocatedSym == X.ReallocatedSym &&
80 IsFreeOnFailure == X.IsFreeOnFailure;
81 }
82};
83
Anna Zaksb319e022012-02-08 20:13:28 +000084class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000085 check::EndPath,
86 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000087 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000088 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000089 check::Location,
90 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000091 eval::Assume,
92 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000093{
Anna Zaksfebdc322012-02-16 22:26:12 +000094 mutable OwningPtr<BugType> BT_DoubleFree;
95 mutable OwningPtr<BugType> BT_Leak;
96 mutable OwningPtr<BugType> BT_UseFree;
97 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +000098 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks40add292012-02-15 00:11:25 +000099 *II_valloc, *II_reallocf;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000100
101public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000102 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks40add292012-02-15 00:11:25 +0000103 II_valloc(0), II_reallocf(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000104
105 /// In pessimistic mode, the checker assumes that it does not know which
106 /// functions might free the memory.
107 struct ChecksFilter {
108 DefaultBool CMallocPessimistic;
109 DefaultBool CMallocOptimistic;
110 };
111
112 ChecksFilter Filter;
113
Anna Zaks66c40402012-02-14 21:55:24 +0000114 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000115 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000116 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000117 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000118 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000119 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000120 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000121 void checkLocation(SVal l, bool isLoad, const Stmt *S,
122 CheckerContext &C) const;
123 void checkBind(SVal location, SVal val, const Stmt*S,
124 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000125 ProgramStateRef
126 checkRegionChanges(ProgramStateRef state,
127 const StoreManager::InvalidatedSymbols *invalidated,
128 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000129 ArrayRef<const MemRegion *> Regions,
130 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000131 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
132 return true;
133 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000134
Zhongxing Xu7b760962009-11-13 07:25:27 +0000135private:
Anna Zaks66c40402012-02-14 21:55:24 +0000136 void initIdentifierInfo(ASTContext &C) const;
137
138 /// Check if this is one of the functions which can allocate/reallocate memory
139 /// pointed to by one of its arguments.
140 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
141
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000142 static void MallocMem(CheckerContext &C, const CallExpr *CE);
143 static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
144 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000145 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000146 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000147 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000148 return MallocMemAux(C, CE,
149 state->getSVal(SizeEx, C.getLocationContext()),
150 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000151 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000152 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000153 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000154 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000155
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000156 void FreeMem(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose2a479922010-08-12 08:54:03 +0000157 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000158 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000159 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
160 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000161 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000162
Anna Zaks40add292012-02-15 00:11:25 +0000163 void ReallocMem(CheckerContext &C, const CallExpr *CE,
164 bool FreesMemOnFailure) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000165 static void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000166
Anna Zaks91c2a112012-02-08 23:16:56 +0000167 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
168 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
169 const Stmt *S = 0) const;
170
Anna Zaks66c40402012-02-14 21:55:24 +0000171 /// Check if the function is not known to us. So, for example, we could
172 /// conservatively assume it can free/reallocate it's pointer arguments.
173 bool hasUnknownBehavior(const FunctionDecl *FD, ProgramStateRef State) const;
174
Ted Kremenek9c378f72011-08-12 23:37:29 +0000175 static bool SummarizeValue(raw_ostream &os, SVal V);
176 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000177 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000178
Anna Zaksda046772012-02-11 21:02:40 +0000179 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
180
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000181 /// The bug visitor which allows us to print extra diagnostics along the
182 /// BugReport path. For example, showing the allocation site of the leaked
183 /// region.
184 class MallocBugVisitor : public BugReporterVisitor {
185 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000186 enum NotificationMode {
187 Normal,
188 Complete,
189 ReallocationFailed
190 };
191
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000192 // The allocated region symbol tracked by the main analysis.
193 SymbolRef Sym;
Anna Zaksfe571602012-02-16 22:26:07 +0000194 NotificationMode Mode;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000195
196 public:
Anna Zaksfe571602012-02-16 22:26:07 +0000197 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000198 virtual ~MallocBugVisitor() {}
199
200 void Profile(llvm::FoldingSetNodeID &ID) const {
201 static int X = 0;
202 ID.AddPointer(&X);
203 ID.AddPointer(Sym);
204 }
205
Anna Zaksfe571602012-02-16 22:26:07 +0000206 inline bool isAllocated(const RefState *S, const RefState *SPrev,
207 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000208 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000209 return (Stmt && isa<CallExpr>(Stmt) &&
210 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000211 }
212
Anna Zaksfe571602012-02-16 22:26:07 +0000213 inline bool isReleased(const RefState *S, const RefState *SPrev,
214 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000215 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000216 return (Stmt && isa<CallExpr>(Stmt) &&
217 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
218 }
219
220 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
221 const Stmt *Stmt) {
222 // If the expression is not a call, and the state change is
223 // released -> allocated, it must be the realloc return value
224 // check. If we have to handle more cases here, it might be cleaner just
225 // to track this extra bit in the state itself.
226 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
227 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000228 }
229
230 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
231 const ExplodedNode *PrevN,
232 BugReporterContext &BRC,
233 BugReport &BR);
234 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000235};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000236} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000237
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000238typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000239typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000240class RegionState {};
241class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000242namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000243namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000244 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000245 struct ProgramStateTrait<RegionState>
246 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000247 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000248 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000249
250 template <>
251 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000252 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000253 static void *GDMIndex() { static int x; return &x; }
254 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000255}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000256}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000257
Anna Zaks4fb54872012-02-11 21:02:35 +0000258namespace {
259class StopTrackingCallback : public SymbolVisitor {
260 ProgramStateRef state;
261public:
262 StopTrackingCallback(ProgramStateRef st) : state(st) {}
263 ProgramStateRef getState() const { return state; }
264
265 bool VisitSymbol(SymbolRef sym) {
266 state = state->remove<RegionState>(sym);
267 return true;
268 }
269};
270} // end anonymous namespace
271
Anna Zaks66c40402012-02-14 21:55:24 +0000272void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000273 if (!II_malloc)
274 II_malloc = &Ctx.Idents.get("malloc");
275 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000276 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000277 if (!II_realloc)
278 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000279 if (!II_reallocf)
280 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000281 if (!II_calloc)
282 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000283 if (!II_valloc)
284 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000285}
286
Anna Zaks66c40402012-02-14 21:55:24 +0000287bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000288 if (!FD)
289 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000290 IdentifierInfo *FunI = FD->getIdentifier();
291 if (!FunI)
292 return false;
293
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000294 initIdentifierInfo(C);
295
Anna Zaks66c40402012-02-14 21:55:24 +0000296 // TODO: Add more here : ex: reallocf!
Anna Zaks40add292012-02-15 00:11:25 +0000297 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
298 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc)
Anna Zaks66c40402012-02-14 21:55:24 +0000299 return true;
300
301 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
302 FD->specific_attr_begin<OwnershipAttr>() !=
303 FD->specific_attr_end<OwnershipAttr>())
304 return true;
305
306
307 return false;
308}
309
Anna Zaksb319e022012-02-08 20:13:28 +0000310void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
311 const FunctionDecl *FD = C.getCalleeDecl(CE);
312 if (!FD)
313 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000314
Anna Zaksb16ce452012-02-15 00:11:22 +0000315 initIdentifierInfo(C.getASTContext());
316 IdentifierInfo *FunI = FD->getIdentifier();
317 if (!FunI)
318 return;
319
320 if (FunI == II_malloc || FunI == II_valloc) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000321 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000322 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000323 } else if (FunI == II_realloc) {
Anna Zaks40add292012-02-15 00:11:25 +0000324 ReallocMem(C, CE, false);
325 return;
326 } else if (FunI == II_reallocf) {
327 ReallocMem(C, CE, true);
Anna Zaksb319e022012-02-08 20:13:28 +0000328 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000329 } else if (FunI == II_calloc) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000330 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000331 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000332 }else if (FunI == II_free) {
Anna Zaksb319e022012-02-08 20:13:28 +0000333 FreeMem(C, CE);
334 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000335 }
336
Anna Zaks91c2a112012-02-08 23:16:56 +0000337 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000338 // Check all the attributes, if there are any.
339 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000340 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000341 for (specific_attr_iterator<OwnershipAttr>
342 i = FD->specific_attr_begin<OwnershipAttr>(),
343 e = FD->specific_attr_end<OwnershipAttr>();
344 i != e; ++i) {
345 switch ((*i)->getOwnKind()) {
346 case OwnershipAttr::Returns: {
347 MallocMemReturnsAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000348 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000349 }
350 case OwnershipAttr::Takes:
351 case OwnershipAttr::Holds: {
352 FreeMemAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000353 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000354 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000355 }
356 }
357 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000358}
359
360void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000361 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000362 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000363 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000364}
365
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000366void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
367 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000368 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000369 return;
370
Sean Huntcf807c42010-08-18 23:23:40 +0000371 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000372 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000373 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000374 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000375 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000376 return;
377 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000378 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000379 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000380 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000381}
382
Anna Zaksb319e022012-02-08 20:13:28 +0000383ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000384 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000385 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000386 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000387 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000388
Anna Zaksb319e022012-02-08 20:13:28 +0000389 // Get the return value.
390 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000391
Anna Zaksb16ce452012-02-15 00:11:22 +0000392 // We expect the malloc functions to return a pointer.
393 if (!isa<Loc>(retVal))
394 return 0;
395
Jordy Rose32f26562010-07-04 00:00:41 +0000396 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000397 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000398
Jordy Rose32f26562010-07-04 00:00:41 +0000399 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000400 const SymbolicRegion *R =
401 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
402 if (!R || !isa<DefinedOrUnknownSVal>(Size))
403 return 0;
404
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000405 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000406 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000407 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000408 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000409
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000410 state = state->assume(extentMatchesSize, true);
411 assert(state);
412
413 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000414 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000415
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000416 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000417 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000418}
419
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000420void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000421 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000422
423 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000424 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000425}
426
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000427void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000428 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000429 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000430 return;
431
Sean Huntcf807c42010-08-18 23:23:40 +0000432 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
433 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000434 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000435 FreeMemAux(C, CE, C.getState(), *I,
436 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000437 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000438 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000439 }
440}
441
Ted Kremenek8bef8232012-01-26 21:29:00 +0000442ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000443 const CallExpr *CE,
444 ProgramStateRef state,
445 unsigned Num,
446 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000447 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000448 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000449 if (!isa<DefinedOrUnknownSVal>(ArgVal))
450 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000451 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
452
453 // Check for null dereferences.
454 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000455 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000456
Anna Zaksb276bd92012-02-14 00:26:13 +0000457 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000458 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000459 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000460 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000461 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000462
Jordy Rose43859f62010-06-07 19:32:37 +0000463 // Unknown values could easily be okay
464 // Undefined values are handled elsewhere
465 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000466 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000467
Jordy Rose43859f62010-06-07 19:32:37 +0000468 const MemRegion *R = ArgVal.getAsRegion();
469
470 // Nonlocs can't be freed, of course.
471 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
472 if (!R) {
473 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000474 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000475 }
476
477 R = R->StripCasts();
478
479 // Blocks might show up as heap data, but should not be free()d
480 if (isa<BlockDataRegion>(R)) {
481 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000482 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000483 }
484
485 const MemSpaceRegion *MS = R->getMemorySpace();
486
487 // Parameters, locals, statics, and globals shouldn't be freed.
488 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
489 // FIXME: at the time this code was written, malloc() regions were
490 // represented by conjured symbols, which are all in UnknownSpaceRegion.
491 // This means that there isn't actually anything from HeapSpaceRegion
492 // that should be freed, even though we allow it here.
493 // Of course, free() can work on memory allocated outside the current
494 // function, so UnknownSpaceRegion is always a possibility.
495 // False negatives are better than false positives.
496
497 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000498 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000499 }
500
501 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
502 // Various cases could lead to non-symbol values here.
503 // For now, ignore them.
504 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000505 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000506
507 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000508 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000509
510 // If the symbol has not been tracked, return. This is possible when free() is
511 // called on a pointer that does not get its pointee directly from malloc().
512 // Full support of this requires inter-procedural analysis.
513 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000514 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000515
516 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000517 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000518 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000519 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000520 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000521 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000522 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000523 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000524 R->addRange(ArgExpr->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000525 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000526 C.EmitReport(R);
527 }
Anna Zaksb319e022012-02-08 20:13:28 +0000528 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000529 }
530
531 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000532 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000533 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
534 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000535}
536
Ted Kremenek9c378f72011-08-12 23:37:29 +0000537bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000538 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
539 os << "an integer (" << IntVal->getValue() << ")";
540 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
541 os << "a constant address (" << ConstAddr->getValue() << ")";
542 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000543 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000544 else
545 return false;
546
547 return true;
548}
549
Ted Kremenek9c378f72011-08-12 23:37:29 +0000550bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000551 const MemRegion *MR) {
552 switch (MR->getKind()) {
553 case MemRegion::FunctionTextRegionKind: {
554 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
555 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000556 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000557 else
558 os << "the address of a function";
559 return true;
560 }
561 case MemRegion::BlockTextRegionKind:
562 os << "block text";
563 return true;
564 case MemRegion::BlockDataRegionKind:
565 // FIXME: where the block came from?
566 os << "a block";
567 return true;
568 default: {
569 const MemSpaceRegion *MS = MR->getMemorySpace();
570
Anna Zakseb31a762012-01-04 23:54:01 +0000571 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000572 const VarRegion *VR = dyn_cast<VarRegion>(MR);
573 const VarDecl *VD;
574 if (VR)
575 VD = VR->getDecl();
576 else
577 VD = NULL;
578
579 if (VD)
580 os << "the address of the local variable '" << VD->getName() << "'";
581 else
582 os << "the address of a local stack variable";
583 return true;
584 }
Anna Zakseb31a762012-01-04 23:54:01 +0000585
586 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000587 const VarRegion *VR = dyn_cast<VarRegion>(MR);
588 const VarDecl *VD;
589 if (VR)
590 VD = VR->getDecl();
591 else
592 VD = NULL;
593
594 if (VD)
595 os << "the address of the parameter '" << VD->getName() << "'";
596 else
597 os << "the address of a parameter";
598 return true;
599 }
Anna Zakseb31a762012-01-04 23:54:01 +0000600
601 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000602 const VarRegion *VR = dyn_cast<VarRegion>(MR);
603 const VarDecl *VD;
604 if (VR)
605 VD = VR->getDecl();
606 else
607 VD = NULL;
608
609 if (VD) {
610 if (VD->isStaticLocal())
611 os << "the address of the static variable '" << VD->getName() << "'";
612 else
613 os << "the address of the global variable '" << VD->getName() << "'";
614 } else
615 os << "the address of a global variable";
616 return true;
617 }
Anna Zakseb31a762012-01-04 23:54:01 +0000618
619 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000620 }
621 }
622}
623
624void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000625 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000626 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000627 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000628 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000629
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000630 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000631 llvm::raw_svector_ostream os(buf);
632
633 const MemRegion *MR = ArgVal.getAsRegion();
634 if (MR) {
635 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
636 MR = ER->getSuperRegion();
637
638 // Special case for alloca()
639 if (isa<AllocaRegion>(MR))
640 os << "Argument to free() was allocated by alloca(), not malloc()";
641 else {
642 os << "Argument to free() is ";
643 if (SummarizeRegion(os, MR))
644 os << ", which is not memory allocated by malloc()";
645 else
646 os << "not memory allocated by malloc()";
647 }
648 } else {
649 os << "Argument to free() is ";
650 if (SummarizeValue(os, ArgVal))
651 os << ", which is not memory allocated by malloc()";
652 else
653 os << "not memory allocated by malloc()";
654 }
655
Anna Zakse172e8b2011-08-17 23:00:25 +0000656 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000657 R->addRange(range);
658 C.EmitReport(R);
659 }
660}
661
Anna Zaks40add292012-02-15 00:11:25 +0000662void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE,
663 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000664 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000665 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000666 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000667 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
668 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
669 return;
670 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000671
Ted Kremenek846eabd2010-12-01 21:28:31 +0000672 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000673
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000674 DefinedOrUnknownSVal PtrEQ =
675 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000676
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000677 // Get the size argument. If there is no size arg then give up.
678 const Expr *Arg1 = CE->getArg(1);
679 if (!Arg1)
680 return;
681
682 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000683 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
684 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
685 return;
686 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000687
688 // Compare the size argument to 0.
689 DefinedOrUnknownSVal SizeZero =
690 svalBuilder.evalEQ(state, Arg1Val,
691 svalBuilder.makeIntValWithPtrWidth(0, false));
692
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000693 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
694 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
695 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
696 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
697 // We only assume exceptional states if they are definitely true; if the
698 // state is under-constrained, assume regular realloc behavior.
699 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
700 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
701
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000702 // If the ptr is NULL and the size is not 0, the call is equivalent to
703 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000704 if ( PrtIsNull && !SizeIsZero) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000705 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000706 UndefinedVal(), StatePtrIsNull);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000707 C.addTransition(stateMalloc);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000708 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000709 }
710
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000711 if (PrtIsNull && SizeIsZero)
712 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000713
Anna Zaks30838b92012-02-13 20:57:07 +0000714 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000715 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000716 SymbolRef FromPtr = arg0Val.getAsSymbol();
717 SVal RetVal = state->getSVal(CE, LCtx);
718 SymbolRef ToPtr = RetVal.getAsSymbol();
719 if (!FromPtr || !ToPtr)
720 return;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000721
722 // If the size is 0, free the memory.
723 if (SizeIsZero)
724 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000725 // The semantics of the return value are:
726 // If size was equal to 0, either NULL or a pointer suitable to be passed
727 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000728 stateFree = stateFree->set<ReallocPairs>(ToPtr,
729 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000730 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks30838b92012-02-13 20:57:07 +0000731 C.addTransition(stateFree);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000732 return;
733 }
734
735 // Default behavior.
736 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
737 // FIXME: We should copy the content of the original buffer.
738 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
739 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000740 if (!stateRealloc)
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000741 return;
Anna Zaks40add292012-02-15 00:11:25 +0000742 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
743 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000744 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000745 C.addTransition(stateRealloc);
746 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000747 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000748}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000749
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000750void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000751 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000752 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000753 const LocationContext *LCtx = C.getLocationContext();
754 SVal count = state->getSVal(CE->getArg(0), LCtx);
755 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000756 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
757 svalBuilder.getContext().getSizeType());
758 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000759
Anna Zaks0bd6b112011-10-26 21:06:34 +0000760 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000761}
762
Anna Zaksda046772012-02-11 21:02:40 +0000763void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
764 CheckerContext &C) const {
765 assert(N);
766 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000767 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000768 // Leaks should not be reported if they are post-dominated by a sink:
769 // (1) Sinks are higher importance bugs.
770 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
771 // with __noreturn functions such as assert() or exit(). We choose not
772 // to report leaks on such paths.
773 BT_Leak->setSuppressOnSink(true);
774 }
775
Anna Zaksfebdc322012-02-16 22:26:12 +0000776 BugReport *R = new BugReport(*BT_Leak,
777 "Memory is never released; potential memory leak", N);
Anna Zaksda046772012-02-11 21:02:40 +0000778 R->addVisitor(new MallocBugVisitor(Sym));
779 C.EmitReport(R);
780}
781
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000782void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
783 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000784{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000785 if (!SymReaper.hasDeadSymbols())
786 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000787
Ted Kremenek8bef8232012-01-26 21:29:00 +0000788 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000789 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000790 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000791
Ted Kremenek217470e2011-07-28 23:07:51 +0000792 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000793 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000794 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
795 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000796 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000797 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000798 Errors.push_back(I->first);
799 }
Jordy Rose90760142010-08-18 04:33:47 +0000800 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000801 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000802
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000803 }
804 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000805
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000806 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000807 ReallocMap RP = state->get<ReallocPairs>();
808 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
809 if (SymReaper.isDead(I->first) ||
810 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000811 state = state->remove<ReallocPairs>(I->first);
812 }
813 }
814
Anna Zaks0bd6b112011-10-26 21:06:34 +0000815 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000816
Ted Kremenek217470e2011-07-28 23:07:51 +0000817 if (N && generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000818 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000819 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
820 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000821 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000822 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000823}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000824
Anna Zaksda046772012-02-11 21:02:40 +0000825void MallocChecker::checkEndPath(CheckerContext &C) const {
826 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000827 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000828
Jordy Rose09cef092010-08-18 04:26:59 +0000829 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000830 RefState RS = I->second;
831 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000832 ExplodedNode *N = C.addTransition(state);
833 if (N)
834 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000835 }
836 }
837}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000838
Anna Zaks91c2a112012-02-08 23:16:56 +0000839bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
840 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000841 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000842 const RefState *RS = state->get<RegionState>(Sym);
843 if (!RS)
844 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000845
Anna Zaks91c2a112012-02-08 23:16:56 +0000846 if (RS->isAllocated()) {
847 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
848 C.addTransition(state);
849 return true;
850 }
851 return false;
852}
853
Anna Zaks66c40402012-02-14 21:55:24 +0000854void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
855 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
856 return;
857
858 // Check use after free, when a freed pointer is passed to a call.
859 ProgramStateRef State = C.getState();
860 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
861 E = CE->arg_end(); I != E; ++I) {
862 const Expr *A = *I;
863 if (A->getType().getTypePtr()->isAnyPointerType()) {
864 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
865 if (!Sym)
866 continue;
867 if (checkUseAfterFree(Sym, C, A))
868 return;
869 }
870 }
871}
872
Anna Zaks91c2a112012-02-08 23:16:56 +0000873void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
874 const Expr *E = S->getRetValue();
875 if (!E)
876 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000877
878 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000879 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000880 if (!Sym)
881 return;
882
Anna Zaks0860cd02012-02-11 21:44:39 +0000883 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +0000884 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +0000885 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000886
887 // Check if the symbol is escaping.
Anna Zaksfe571602012-02-16 22:26:07 +0000888 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000889}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000890
Anna Zaks91c2a112012-02-08 23:16:56 +0000891bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
892 const Stmt *S) const {
893 assert(Sym);
894 const RefState *RS = C.getState()->get<RegionState>(Sym);
895 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000896 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000897 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000898 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +0000899
Anna Zaksfebdc322012-02-16 22:26:12 +0000900 BugReport *R = new BugReport(*BT_UseFree,
901 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +0000902 if (S)
903 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000904 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000905 C.EmitReport(R);
906 return true;
907 }
908 }
909 return false;
910}
911
Zhongxing Xuc8023782010-03-10 04:58:55 +0000912// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000913void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
914 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000915 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000916 if (Sym)
917 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000918}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000919
Anna Zaks4fb54872012-02-11 21:02:35 +0000920//===----------------------------------------------------------------------===//
921// Check various ways a symbol can be invalidated.
922// TODO: This logic (the next 3 functions) is copied/similar to the
923// RetainRelease checker. We might want to factor this out.
924//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000925
Anna Zaks4fb54872012-02-11 21:02:35 +0000926// Stop tracking symbols when a value escapes as a result of checkBind.
927// A value escapes in three possible cases:
928// (1) we are binding to something that is not a memory region.
929// (2) we are binding to a memregion that does not have stack storage
930// (3) we are binding to a memregion with stack storage that the store
931// does not understand.
932void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
933 CheckerContext &C) const {
934 // Are we storing to something that causes the value to "escape"?
935 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000936 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000937
Anna Zaks4fb54872012-02-11 21:02:35 +0000938 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
939 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000940
Anna Zaks4fb54872012-02-11 21:02:35 +0000941 if (!escapes) {
942 // To test (3), generate a new state with the binding added. If it is
943 // the same state, then it escapes (since the store cannot represent
944 // the binding).
945 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000946 }
Anna Zaksac593002012-02-16 03:40:57 +0000947 if (!escapes) {
948 // Case 4: We do not currently model what happens when a symbol is
949 // assigned to a struct field, so be conservative here and let the symbol
950 // go. TODO: This could definitely be improved upon.
951 escapes = !isa<VarRegion>(regionLoc->getRegion());
952 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000953 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000954
955 // If our store can represent the binding and we aren't storing to something
956 // that doesn't have local storage then just return and have the simulation
957 // state continue as is.
958 if (!escapes)
959 return;
960
961 // Otherwise, find all symbols referenced by 'val' that we are tracking
962 // and stop tracking them.
963 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
964 C.addTransition(state);
965}
966
967// If a symbolic region is assumed to NULL (or another constant), stop tracking
968// it - assuming that allocation failed on this path.
969ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
970 SVal Cond,
971 bool Assumption) const {
972 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +0000973 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
974 // If the symbol is assumed to NULL or another constant, this will
975 // return an APSInt*.
976 if (state->getSymVal(I.getKey()))
977 state = state->remove<RegionState>(I.getKey());
978 }
979
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000980 // Realloc returns 0 when reallocation fails, which means that we should
981 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000982 ReallocMap RP = state->get<ReallocPairs>();
983 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000984 // If the symbol is assumed to NULL or another constant, this will
985 // return an APSInt*.
986 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +0000987 SymbolRef ReallocSym = I.getData().ReallocatedSym;
988 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000989 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +0000990 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
991 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000992 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000993 }
994 state = state->remove<ReallocPairs>(I.getKey());
995 }
996 }
997
Anna Zaks4fb54872012-02-11 21:02:35 +0000998 return state;
999}
1000
Anna Zaks66c40402012-02-14 21:55:24 +00001001// Check if the function is not known to us. So, for example, we could
1002// conservatively assume it can free/reallocate it's pointer arguments.
1003// (We assume that the pointers cannot escape through calls to system
1004// functions not handled by this checker.)
1005bool MallocChecker::hasUnknownBehavior(const FunctionDecl *FD,
1006 ProgramStateRef State) const {
1007 ASTContext &ASTC = State->getStateManager().getContext();
1008
1009 // If it's one of the allocation functions we can reason about, we model it's
1010 // behavior explicitly.
1011 if (isMemFunction(FD, ASTC)) {
1012 return false;
1013 }
1014
1015 // If it's a system call, we know it does not free the memory.
1016 SourceManager &SM = ASTC.getSourceManager();
1017 if (SM.isInSystemHeader(FD->getLocation())) {
1018 return false;
1019 }
1020
1021 // Otherwise, assume that the function can free memory.
1022 return true;
1023}
1024
Anna Zaks4fb54872012-02-11 21:02:35 +00001025// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1026// escapes, when we are tracking p), do not track the symbol as we cannot reason
1027// about it anymore.
1028ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001029MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001030 const StoreManager::InvalidatedSymbols *invalidated,
1031 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001032 ArrayRef<const MemRegion *> Regions,
1033 const CallOrObjCMessage *Call) const {
Anna Zaks4fb54872012-02-11 21:02:35 +00001034 if (!invalidated)
Anna Zaks66c40402012-02-14 21:55:24 +00001035 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001036 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001037
Anna Zaks1d6cc6a2012-02-15 02:12:00 +00001038 const FunctionDecl *FD = (Call ?
1039 dyn_cast_or_null<FunctionDecl>(Call->getDecl()) :0);
Anna Zaks66c40402012-02-14 21:55:24 +00001040
1041 // If it's a call which might free or reallocate memory, we assume that all
1042 // regions (explicit and implicit) escaped. Otherwise, whitelist explicit
1043 // pointers; we still can track them.
1044 if (!(FD && hasUnknownBehavior(FD, State))) {
1045 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1046 E = ExplicitRegions.end(); I != E; ++I) {
1047 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1048 WhitelistedSymbols.insert(R->getSymbol());
1049 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001050 }
1051
1052 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1053 E = invalidated->end(); I!=E; ++I) {
1054 SymbolRef sym = *I;
1055 if (WhitelistedSymbols.count(sym))
1056 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001057 // The symbol escaped.
1058 if (const RefState *RS = State->get<RegionState>(sym))
1059 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001060 }
Anna Zaks66c40402012-02-14 21:55:24 +00001061 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001062}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001063
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001064PathDiagnosticPiece *
1065MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1066 const ExplodedNode *PrevN,
1067 BugReporterContext &BRC,
1068 BugReport &BR) {
1069 const RefState *RS = N->getState()->get<RegionState>(Sym);
1070 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1071 if (!RS && !RSPrev)
1072 return 0;
1073
Anna Zaksfe571602012-02-16 22:26:07 +00001074 const Stmt *S = 0;
1075 const char *Msg = 0;
1076
1077 // Retrieve the associated statement.
1078 ProgramPoint ProgLoc = N->getLocation();
1079 if (isa<StmtPoint>(ProgLoc))
1080 S = cast<StmtPoint>(ProgLoc).getStmt();
1081 // If an assumption was made on a branch, it should be caught
1082 // here by looking at the state transition.
1083 if (isa<BlockEdge>(ProgLoc)) {
1084 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1085 S = srcBlk->getTerminator();
1086 }
1087 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001088 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001089
1090 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001091 if (Mode == Normal) {
1092 if (isAllocated(RS, RSPrev, S))
1093 Msg = "Memory is allocated";
1094 else if (isReleased(RS, RSPrev, S))
1095 Msg = "Memory is released";
1096 else if (isReallocFailedCheck(RS, RSPrev, S)) {
1097 Mode = ReallocationFailed;
1098 Msg = "Reallocation failed";
1099 }
1100
1101 // We are in a special mode if a reallocation failed later in the path.
1102 } else if (Mode == ReallocationFailed) {
1103 // Generate a special diagnostic for the first realloc we find.
1104 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1105 return 0;
1106
1107 // Check that the name of the function is realloc.
1108 const CallExpr *CE = dyn_cast<CallExpr>(S);
1109 if (!CE)
1110 return 0;
1111 const FunctionDecl *funDecl = CE->getDirectCallee();
1112 if (!funDecl)
1113 return 0;
1114 StringRef FunName = funDecl->getName();
1115 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1116 return 0;
1117 Msg = "Attempt to reallocate memory";
1118 Mode = Normal;
1119 }
1120
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001121 if (!Msg)
1122 return 0;
1123
1124 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001125 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001126 N->getLocationContext());
1127 return new PathDiagnosticEventPiece(Pos, Msg);
1128}
1129
1130
Anna Zaks231361a2012-02-08 23:16:52 +00001131#define REGISTER_CHECKER(name) \
1132void ento::register##name(CheckerManager &mgr) {\
1133 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001134}
Anna Zaks231361a2012-02-08 23:16:52 +00001135
1136REGISTER_CHECKER(MallocPessimistic)
1137REGISTER_CHECKER(MallocOptimistic)