blob: 766de4b751254ccbafd21bf417c6b1acabf28292 [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{
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000094 mutable OwningPtr<BuiltinBug> BT_DoubleFree;
95 mutable OwningPtr<BuiltinBug> BT_Leak;
96 mutable OwningPtr<BuiltinBug> BT_UseFree;
97 mutable OwningPtr<BuiltinBug> BT_UseRelinquished;
98 mutable OwningPtr<BuiltinBug> 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:
187 // The allocated region symbol tracked by the main analysis.
188 SymbolRef Sym;
189
190 public:
191 MallocBugVisitor(SymbolRef S) : Sym(S) {}
192 virtual ~MallocBugVisitor() {}
193
194 void Profile(llvm::FoldingSetNodeID &ID) const {
195 static int X = 0;
196 ID.AddPointer(&X);
197 ID.AddPointer(Sym);
198 }
199
200 inline bool isAllocated(const RefState *S, const RefState *SPrev) {
201 // Did not track -> allocated. Other state (released) -> allocated.
202 return ((S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
203 }
204
205 inline bool isReleased(const RefState *S, const RefState *SPrev) {
206 // Did not track -> released. Other state (allocated) -> released.
207 return ((S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
208 }
209
210 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
211 const ExplodedNode *PrevN,
212 BugReporterContext &BRC,
213 BugReport &BR);
214 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000215};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000216} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000217
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000218typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000219typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000220class RegionState {};
221class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000222namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000223namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000224 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000225 struct ProgramStateTrait<RegionState>
226 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000227 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000228 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000229
230 template <>
231 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000232 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000233 static void *GDMIndex() { static int x; return &x; }
234 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000235}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000236}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000237
Anna Zaks4fb54872012-02-11 21:02:35 +0000238namespace {
239class StopTrackingCallback : public SymbolVisitor {
240 ProgramStateRef state;
241public:
242 StopTrackingCallback(ProgramStateRef st) : state(st) {}
243 ProgramStateRef getState() const { return state; }
244
245 bool VisitSymbol(SymbolRef sym) {
246 state = state->remove<RegionState>(sym);
247 return true;
248 }
249};
250} // end anonymous namespace
251
Anna Zaks66c40402012-02-14 21:55:24 +0000252void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000253 if (!II_malloc)
254 II_malloc = &Ctx.Idents.get("malloc");
255 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000256 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000257 if (!II_realloc)
258 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000259 if (!II_reallocf)
260 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000261 if (!II_calloc)
262 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000263 if (!II_valloc)
264 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000265}
266
Anna Zaks66c40402012-02-14 21:55:24 +0000267bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
268 initIdentifierInfo(C);
269 IdentifierInfo *FunI = FD->getIdentifier();
270 if (!FunI)
271 return false;
272
273 // TODO: Add more here : ex: reallocf!
Anna Zaks40add292012-02-15 00:11:25 +0000274 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
275 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc)
Anna Zaks66c40402012-02-14 21:55:24 +0000276 return true;
277
278 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
279 FD->specific_attr_begin<OwnershipAttr>() !=
280 FD->specific_attr_end<OwnershipAttr>())
281 return true;
282
283
284 return false;
285}
286
Anna Zaksb319e022012-02-08 20:13:28 +0000287void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
288 const FunctionDecl *FD = C.getCalleeDecl(CE);
289 if (!FD)
290 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000291
Anna Zaksb16ce452012-02-15 00:11:22 +0000292 initIdentifierInfo(C.getASTContext());
293 IdentifierInfo *FunI = FD->getIdentifier();
294 if (!FunI)
295 return;
296
297 if (FunI == II_malloc || FunI == II_valloc) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000298 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000299 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000300 } else if (FunI == II_realloc) {
Anna Zaks40add292012-02-15 00:11:25 +0000301 ReallocMem(C, CE, false);
302 return;
303 } else if (FunI == II_reallocf) {
304 ReallocMem(C, CE, true);
Anna Zaksb319e022012-02-08 20:13:28 +0000305 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000306 } else if (FunI == II_calloc) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000307 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000308 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000309 }else if (FunI == II_free) {
Anna Zaksb319e022012-02-08 20:13:28 +0000310 FreeMem(C, CE);
311 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000312 }
313
Anna Zaks91c2a112012-02-08 23:16:56 +0000314 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000315 // Check all the attributes, if there are any.
316 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000317 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000318 for (specific_attr_iterator<OwnershipAttr>
319 i = FD->specific_attr_begin<OwnershipAttr>(),
320 e = FD->specific_attr_end<OwnershipAttr>();
321 i != e; ++i) {
322 switch ((*i)->getOwnKind()) {
323 case OwnershipAttr::Returns: {
324 MallocMemReturnsAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000325 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000326 }
327 case OwnershipAttr::Takes:
328 case OwnershipAttr::Holds: {
329 FreeMemAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000330 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000331 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000332 }
333 }
334 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000335}
336
337void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000338 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000339 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000340 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000341}
342
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000343void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
344 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000345 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000346 return;
347
Sean Huntcf807c42010-08-18 23:23:40 +0000348 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000349 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000350 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000351 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000352 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000353 return;
354 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000355 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000356 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000357 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000358}
359
Anna Zaksb319e022012-02-08 20:13:28 +0000360ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000361 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000362 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000363 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000364 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000365
Anna Zaksb319e022012-02-08 20:13:28 +0000366 // Get the return value.
367 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000368
Anna Zaksb16ce452012-02-15 00:11:22 +0000369 // We expect the malloc functions to return a pointer.
370 if (!isa<Loc>(retVal))
371 return 0;
372
Jordy Rose32f26562010-07-04 00:00:41 +0000373 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000374 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000375
Jordy Rose32f26562010-07-04 00:00:41 +0000376 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000377 const SymbolicRegion *R =
378 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
379 if (!R || !isa<DefinedOrUnknownSVal>(Size))
380 return 0;
381
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000382 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000383 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000384 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000385 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000386
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000387 state = state->assume(extentMatchesSize, true);
388 assert(state);
389
390 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000391 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000392
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000393 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000394 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000395}
396
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000397void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000398 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000399
400 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000401 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000402}
403
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000404void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000405 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000406 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000407 return;
408
Sean Huntcf807c42010-08-18 23:23:40 +0000409 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
410 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000411 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000412 FreeMemAux(C, CE, C.getState(), *I,
413 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000414 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000415 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000416 }
417}
418
Ted Kremenek8bef8232012-01-26 21:29:00 +0000419ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000420 const CallExpr *CE,
421 ProgramStateRef state,
422 unsigned Num,
423 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000424 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000425 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000426 if (!isa<DefinedOrUnknownSVal>(ArgVal))
427 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000428 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
429
430 // Check for null dereferences.
431 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000432 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000433
Anna Zaksb276bd92012-02-14 00:26:13 +0000434 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000435 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000436 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000437 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000438 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000439
Jordy Rose43859f62010-06-07 19:32:37 +0000440 // Unknown values could easily be okay
441 // Undefined values are handled elsewhere
442 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000443 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000444
Jordy Rose43859f62010-06-07 19:32:37 +0000445 const MemRegion *R = ArgVal.getAsRegion();
446
447 // Nonlocs can't be freed, of course.
448 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
449 if (!R) {
450 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000451 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000452 }
453
454 R = R->StripCasts();
455
456 // Blocks might show up as heap data, but should not be free()d
457 if (isa<BlockDataRegion>(R)) {
458 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000459 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000460 }
461
462 const MemSpaceRegion *MS = R->getMemorySpace();
463
464 // Parameters, locals, statics, and globals shouldn't be freed.
465 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
466 // FIXME: at the time this code was written, malloc() regions were
467 // represented by conjured symbols, which are all in UnknownSpaceRegion.
468 // This means that there isn't actually anything from HeapSpaceRegion
469 // that should be freed, even though we allow it here.
470 // Of course, free() can work on memory allocated outside the current
471 // function, so UnknownSpaceRegion is always a possibility.
472 // False negatives are better than false positives.
473
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 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
479 // Various cases could lead to non-symbol values here.
480 // For now, ignore them.
481 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000482 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000483
484 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000485 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000486
487 // If the symbol has not been tracked, return. This is possible when free() is
488 // called on a pointer that does not get its pointee directly from malloc().
489 // Full support of this requires inter-procedural analysis.
490 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000491 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000492
493 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000494 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000495 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000496 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000497 BT_DoubleFree.reset(
498 new BuiltinBug("Double free",
499 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000500 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000501 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000502 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000503 C.EmitReport(R);
504 }
Anna Zaksb319e022012-02-08 20:13:28 +0000505 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000506 }
507
508 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000509 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000510 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
511 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000512}
513
Ted Kremenek9c378f72011-08-12 23:37:29 +0000514bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000515 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
516 os << "an integer (" << IntVal->getValue() << ")";
517 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
518 os << "a constant address (" << ConstAddr->getValue() << ")";
519 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000520 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000521 else
522 return false;
523
524 return true;
525}
526
Ted Kremenek9c378f72011-08-12 23:37:29 +0000527bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000528 const MemRegion *MR) {
529 switch (MR->getKind()) {
530 case MemRegion::FunctionTextRegionKind: {
531 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
532 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000533 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000534 else
535 os << "the address of a function";
536 return true;
537 }
538 case MemRegion::BlockTextRegionKind:
539 os << "block text";
540 return true;
541 case MemRegion::BlockDataRegionKind:
542 // FIXME: where the block came from?
543 os << "a block";
544 return true;
545 default: {
546 const MemSpaceRegion *MS = MR->getMemorySpace();
547
Anna Zakseb31a762012-01-04 23:54:01 +0000548 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000549 const VarRegion *VR = dyn_cast<VarRegion>(MR);
550 const VarDecl *VD;
551 if (VR)
552 VD = VR->getDecl();
553 else
554 VD = NULL;
555
556 if (VD)
557 os << "the address of the local variable '" << VD->getName() << "'";
558 else
559 os << "the address of a local stack variable";
560 return true;
561 }
Anna Zakseb31a762012-01-04 23:54:01 +0000562
563 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000564 const VarRegion *VR = dyn_cast<VarRegion>(MR);
565 const VarDecl *VD;
566 if (VR)
567 VD = VR->getDecl();
568 else
569 VD = NULL;
570
571 if (VD)
572 os << "the address of the parameter '" << VD->getName() << "'";
573 else
574 os << "the address of a parameter";
575 return true;
576 }
Anna Zakseb31a762012-01-04 23:54:01 +0000577
578 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000579 const VarRegion *VR = dyn_cast<VarRegion>(MR);
580 const VarDecl *VD;
581 if (VR)
582 VD = VR->getDecl();
583 else
584 VD = NULL;
585
586 if (VD) {
587 if (VD->isStaticLocal())
588 os << "the address of the static variable '" << VD->getName() << "'";
589 else
590 os << "the address of the global variable '" << VD->getName() << "'";
591 } else
592 os << "the address of a global variable";
593 return true;
594 }
Anna Zakseb31a762012-01-04 23:54:01 +0000595
596 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000597 }
598 }
599}
600
601void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000602 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000603 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000604 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000605 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000606
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000607 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000608 llvm::raw_svector_ostream os(buf);
609
610 const MemRegion *MR = ArgVal.getAsRegion();
611 if (MR) {
612 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
613 MR = ER->getSuperRegion();
614
615 // Special case for alloca()
616 if (isa<AllocaRegion>(MR))
617 os << "Argument to free() was allocated by alloca(), not malloc()";
618 else {
619 os << "Argument to free() is ";
620 if (SummarizeRegion(os, MR))
621 os << ", which is not memory allocated by malloc()";
622 else
623 os << "not memory allocated by malloc()";
624 }
625 } else {
626 os << "Argument to free() is ";
627 if (SummarizeValue(os, ArgVal))
628 os << ", which is not memory allocated by malloc()";
629 else
630 os << "not memory allocated by malloc()";
631 }
632
Anna Zakse172e8b2011-08-17 23:00:25 +0000633 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000634 R->addRange(range);
635 C.EmitReport(R);
636 }
637}
638
Anna Zaks40add292012-02-15 00:11:25 +0000639void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE,
640 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000641 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000642 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000643 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000644 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
645 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
646 return;
647 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000648
Ted Kremenek846eabd2010-12-01 21:28:31 +0000649 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000650
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000651 DefinedOrUnknownSVal PtrEQ =
652 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000653
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000654 // Get the size argument. If there is no size arg then give up.
655 const Expr *Arg1 = CE->getArg(1);
656 if (!Arg1)
657 return;
658
659 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000660 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
661 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
662 return;
663 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000664
665 // Compare the size argument to 0.
666 DefinedOrUnknownSVal SizeZero =
667 svalBuilder.evalEQ(state, Arg1Val,
668 svalBuilder.makeIntValWithPtrWidth(0, false));
669
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000670 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
671 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
672 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
673 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
674 // We only assume exceptional states if they are definitely true; if the
675 // state is under-constrained, assume regular realloc behavior.
676 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
677 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
678
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000679 // If the ptr is NULL and the size is not 0, the call is equivalent to
680 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000681 if ( PrtIsNull && !SizeIsZero) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000682 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000683 UndefinedVal(), StatePtrIsNull);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000684 C.addTransition(stateMalloc);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000685 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000686 }
687
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000688 if (PrtIsNull && SizeIsZero)
689 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000690
Anna Zaks30838b92012-02-13 20:57:07 +0000691 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000692 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000693 SymbolRef FromPtr = arg0Val.getAsSymbol();
694 SVal RetVal = state->getSVal(CE, LCtx);
695 SymbolRef ToPtr = RetVal.getAsSymbol();
696 if (!FromPtr || !ToPtr)
697 return;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000698
699 // If the size is 0, free the memory.
700 if (SizeIsZero)
701 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000702 // The semantics of the return value are:
703 // If size was equal to 0, either NULL or a pointer suitable to be passed
704 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000705 stateFree = stateFree->set<ReallocPairs>(ToPtr,
706 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000707 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks30838b92012-02-13 20:57:07 +0000708 C.addTransition(stateFree);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000709 return;
710 }
711
712 // Default behavior.
713 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
714 // FIXME: We should copy the content of the original buffer.
715 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
716 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000717 if (!stateRealloc)
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000718 return;
Anna Zaks40add292012-02-15 00:11:25 +0000719 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
720 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000721 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000722 C.addTransition(stateRealloc);
723 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000724 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000725}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000726
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000727void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000728 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000729 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000730 const LocationContext *LCtx = C.getLocationContext();
731 SVal count = state->getSVal(CE->getArg(0), LCtx);
732 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000733 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
734 svalBuilder.getContext().getSizeType());
735 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000736
Anna Zaks0bd6b112011-10-26 21:06:34 +0000737 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000738}
739
Anna Zaksda046772012-02-11 21:02:40 +0000740void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
741 CheckerContext &C) const {
742 assert(N);
743 if (!BT_Leak) {
744 BT_Leak.reset(new BuiltinBug("Memory leak",
745 "Allocated memory never released. Potential memory leak."));
746 // Leaks should not be reported if they are post-dominated by a sink:
747 // (1) Sinks are higher importance bugs.
748 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
749 // with __noreturn functions such as assert() or exit(). We choose not
750 // to report leaks on such paths.
751 BT_Leak->setSuppressOnSink(true);
752 }
753
754 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
755 R->addVisitor(new MallocBugVisitor(Sym));
756 C.EmitReport(R);
757}
758
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000759void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
760 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000761{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000762 if (!SymReaper.hasDeadSymbols())
763 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000764
Ted Kremenek8bef8232012-01-26 21:29:00 +0000765 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000766 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000767 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000768
Ted Kremenek217470e2011-07-28 23:07:51 +0000769 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000770 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000771 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
772 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000773 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000774 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000775 Errors.push_back(I->first);
776 }
Jordy Rose90760142010-08-18 04:33:47 +0000777 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000778 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000779
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000780 }
781 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000782
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000783 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000784 ReallocMap RP = state->get<ReallocPairs>();
785 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
786 if (SymReaper.isDead(I->first) ||
787 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000788 state = state->remove<ReallocPairs>(I->first);
789 }
790 }
791
Anna Zaks0bd6b112011-10-26 21:06:34 +0000792 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000793
Ted Kremenek217470e2011-07-28 23:07:51 +0000794 if (N && generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000795 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000796 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
797 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000798 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000799 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000800}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000801
Anna Zaksda046772012-02-11 21:02:40 +0000802void MallocChecker::checkEndPath(CheckerContext &C) const {
803 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000804 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000805
Jordy Rose09cef092010-08-18 04:26:59 +0000806 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000807 RefState RS = I->second;
808 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000809 ExplodedNode *N = C.addTransition(state);
810 if (N)
811 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000812 }
813 }
814}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000815
Anna Zaks91c2a112012-02-08 23:16:56 +0000816bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
817 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000818 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000819 const RefState *RS = state->get<RegionState>(Sym);
820 if (!RS)
821 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000822
Anna Zaks91c2a112012-02-08 23:16:56 +0000823 if (RS->isAllocated()) {
824 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
825 C.addTransition(state);
826 return true;
827 }
828 return false;
829}
830
Anna Zaks66c40402012-02-14 21:55:24 +0000831void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
832 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
833 return;
834
835 // Check use after free, when a freed pointer is passed to a call.
836 ProgramStateRef State = C.getState();
837 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
838 E = CE->arg_end(); I != E; ++I) {
839 const Expr *A = *I;
840 if (A->getType().getTypePtr()->isAnyPointerType()) {
841 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
842 if (!Sym)
843 continue;
844 if (checkUseAfterFree(Sym, C, A))
845 return;
846 }
847 }
848}
849
Anna Zaks91c2a112012-02-08 23:16:56 +0000850void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
851 const Expr *E = S->getRetValue();
852 if (!E)
853 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000854
855 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000856 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000857 if (!Sym)
858 return;
859
Anna Zaks0860cd02012-02-11 21:44:39 +0000860 // Check if we are returning freed memory.
Anna Zaks15d0ae12012-02-11 23:46:36 +0000861 if (checkUseAfterFree(Sym, C, S))
862 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000863
864 // Check if the symbol is escaping.
Anna Zaks91c2a112012-02-08 23:16:56 +0000865 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000866}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000867
Anna Zaks91c2a112012-02-08 23:16:56 +0000868bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
869 const Stmt *S) const {
870 assert(Sym);
871 const RefState *RS = C.getState()->get<RegionState>(Sym);
872 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000873 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000874 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000875 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000876 "after it is freed."));
877
878 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
879 if (S)
880 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000881 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000882 C.EmitReport(R);
883 return true;
884 }
885 }
886 return false;
887}
888
Zhongxing Xuc8023782010-03-10 04:58:55 +0000889// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000890void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
891 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000892 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000893 if (Sym)
894 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000895}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000896
Anna Zaks4fb54872012-02-11 21:02:35 +0000897//===----------------------------------------------------------------------===//
898// Check various ways a symbol can be invalidated.
899// TODO: This logic (the next 3 functions) is copied/similar to the
900// RetainRelease checker. We might want to factor this out.
901//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000902
Anna Zaks4fb54872012-02-11 21:02:35 +0000903// Stop tracking symbols when a value escapes as a result of checkBind.
904// A value escapes in three possible cases:
905// (1) we are binding to something that is not a memory region.
906// (2) we are binding to a memregion that does not have stack storage
907// (3) we are binding to a memregion with stack storage that the store
908// does not understand.
909void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
910 CheckerContext &C) const {
911 // Are we storing to something that causes the value to "escape"?
912 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000913 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000914
Anna Zaks4fb54872012-02-11 21:02:35 +0000915 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
916 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000917
Anna Zaks4fb54872012-02-11 21:02:35 +0000918 if (!escapes) {
919 // To test (3), generate a new state with the binding added. If it is
920 // the same state, then it escapes (since the store cannot represent
921 // the binding).
922 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000923 }
924 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000925
926 // If our store can represent the binding and we aren't storing to something
927 // that doesn't have local storage then just return and have the simulation
928 // state continue as is.
929 if (!escapes)
930 return;
931
932 // Otherwise, find all symbols referenced by 'val' that we are tracking
933 // and stop tracking them.
934 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
935 C.addTransition(state);
936}
937
938// If a symbolic region is assumed to NULL (or another constant), stop tracking
939// it - assuming that allocation failed on this path.
940ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
941 SVal Cond,
942 bool Assumption) const {
943 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +0000944 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
945 // If the symbol is assumed to NULL or another constant, this will
946 // return an APSInt*.
947 if (state->getSymVal(I.getKey()))
948 state = state->remove<RegionState>(I.getKey());
949 }
950
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000951 // Realloc returns 0 when reallocation fails, which means that we should
952 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000953 ReallocMap RP = state->get<ReallocPairs>();
954 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000955 // If the symbol is assumed to NULL or another constant, this will
956 // return an APSInt*.
957 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +0000958 SymbolRef ReallocSym = I.getData().ReallocatedSym;
959 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000960 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +0000961 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
962 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000963 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000964 }
965 state = state->remove<ReallocPairs>(I.getKey());
966 }
967 }
968
Anna Zaks4fb54872012-02-11 21:02:35 +0000969 return state;
970}
971
Anna Zaks66c40402012-02-14 21:55:24 +0000972// Check if the function is not known to us. So, for example, we could
973// conservatively assume it can free/reallocate it's pointer arguments.
974// (We assume that the pointers cannot escape through calls to system
975// functions not handled by this checker.)
976bool MallocChecker::hasUnknownBehavior(const FunctionDecl *FD,
977 ProgramStateRef State) const {
978 ASTContext &ASTC = State->getStateManager().getContext();
979
980 // If it's one of the allocation functions we can reason about, we model it's
981 // behavior explicitly.
982 if (isMemFunction(FD, ASTC)) {
983 return false;
984 }
985
986 // If it's a system call, we know it does not free the memory.
987 SourceManager &SM = ASTC.getSourceManager();
988 if (SM.isInSystemHeader(FD->getLocation())) {
989 return false;
990 }
991
992 // Otherwise, assume that the function can free memory.
993 return true;
994}
995
Anna Zaks4fb54872012-02-11 21:02:35 +0000996// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
997// escapes, when we are tracking p), do not track the symbol as we cannot reason
998// about it anymore.
999ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001000MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001001 const StoreManager::InvalidatedSymbols *invalidated,
1002 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001003 ArrayRef<const MemRegion *> Regions,
1004 const CallOrObjCMessage *Call) const {
Anna Zaks4fb54872012-02-11 21:02:35 +00001005 if (!invalidated)
Anna Zaks66c40402012-02-14 21:55:24 +00001006 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001007 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001008
1009 const FunctionDecl *FD = (Call ? dyn_cast<FunctionDecl>(Call->getDecl()) : 0);
1010
1011 // If it's a call which might free or reallocate memory, we assume that all
1012 // regions (explicit and implicit) escaped. Otherwise, whitelist explicit
1013 // pointers; we still can track them.
1014 if (!(FD && hasUnknownBehavior(FD, State))) {
1015 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1016 E = ExplicitRegions.end(); I != E; ++I) {
1017 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1018 WhitelistedSymbols.insert(R->getSymbol());
1019 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001020 }
1021
1022 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1023 E = invalidated->end(); I!=E; ++I) {
1024 SymbolRef sym = *I;
1025 if (WhitelistedSymbols.count(sym))
1026 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001027 // The symbol escaped.
1028 if (const RefState *RS = State->get<RegionState>(sym))
1029 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001030 }
Anna Zaks66c40402012-02-14 21:55:24 +00001031 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001032}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001033
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001034PathDiagnosticPiece *
1035MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1036 const ExplodedNode *PrevN,
1037 BugReporterContext &BRC,
1038 BugReport &BR) {
1039 const RefState *RS = N->getState()->get<RegionState>(Sym);
1040 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1041 if (!RS && !RSPrev)
1042 return 0;
1043
1044 // We expect the interesting locations be StmtPoints corresponding to call
1045 // expressions. We do not support indirect function calls as of now.
1046 const CallExpr *CE = 0;
1047 if (isa<StmtPoint>(N->getLocation()))
1048 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
1049 if (!CE)
1050 return 0;
1051 const FunctionDecl *funDecl = CE->getDirectCallee();
1052 if (!funDecl)
1053 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001054
1055 // Find out if this is an interesting point and what is the kind.
1056 const char *Msg = 0;
1057 if (isAllocated(RS, RSPrev))
1058 Msg = "Memory is allocated here";
1059 else if (isReleased(RS, RSPrev))
1060 Msg = "Memory is released here";
1061 if (!Msg)
1062 return 0;
1063
1064 // Generate the extra diagnostic.
1065 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
1066 N->getLocationContext());
1067 return new PathDiagnosticEventPiece(Pos, Msg);
1068}
1069
1070
Anna Zaks231361a2012-02-08 23:16:52 +00001071#define REGISTER_CHECKER(name) \
1072void ento::register##name(CheckerManager &mgr) {\
1073 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001074}
Anna Zaks231361a2012-02-08 23:16:52 +00001075
1076REGISTER_CHECKER(MallocPessimistic)
1077REGISTER_CHECKER(MallocOptimistic)