blob: 88a0613a78f56f12cdc28c8e76dec8d153138f42 [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 {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000268 if (!FD)
269 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000270 IdentifierInfo *FunI = FD->getIdentifier();
271 if (!FunI)
272 return false;
273
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000274 initIdentifierInfo(C);
275
Anna Zaks66c40402012-02-14 21:55:24 +0000276 // TODO: Add more here : ex: reallocf!
Anna Zaks40add292012-02-15 00:11:25 +0000277 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
278 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc)
Anna Zaks66c40402012-02-14 21:55:24 +0000279 return true;
280
281 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
282 FD->specific_attr_begin<OwnershipAttr>() !=
283 FD->specific_attr_end<OwnershipAttr>())
284 return true;
285
286
287 return false;
288}
289
Anna Zaksb319e022012-02-08 20:13:28 +0000290void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
291 const FunctionDecl *FD = C.getCalleeDecl(CE);
292 if (!FD)
293 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000294
Anna Zaksb16ce452012-02-15 00:11:22 +0000295 initIdentifierInfo(C.getASTContext());
296 IdentifierInfo *FunI = FD->getIdentifier();
297 if (!FunI)
298 return;
299
300 if (FunI == II_malloc || FunI == II_valloc) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000301 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000302 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000303 } else if (FunI == II_realloc) {
Anna Zaks40add292012-02-15 00:11:25 +0000304 ReallocMem(C, CE, false);
305 return;
306 } else if (FunI == II_reallocf) {
307 ReallocMem(C, CE, true);
Anna Zaksb319e022012-02-08 20:13:28 +0000308 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000309 } else if (FunI == II_calloc) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000310 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000311 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000312 }else if (FunI == II_free) {
Anna Zaksb319e022012-02-08 20:13:28 +0000313 FreeMem(C, CE);
314 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000315 }
316
Anna Zaks91c2a112012-02-08 23:16:56 +0000317 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000318 // Check all the attributes, if there are any.
319 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000320 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000321 for (specific_attr_iterator<OwnershipAttr>
322 i = FD->specific_attr_begin<OwnershipAttr>(),
323 e = FD->specific_attr_end<OwnershipAttr>();
324 i != e; ++i) {
325 switch ((*i)->getOwnKind()) {
326 case OwnershipAttr::Returns: {
327 MallocMemReturnsAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000328 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000329 }
330 case OwnershipAttr::Takes:
331 case OwnershipAttr::Holds: {
332 FreeMemAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000333 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000334 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000335 }
336 }
337 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000338}
339
340void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000341 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000342 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000343 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000344}
345
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000346void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
347 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000348 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000349 return;
350
Sean Huntcf807c42010-08-18 23:23:40 +0000351 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000352 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000353 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000354 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000355 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000356 return;
357 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000358 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000359 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000360 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000361}
362
Anna Zaksb319e022012-02-08 20:13:28 +0000363ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000364 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000365 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000366 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000367 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000368
Anna Zaksb319e022012-02-08 20:13:28 +0000369 // Get the return value.
370 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000371
Anna Zaksb16ce452012-02-15 00:11:22 +0000372 // We expect the malloc functions to return a pointer.
373 if (!isa<Loc>(retVal))
374 return 0;
375
Jordy Rose32f26562010-07-04 00:00:41 +0000376 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000377 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000378
Jordy Rose32f26562010-07-04 00:00:41 +0000379 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000380 const SymbolicRegion *R =
381 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
382 if (!R || !isa<DefinedOrUnknownSVal>(Size))
383 return 0;
384
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000385 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000386 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000387 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000388 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000389
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000390 state = state->assume(extentMatchesSize, true);
391 assert(state);
392
393 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000394 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000395
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000396 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000397 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000398}
399
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000400void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000401 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000402
403 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000404 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000405}
406
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000407void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000408 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000409 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000410 return;
411
Sean Huntcf807c42010-08-18 23:23:40 +0000412 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
413 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000414 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000415 FreeMemAux(C, CE, C.getState(), *I,
416 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000417 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000418 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000419 }
420}
421
Ted Kremenek8bef8232012-01-26 21:29:00 +0000422ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000423 const CallExpr *CE,
424 ProgramStateRef state,
425 unsigned Num,
426 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000427 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000428 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000429 if (!isa<DefinedOrUnknownSVal>(ArgVal))
430 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000431 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
432
433 // Check for null dereferences.
434 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000435 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000436
Anna Zaksb276bd92012-02-14 00:26:13 +0000437 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000438 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000439 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000440 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000441 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000442
Jordy Rose43859f62010-06-07 19:32:37 +0000443 // Unknown values could easily be okay
444 // Undefined values are handled elsewhere
445 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000446 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000447
Jordy Rose43859f62010-06-07 19:32:37 +0000448 const MemRegion *R = ArgVal.getAsRegion();
449
450 // Nonlocs can't be freed, of course.
451 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
452 if (!R) {
453 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000454 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000455 }
456
457 R = R->StripCasts();
458
459 // Blocks might show up as heap data, but should not be free()d
460 if (isa<BlockDataRegion>(R)) {
461 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000462 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000463 }
464
465 const MemSpaceRegion *MS = R->getMemorySpace();
466
467 // Parameters, locals, statics, and globals shouldn't be freed.
468 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
469 // FIXME: at the time this code was written, malloc() regions were
470 // represented by conjured symbols, which are all in UnknownSpaceRegion.
471 // This means that there isn't actually anything from HeapSpaceRegion
472 // that should be freed, even though we allow it here.
473 // Of course, free() can work on memory allocated outside the current
474 // function, so UnknownSpaceRegion is always a possibility.
475 // False negatives are better than false positives.
476
477 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000478 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000479 }
480
481 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
482 // Various cases could lead to non-symbol values here.
483 // For now, ignore them.
484 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000485 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000486
487 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000488 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000489
490 // If the symbol has not been tracked, return. This is possible when free() is
491 // called on a pointer that does not get its pointee directly from malloc().
492 // Full support of this requires inter-procedural analysis.
493 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000494 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000495
496 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000497 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000498 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000499 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000500 BT_DoubleFree.reset(
501 new BuiltinBug("Double free",
502 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000503 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000504 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000505 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000506 C.EmitReport(R);
507 }
Anna Zaksb319e022012-02-08 20:13:28 +0000508 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000509 }
510
511 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000512 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000513 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
514 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000515}
516
Ted Kremenek9c378f72011-08-12 23:37:29 +0000517bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000518 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
519 os << "an integer (" << IntVal->getValue() << ")";
520 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
521 os << "a constant address (" << ConstAddr->getValue() << ")";
522 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000523 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000524 else
525 return false;
526
527 return true;
528}
529
Ted Kremenek9c378f72011-08-12 23:37:29 +0000530bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000531 const MemRegion *MR) {
532 switch (MR->getKind()) {
533 case MemRegion::FunctionTextRegionKind: {
534 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
535 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000536 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000537 else
538 os << "the address of a function";
539 return true;
540 }
541 case MemRegion::BlockTextRegionKind:
542 os << "block text";
543 return true;
544 case MemRegion::BlockDataRegionKind:
545 // FIXME: where the block came from?
546 os << "a block";
547 return true;
548 default: {
549 const MemSpaceRegion *MS = MR->getMemorySpace();
550
Anna Zakseb31a762012-01-04 23:54:01 +0000551 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000552 const VarRegion *VR = dyn_cast<VarRegion>(MR);
553 const VarDecl *VD;
554 if (VR)
555 VD = VR->getDecl();
556 else
557 VD = NULL;
558
559 if (VD)
560 os << "the address of the local variable '" << VD->getName() << "'";
561 else
562 os << "the address of a local stack variable";
563 return true;
564 }
Anna Zakseb31a762012-01-04 23:54:01 +0000565
566 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000567 const VarRegion *VR = dyn_cast<VarRegion>(MR);
568 const VarDecl *VD;
569 if (VR)
570 VD = VR->getDecl();
571 else
572 VD = NULL;
573
574 if (VD)
575 os << "the address of the parameter '" << VD->getName() << "'";
576 else
577 os << "the address of a parameter";
578 return true;
579 }
Anna Zakseb31a762012-01-04 23:54:01 +0000580
581 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000582 const VarRegion *VR = dyn_cast<VarRegion>(MR);
583 const VarDecl *VD;
584 if (VR)
585 VD = VR->getDecl();
586 else
587 VD = NULL;
588
589 if (VD) {
590 if (VD->isStaticLocal())
591 os << "the address of the static variable '" << VD->getName() << "'";
592 else
593 os << "the address of the global variable '" << VD->getName() << "'";
594 } else
595 os << "the address of a global variable";
596 return true;
597 }
Anna Zakseb31a762012-01-04 23:54:01 +0000598
599 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000600 }
601 }
602}
603
604void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000605 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000606 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000607 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000608 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000609
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000610 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000611 llvm::raw_svector_ostream os(buf);
612
613 const MemRegion *MR = ArgVal.getAsRegion();
614 if (MR) {
615 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
616 MR = ER->getSuperRegion();
617
618 // Special case for alloca()
619 if (isa<AllocaRegion>(MR))
620 os << "Argument to free() was allocated by alloca(), not malloc()";
621 else {
622 os << "Argument to free() is ";
623 if (SummarizeRegion(os, MR))
624 os << ", which is not memory allocated by malloc()";
625 else
626 os << "not memory allocated by malloc()";
627 }
628 } else {
629 os << "Argument to free() is ";
630 if (SummarizeValue(os, ArgVal))
631 os << ", which is not memory allocated by malloc()";
632 else
633 os << "not memory allocated by malloc()";
634 }
635
Anna Zakse172e8b2011-08-17 23:00:25 +0000636 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000637 R->addRange(range);
638 C.EmitReport(R);
639 }
640}
641
Anna Zaks40add292012-02-15 00:11:25 +0000642void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE,
643 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000644 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000645 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000646 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000647 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
648 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
649 return;
650 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000651
Ted Kremenek846eabd2010-12-01 21:28:31 +0000652 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000653
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000654 DefinedOrUnknownSVal PtrEQ =
655 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000656
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000657 // Get the size argument. If there is no size arg then give up.
658 const Expr *Arg1 = CE->getArg(1);
659 if (!Arg1)
660 return;
661
662 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000663 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
664 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
665 return;
666 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000667
668 // Compare the size argument to 0.
669 DefinedOrUnknownSVal SizeZero =
670 svalBuilder.evalEQ(state, Arg1Val,
671 svalBuilder.makeIntValWithPtrWidth(0, false));
672
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000673 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
674 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
675 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
676 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
677 // We only assume exceptional states if they are definitely true; if the
678 // state is under-constrained, assume regular realloc behavior.
679 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
680 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
681
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000682 // If the ptr is NULL and the size is not 0, the call is equivalent to
683 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000684 if ( PrtIsNull && !SizeIsZero) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000685 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000686 UndefinedVal(), StatePtrIsNull);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000687 C.addTransition(stateMalloc);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000688 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000689 }
690
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000691 if (PrtIsNull && SizeIsZero)
692 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000693
Anna Zaks30838b92012-02-13 20:57:07 +0000694 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000695 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000696 SymbolRef FromPtr = arg0Val.getAsSymbol();
697 SVal RetVal = state->getSVal(CE, LCtx);
698 SymbolRef ToPtr = RetVal.getAsSymbol();
699 if (!FromPtr || !ToPtr)
700 return;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000701
702 // If the size is 0, free the memory.
703 if (SizeIsZero)
704 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000705 // The semantics of the return value are:
706 // If size was equal to 0, either NULL or a pointer suitable to be passed
707 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000708 stateFree = stateFree->set<ReallocPairs>(ToPtr,
709 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000710 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks30838b92012-02-13 20:57:07 +0000711 C.addTransition(stateFree);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000712 return;
713 }
714
715 // Default behavior.
716 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
717 // FIXME: We should copy the content of the original buffer.
718 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
719 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000720 if (!stateRealloc)
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000721 return;
Anna Zaks40add292012-02-15 00:11:25 +0000722 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
723 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000724 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000725 C.addTransition(stateRealloc);
726 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000727 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000728}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000729
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000730void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000731 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000732 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000733 const LocationContext *LCtx = C.getLocationContext();
734 SVal count = state->getSVal(CE->getArg(0), LCtx);
735 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000736 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
737 svalBuilder.getContext().getSizeType());
738 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000739
Anna Zaks0bd6b112011-10-26 21:06:34 +0000740 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000741}
742
Anna Zaksda046772012-02-11 21:02:40 +0000743void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
744 CheckerContext &C) const {
745 assert(N);
746 if (!BT_Leak) {
747 BT_Leak.reset(new BuiltinBug("Memory leak",
748 "Allocated memory never released. Potential memory leak."));
749 // Leaks should not be reported if they are post-dominated by a sink:
750 // (1) Sinks are higher importance bugs.
751 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
752 // with __noreturn functions such as assert() or exit(). We choose not
753 // to report leaks on such paths.
754 BT_Leak->setSuppressOnSink(true);
755 }
756
757 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
758 R->addVisitor(new MallocBugVisitor(Sym));
759 C.EmitReport(R);
760}
761
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000762void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
763 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000764{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000765 if (!SymReaper.hasDeadSymbols())
766 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000767
Ted Kremenek8bef8232012-01-26 21:29:00 +0000768 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000769 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000770 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000771
Ted Kremenek217470e2011-07-28 23:07:51 +0000772 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000773 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000774 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
775 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000776 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000777 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000778 Errors.push_back(I->first);
779 }
Jordy Rose90760142010-08-18 04:33:47 +0000780 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000781 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000782
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000783 }
784 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000785
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000786 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000787 ReallocMap RP = state->get<ReallocPairs>();
788 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
789 if (SymReaper.isDead(I->first) ||
790 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000791 state = state->remove<ReallocPairs>(I->first);
792 }
793 }
794
Anna Zaks0bd6b112011-10-26 21:06:34 +0000795 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000796
Ted Kremenek217470e2011-07-28 23:07:51 +0000797 if (N && generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000798 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000799 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
800 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000801 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000802 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000803}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000804
Anna Zaksda046772012-02-11 21:02:40 +0000805void MallocChecker::checkEndPath(CheckerContext &C) const {
806 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000807 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000808
Jordy Rose09cef092010-08-18 04:26:59 +0000809 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000810 RefState RS = I->second;
811 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000812 ExplodedNode *N = C.addTransition(state);
813 if (N)
814 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000815 }
816 }
817}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000818
Anna Zaks91c2a112012-02-08 23:16:56 +0000819bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
820 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000821 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000822 const RefState *RS = state->get<RegionState>(Sym);
823 if (!RS)
824 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000825
Anna Zaks91c2a112012-02-08 23:16:56 +0000826 if (RS->isAllocated()) {
827 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
828 C.addTransition(state);
829 return true;
830 }
831 return false;
832}
833
Anna Zaks66c40402012-02-14 21:55:24 +0000834void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
835 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
836 return;
837
838 // Check use after free, when a freed pointer is passed to a call.
839 ProgramStateRef State = C.getState();
840 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
841 E = CE->arg_end(); I != E; ++I) {
842 const Expr *A = *I;
843 if (A->getType().getTypePtr()->isAnyPointerType()) {
844 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
845 if (!Sym)
846 continue;
847 if (checkUseAfterFree(Sym, C, A))
848 return;
849 }
850 }
851}
852
Anna Zaks91c2a112012-02-08 23:16:56 +0000853void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
854 const Expr *E = S->getRetValue();
855 if (!E)
856 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000857
858 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000859 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000860 if (!Sym)
861 return;
862
Anna Zaks0860cd02012-02-11 21:44:39 +0000863 // Check if we are returning freed memory.
Anna Zaks15d0ae12012-02-11 23:46:36 +0000864 if (checkUseAfterFree(Sym, C, S))
865 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000866
867 // Check if the symbol is escaping.
Anna Zaks91c2a112012-02-08 23:16:56 +0000868 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000869}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000870
Anna Zaks91c2a112012-02-08 23:16:56 +0000871bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
872 const Stmt *S) const {
873 assert(Sym);
874 const RefState *RS = C.getState()->get<RegionState>(Sym);
875 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000876 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000877 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000878 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000879 "after it is freed."));
880
881 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
882 if (S)
883 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000884 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000885 C.EmitReport(R);
886 return true;
887 }
888 }
889 return false;
890}
891
Zhongxing Xuc8023782010-03-10 04:58:55 +0000892// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000893void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
894 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000895 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000896 if (Sym)
897 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000898}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000899
Anna Zaks4fb54872012-02-11 21:02:35 +0000900//===----------------------------------------------------------------------===//
901// Check various ways a symbol can be invalidated.
902// TODO: This logic (the next 3 functions) is copied/similar to the
903// RetainRelease checker. We might want to factor this out.
904//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000905
Anna Zaks4fb54872012-02-11 21:02:35 +0000906// Stop tracking symbols when a value escapes as a result of checkBind.
907// A value escapes in three possible cases:
908// (1) we are binding to something that is not a memory region.
909// (2) we are binding to a memregion that does not have stack storage
910// (3) we are binding to a memregion with stack storage that the store
911// does not understand.
912void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
913 CheckerContext &C) const {
914 // Are we storing to something that causes the value to "escape"?
915 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000916 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000917
Anna Zaks4fb54872012-02-11 21:02:35 +0000918 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
919 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000920
Anna Zaks4fb54872012-02-11 21:02:35 +0000921 if (!escapes) {
922 // To test (3), generate a new state with the binding added. If it is
923 // the same state, then it escapes (since the store cannot represent
924 // the binding).
925 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000926 }
927 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000928
929 // If our store can represent the binding and we aren't storing to something
930 // that doesn't have local storage then just return and have the simulation
931 // state continue as is.
932 if (!escapes)
933 return;
934
935 // Otherwise, find all symbols referenced by 'val' that we are tracking
936 // and stop tracking them.
937 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
938 C.addTransition(state);
939}
940
941// If a symbolic region is assumed to NULL (or another constant), stop tracking
942// it - assuming that allocation failed on this path.
943ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
944 SVal Cond,
945 bool Assumption) const {
946 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +0000947 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
948 // If the symbol is assumed to NULL or another constant, this will
949 // return an APSInt*.
950 if (state->getSymVal(I.getKey()))
951 state = state->remove<RegionState>(I.getKey());
952 }
953
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000954 // Realloc returns 0 when reallocation fails, which means that we should
955 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000956 ReallocMap RP = state->get<ReallocPairs>();
957 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000958 // If the symbol is assumed to NULL or another constant, this will
959 // return an APSInt*.
960 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +0000961 SymbolRef ReallocSym = I.getData().ReallocatedSym;
962 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000963 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +0000964 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
965 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000966 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000967 }
968 state = state->remove<ReallocPairs>(I.getKey());
969 }
970 }
971
Anna Zaks4fb54872012-02-11 21:02:35 +0000972 return state;
973}
974
Anna Zaks66c40402012-02-14 21:55:24 +0000975// Check if the function is not known to us. So, for example, we could
976// conservatively assume it can free/reallocate it's pointer arguments.
977// (We assume that the pointers cannot escape through calls to system
978// functions not handled by this checker.)
979bool MallocChecker::hasUnknownBehavior(const FunctionDecl *FD,
980 ProgramStateRef State) const {
981 ASTContext &ASTC = State->getStateManager().getContext();
982
983 // If it's one of the allocation functions we can reason about, we model it's
984 // behavior explicitly.
985 if (isMemFunction(FD, ASTC)) {
986 return false;
987 }
988
989 // If it's a system call, we know it does not free the memory.
990 SourceManager &SM = ASTC.getSourceManager();
991 if (SM.isInSystemHeader(FD->getLocation())) {
992 return false;
993 }
994
995 // Otherwise, assume that the function can free memory.
996 return true;
997}
998
Anna Zaks4fb54872012-02-11 21:02:35 +0000999// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1000// escapes, when we are tracking p), do not track the symbol as we cannot reason
1001// about it anymore.
1002ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001003MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001004 const StoreManager::InvalidatedSymbols *invalidated,
1005 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001006 ArrayRef<const MemRegion *> Regions,
1007 const CallOrObjCMessage *Call) const {
Anna Zaks4fb54872012-02-11 21:02:35 +00001008 if (!invalidated)
Anna Zaks66c40402012-02-14 21:55:24 +00001009 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001010 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001011
Anna Zaks1d6cc6a2012-02-15 02:12:00 +00001012 const FunctionDecl *FD = (Call ?
1013 dyn_cast_or_null<FunctionDecl>(Call->getDecl()) :0);
Anna Zaks66c40402012-02-14 21:55:24 +00001014
1015 // If it's a call which might free or reallocate memory, we assume that all
1016 // regions (explicit and implicit) escaped. Otherwise, whitelist explicit
1017 // pointers; we still can track them.
1018 if (!(FD && hasUnknownBehavior(FD, State))) {
1019 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1020 E = ExplicitRegions.end(); I != E; ++I) {
1021 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1022 WhitelistedSymbols.insert(R->getSymbol());
1023 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001024 }
1025
1026 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1027 E = invalidated->end(); I!=E; ++I) {
1028 SymbolRef sym = *I;
1029 if (WhitelistedSymbols.count(sym))
1030 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001031 // The symbol escaped.
1032 if (const RefState *RS = State->get<RegionState>(sym))
1033 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001034 }
Anna Zaks66c40402012-02-14 21:55:24 +00001035 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001036}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001037
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001038PathDiagnosticPiece *
1039MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1040 const ExplodedNode *PrevN,
1041 BugReporterContext &BRC,
1042 BugReport &BR) {
1043 const RefState *RS = N->getState()->get<RegionState>(Sym);
1044 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1045 if (!RS && !RSPrev)
1046 return 0;
1047
1048 // We expect the interesting locations be StmtPoints corresponding to call
1049 // expressions. We do not support indirect function calls as of now.
1050 const CallExpr *CE = 0;
1051 if (isa<StmtPoint>(N->getLocation()))
1052 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
1053 if (!CE)
1054 return 0;
1055 const FunctionDecl *funDecl = CE->getDirectCallee();
1056 if (!funDecl)
1057 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001058
1059 // Find out if this is an interesting point and what is the kind.
1060 const char *Msg = 0;
1061 if (isAllocated(RS, RSPrev))
1062 Msg = "Memory is allocated here";
1063 else if (isReleased(RS, RSPrev))
1064 Msg = "Memory is released here";
1065 if (!Msg)
1066 return 0;
1067
1068 // Generate the extra diagnostic.
1069 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
1070 N->getLocationContext());
1071 return new PathDiagnosticEventPiece(Pos, Msg);
1072}
1073
1074
Anna Zaks231361a2012-02-08 23:16:52 +00001075#define REGISTER_CHECKER(name) \
1076void ento::register##name(CheckerManager &mgr) {\
1077 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001078}
Anna Zaks231361a2012-02-08 23:16:52 +00001079
1080REGISTER_CHECKER(MallocPessimistic)
1081REGISTER_CHECKER(MallocOptimistic)