blob: 1191cf8d902a9140bfa9cc0ab1d1d2faa1976bf0 [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 Zaksb319e022012-02-08 20:13:28 +000070class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000071 check::EndPath,
72 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000073 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000074 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000075 check::Location,
76 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000077 eval::Assume,
78 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000079{
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000080 mutable OwningPtr<BuiltinBug> BT_DoubleFree;
81 mutable OwningPtr<BuiltinBug> BT_Leak;
82 mutable OwningPtr<BuiltinBug> BT_UseFree;
83 mutable OwningPtr<BuiltinBug> BT_UseRelinquished;
84 mutable OwningPtr<BuiltinBug> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +000085 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
86 *II_valloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000087
88public:
Anna Zaksb16ce452012-02-15 00:11:22 +000089 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
90 II_valloc(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +000091
92 /// In pessimistic mode, the checker assumes that it does not know which
93 /// functions might free the memory.
94 struct ChecksFilter {
95 DefaultBool CMallocPessimistic;
96 DefaultBool CMallocOptimistic;
97 };
98
99 ChecksFilter Filter;
100
Anna Zaks66c40402012-02-14 21:55:24 +0000101 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000102 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000103 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000104 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000105 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000106 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000107 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000108 void checkLocation(SVal l, bool isLoad, const Stmt *S,
109 CheckerContext &C) const;
110 void checkBind(SVal location, SVal val, const Stmt*S,
111 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000112 ProgramStateRef
113 checkRegionChanges(ProgramStateRef state,
114 const StoreManager::InvalidatedSymbols *invalidated,
115 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000116 ArrayRef<const MemRegion *> Regions,
117 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000118 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
119 return true;
120 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000121
Zhongxing Xu7b760962009-11-13 07:25:27 +0000122private:
Anna Zaks66c40402012-02-14 21:55:24 +0000123 void initIdentifierInfo(ASTContext &C) const;
124
125 /// Check if this is one of the functions which can allocate/reallocate memory
126 /// pointed to by one of its arguments.
127 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
128
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000129 static void MallocMem(CheckerContext &C, const CallExpr *CE);
130 static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
131 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000132 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000133 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000134 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000135 return MallocMemAux(C, CE,
136 state->getSVal(SizeEx, C.getLocationContext()),
137 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000138 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000139 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000140 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000141 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000142
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000143 void FreeMem(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose2a479922010-08-12 08:54:03 +0000144 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000145 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000146 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
147 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000148 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000149
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000150 void ReallocMem(CheckerContext &C, const CallExpr *CE) const;
151 static void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000152
Anna Zaks91c2a112012-02-08 23:16:56 +0000153 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
154 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
155 const Stmt *S = 0) const;
156
Anna Zaks66c40402012-02-14 21:55:24 +0000157 /// Check if the function is not known to us. So, for example, we could
158 /// conservatively assume it can free/reallocate it's pointer arguments.
159 bool hasUnknownBehavior(const FunctionDecl *FD, ProgramStateRef State) const;
160
Ted Kremenek9c378f72011-08-12 23:37:29 +0000161 static bool SummarizeValue(raw_ostream &os, SVal V);
162 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000163 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000164
Anna Zaksda046772012-02-11 21:02:40 +0000165 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
166
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000167 /// The bug visitor which allows us to print extra diagnostics along the
168 /// BugReport path. For example, showing the allocation site of the leaked
169 /// region.
170 class MallocBugVisitor : public BugReporterVisitor {
171 protected:
172 // The allocated region symbol tracked by the main analysis.
173 SymbolRef Sym;
174
175 public:
176 MallocBugVisitor(SymbolRef S) : Sym(S) {}
177 virtual ~MallocBugVisitor() {}
178
179 void Profile(llvm::FoldingSetNodeID &ID) const {
180 static int X = 0;
181 ID.AddPointer(&X);
182 ID.AddPointer(Sym);
183 }
184
185 inline bool isAllocated(const RefState *S, const RefState *SPrev) {
186 // Did not track -> allocated. Other state (released) -> allocated.
187 return ((S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
188 }
189
190 inline bool isReleased(const RefState *S, const RefState *SPrev) {
191 // Did not track -> released. Other state (allocated) -> released.
192 return ((S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
193 }
194
195 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
196 const ExplodedNode *PrevN,
197 BugReporterContext &BRC,
198 BugReport &BR);
199 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000200};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000201} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000202
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000203typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000204typedef llvm::ImmutableMap<SymbolRef, SymbolRef> SymRefToSymRefTy;
205class RegionState {};
206class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000207namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000208namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000209 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000210 struct ProgramStateTrait<RegionState>
211 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000212 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000213 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000214
215 template <>
216 struct ProgramStateTrait<ReallocPairs>
217 : public ProgramStatePartialTrait<SymRefToSymRefTy> {
218 static void *GDMIndex() { static int x; return &x; }
219 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000220}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000221}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000222
Anna Zaks4fb54872012-02-11 21:02:35 +0000223namespace {
224class StopTrackingCallback : public SymbolVisitor {
225 ProgramStateRef state;
226public:
227 StopTrackingCallback(ProgramStateRef st) : state(st) {}
228 ProgramStateRef getState() const { return state; }
229
230 bool VisitSymbol(SymbolRef sym) {
231 state = state->remove<RegionState>(sym);
232 return true;
233 }
234};
235} // end anonymous namespace
236
Anna Zaks66c40402012-02-14 21:55:24 +0000237void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000238 if (!II_malloc)
239 II_malloc = &Ctx.Idents.get("malloc");
240 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000241 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000242 if (!II_realloc)
243 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000244 if (!II_calloc)
245 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000246 if (!II_valloc)
247 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000248}
249
Anna Zaks66c40402012-02-14 21:55:24 +0000250bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
251 initIdentifierInfo(C);
252 IdentifierInfo *FunI = FD->getIdentifier();
253 if (!FunI)
254 return false;
255
256 // TODO: Add more here : ex: reallocf!
257 if (FunI == II_malloc || FunI == II_free ||
Anna Zaksb16ce452012-02-15 00:11:22 +0000258 FunI == II_realloc || FunI == II_calloc || FunI == II_valloc)
Anna Zaks66c40402012-02-14 21:55:24 +0000259 return true;
260
261 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
262 FD->specific_attr_begin<OwnershipAttr>() !=
263 FD->specific_attr_end<OwnershipAttr>())
264 return true;
265
266
267 return false;
268}
269
Anna Zaksb319e022012-02-08 20:13:28 +0000270void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
271 const FunctionDecl *FD = C.getCalleeDecl(CE);
272 if (!FD)
273 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000274
Anna Zaksb16ce452012-02-15 00:11:22 +0000275 initIdentifierInfo(C.getASTContext());
276 IdentifierInfo *FunI = FD->getIdentifier();
277 if (!FunI)
278 return;
279
280 if (FunI == II_malloc || FunI == II_valloc) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000281 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000282 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000283 } else if (FunI == II_realloc) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000284 ReallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000285 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000286 } else if (FunI == II_calloc) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000287 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000288 return;
Anna Zaksb16ce452012-02-15 00:11:22 +0000289 }else if (FunI == II_free) {
Anna Zaksb319e022012-02-08 20:13:28 +0000290 FreeMem(C, CE);
291 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000292 }
293
Anna Zaks91c2a112012-02-08 23:16:56 +0000294 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000295 // Check all the attributes, if there are any.
296 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000297 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000298 for (specific_attr_iterator<OwnershipAttr>
299 i = FD->specific_attr_begin<OwnershipAttr>(),
300 e = FD->specific_attr_end<OwnershipAttr>();
301 i != e; ++i) {
302 switch ((*i)->getOwnKind()) {
303 case OwnershipAttr::Returns: {
304 MallocMemReturnsAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000305 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000306 }
307 case OwnershipAttr::Takes:
308 case OwnershipAttr::Holds: {
309 FreeMemAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000310 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000311 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000312 }
313 }
314 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000315}
316
317void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000318 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000319 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000320 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000321}
322
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000323void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
324 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000325 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000326 return;
327
Sean Huntcf807c42010-08-18 23:23:40 +0000328 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000329 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000330 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000331 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000332 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000333 return;
334 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000335 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000336 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000337 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000338}
339
Anna Zaksb319e022012-02-08 20:13:28 +0000340ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000341 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000342 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000343 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000344 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000345
Anna Zaksb319e022012-02-08 20:13:28 +0000346 // Get the return value.
347 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000348
Anna Zaksb16ce452012-02-15 00:11:22 +0000349 // We expect the malloc functions to return a pointer.
350 if (!isa<Loc>(retVal))
351 return 0;
352
Jordy Rose32f26562010-07-04 00:00:41 +0000353 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000354 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000355
Jordy Rose32f26562010-07-04 00:00:41 +0000356 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000357 const SymbolicRegion *R =
358 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
359 if (!R || !isa<DefinedOrUnknownSVal>(Size))
360 return 0;
361
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000362 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000363 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000364 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000365 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000366
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000367 state = state->assume(extentMatchesSize, true);
368 assert(state);
369
370 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000371 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000372
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000373 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000374 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000375}
376
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000377void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000378 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000379
380 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000381 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000382}
383
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000384void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000385 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000386 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000387 return;
388
Sean Huntcf807c42010-08-18 23:23:40 +0000389 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
390 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000391 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000392 FreeMemAux(C, CE, C.getState(), *I,
393 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000394 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000395 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000396 }
397}
398
Ted Kremenek8bef8232012-01-26 21:29:00 +0000399ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000400 const CallExpr *CE,
401 ProgramStateRef state,
402 unsigned Num,
403 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000404 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000405 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000406 if (!isa<DefinedOrUnknownSVal>(ArgVal))
407 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000408 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
409
410 // Check for null dereferences.
411 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000412 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000413
Anna Zaksb276bd92012-02-14 00:26:13 +0000414 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000415 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000416 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000417 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000418 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000419
Jordy Rose43859f62010-06-07 19:32:37 +0000420 // Unknown values could easily be okay
421 // Undefined values are handled elsewhere
422 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000423 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000424
Jordy Rose43859f62010-06-07 19:32:37 +0000425 const MemRegion *R = ArgVal.getAsRegion();
426
427 // Nonlocs can't be freed, of course.
428 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
429 if (!R) {
430 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000431 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000432 }
433
434 R = R->StripCasts();
435
436 // Blocks might show up as heap data, but should not be free()d
437 if (isa<BlockDataRegion>(R)) {
438 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000439 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000440 }
441
442 const MemSpaceRegion *MS = R->getMemorySpace();
443
444 // Parameters, locals, statics, and globals shouldn't be freed.
445 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
446 // FIXME: at the time this code was written, malloc() regions were
447 // represented by conjured symbols, which are all in UnknownSpaceRegion.
448 // This means that there isn't actually anything from HeapSpaceRegion
449 // that should be freed, even though we allow it here.
450 // Of course, free() can work on memory allocated outside the current
451 // function, so UnknownSpaceRegion is always a possibility.
452 // False negatives are better than false positives.
453
454 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000455 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000456 }
457
458 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
459 // Various cases could lead to non-symbol values here.
460 // For now, ignore them.
461 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000462 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000463
464 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000465 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000466
467 // If the symbol has not been tracked, return. This is possible when free() is
468 // called on a pointer that does not get its pointee directly from malloc().
469 // Full support of this requires inter-procedural analysis.
470 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000471 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000472
473 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000474 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000475 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000476 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000477 BT_DoubleFree.reset(
478 new BuiltinBug("Double free",
479 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000480 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000481 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000482 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000483 C.EmitReport(R);
484 }
Anna Zaksb319e022012-02-08 20:13:28 +0000485 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000486 }
487
488 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000489 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000490 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
491 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000492}
493
Ted Kremenek9c378f72011-08-12 23:37:29 +0000494bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000495 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
496 os << "an integer (" << IntVal->getValue() << ")";
497 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
498 os << "a constant address (" << ConstAddr->getValue() << ")";
499 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000500 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000501 else
502 return false;
503
504 return true;
505}
506
Ted Kremenek9c378f72011-08-12 23:37:29 +0000507bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000508 const MemRegion *MR) {
509 switch (MR->getKind()) {
510 case MemRegion::FunctionTextRegionKind: {
511 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
512 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000513 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000514 else
515 os << "the address of a function";
516 return true;
517 }
518 case MemRegion::BlockTextRegionKind:
519 os << "block text";
520 return true;
521 case MemRegion::BlockDataRegionKind:
522 // FIXME: where the block came from?
523 os << "a block";
524 return true;
525 default: {
526 const MemSpaceRegion *MS = MR->getMemorySpace();
527
Anna Zakseb31a762012-01-04 23:54:01 +0000528 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000529 const VarRegion *VR = dyn_cast<VarRegion>(MR);
530 const VarDecl *VD;
531 if (VR)
532 VD = VR->getDecl();
533 else
534 VD = NULL;
535
536 if (VD)
537 os << "the address of the local variable '" << VD->getName() << "'";
538 else
539 os << "the address of a local stack variable";
540 return true;
541 }
Anna Zakseb31a762012-01-04 23:54:01 +0000542
543 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000544 const VarRegion *VR = dyn_cast<VarRegion>(MR);
545 const VarDecl *VD;
546 if (VR)
547 VD = VR->getDecl();
548 else
549 VD = NULL;
550
551 if (VD)
552 os << "the address of the parameter '" << VD->getName() << "'";
553 else
554 os << "the address of a parameter";
555 return true;
556 }
Anna Zakseb31a762012-01-04 23:54:01 +0000557
558 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000559 const VarRegion *VR = dyn_cast<VarRegion>(MR);
560 const VarDecl *VD;
561 if (VR)
562 VD = VR->getDecl();
563 else
564 VD = NULL;
565
566 if (VD) {
567 if (VD->isStaticLocal())
568 os << "the address of the static variable '" << VD->getName() << "'";
569 else
570 os << "the address of the global variable '" << VD->getName() << "'";
571 } else
572 os << "the address of a global variable";
573 return true;
574 }
Anna Zakseb31a762012-01-04 23:54:01 +0000575
576 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000577 }
578 }
579}
580
581void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000582 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000583 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000584 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000585 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000586
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000587 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000588 llvm::raw_svector_ostream os(buf);
589
590 const MemRegion *MR = ArgVal.getAsRegion();
591 if (MR) {
592 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
593 MR = ER->getSuperRegion();
594
595 // Special case for alloca()
596 if (isa<AllocaRegion>(MR))
597 os << "Argument to free() was allocated by alloca(), not malloc()";
598 else {
599 os << "Argument to free() is ";
600 if (SummarizeRegion(os, MR))
601 os << ", which is not memory allocated by malloc()";
602 else
603 os << "not memory allocated by malloc()";
604 }
605 } else {
606 os << "Argument to free() is ";
607 if (SummarizeValue(os, ArgVal))
608 os << ", which is not memory allocated by malloc()";
609 else
610 os << "not memory allocated by malloc()";
611 }
612
Anna Zakse172e8b2011-08-17 23:00:25 +0000613 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000614 R->addRange(range);
615 C.EmitReport(R);
616 }
617}
618
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000619void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000620 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000621 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000622 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000623 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
624 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
625 return;
626 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000627
Ted Kremenek846eabd2010-12-01 21:28:31 +0000628 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000629
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000630 DefinedOrUnknownSVal PtrEQ =
631 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000632
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000633 // Get the size argument. If there is no size arg then give up.
634 const Expr *Arg1 = CE->getArg(1);
635 if (!Arg1)
636 return;
637
638 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000639 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
640 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
641 return;
642 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000643
644 // Compare the size argument to 0.
645 DefinedOrUnknownSVal SizeZero =
646 svalBuilder.evalEQ(state, Arg1Val,
647 svalBuilder.makeIntValWithPtrWidth(0, false));
648
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000649 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
650 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
651 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
652 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
653 // We only assume exceptional states if they are definitely true; if the
654 // state is under-constrained, assume regular realloc behavior.
655 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
656 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
657
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000658 // If the ptr is NULL and the size is not 0, the call is equivalent to
659 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000660 if ( PrtIsNull && !SizeIsZero) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000661 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000662 UndefinedVal(), StatePtrIsNull);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000663 C.addTransition(stateMalloc);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000664 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000665 }
666
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000667 if (PrtIsNull && SizeIsZero)
668 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000669
Anna Zaks30838b92012-02-13 20:57:07 +0000670 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000671 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000672 SymbolRef FromPtr = arg0Val.getAsSymbol();
673 SVal RetVal = state->getSVal(CE, LCtx);
674 SymbolRef ToPtr = RetVal.getAsSymbol();
675 if (!FromPtr || !ToPtr)
676 return;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000677
678 // If the size is 0, free the memory.
679 if (SizeIsZero)
680 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000681 // The semantics of the return value are:
682 // If size was equal to 0, either NULL or a pointer suitable to be passed
683 // to free() is returned.
Anna Zaks30838b92012-02-13 20:57:07 +0000684 stateFree = stateFree->set<ReallocPairs>(ToPtr, FromPtr);
Anna Zaksb276bd92012-02-14 00:26:13 +0000685 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks30838b92012-02-13 20:57:07 +0000686 C.addTransition(stateFree);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000687 return;
688 }
689
690 // Default behavior.
691 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
692 // FIXME: We should copy the content of the original buffer.
693 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
694 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000695 if (!stateRealloc)
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000696 return;
697 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr, FromPtr);
Anna Zaksb276bd92012-02-14 00:26:13 +0000698 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000699 C.addTransition(stateRealloc);
700 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000701 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000702}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000703
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000704void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000705 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000706 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000707 const LocationContext *LCtx = C.getLocationContext();
708 SVal count = state->getSVal(CE->getArg(0), LCtx);
709 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000710 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
711 svalBuilder.getContext().getSizeType());
712 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000713
Anna Zaks0bd6b112011-10-26 21:06:34 +0000714 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000715}
716
Anna Zaksda046772012-02-11 21:02:40 +0000717void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
718 CheckerContext &C) const {
719 assert(N);
720 if (!BT_Leak) {
721 BT_Leak.reset(new BuiltinBug("Memory leak",
722 "Allocated memory never released. Potential memory leak."));
723 // Leaks should not be reported if they are post-dominated by a sink:
724 // (1) Sinks are higher importance bugs.
725 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
726 // with __noreturn functions such as assert() or exit(). We choose not
727 // to report leaks on such paths.
728 BT_Leak->setSuppressOnSink(true);
729 }
730
731 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
732 R->addVisitor(new MallocBugVisitor(Sym));
733 C.EmitReport(R);
734}
735
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000736void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
737 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000738{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000739 if (!SymReaper.hasDeadSymbols())
740 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000741
Ted Kremenek8bef8232012-01-26 21:29:00 +0000742 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000743 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000744 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000745
Ted Kremenek217470e2011-07-28 23:07:51 +0000746 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000747 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000748 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
749 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000750 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000751 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000752 Errors.push_back(I->first);
753 }
Jordy Rose90760142010-08-18 04:33:47 +0000754 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000755 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000756
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000757 }
758 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000759
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000760 // Cleanup the Realloc Pairs Map.
761 SymRefToSymRefTy RP = state->get<ReallocPairs>();
762 for (SymRefToSymRefTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
763 if (SymReaper.isDead(I->first) || SymReaper.isDead(I->second)) {
764 state = state->remove<ReallocPairs>(I->first);
765 }
766 }
767
Anna Zaks0bd6b112011-10-26 21:06:34 +0000768 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000769
Ted Kremenek217470e2011-07-28 23:07:51 +0000770 if (N && generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000771 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000772 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
773 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000774 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000775 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000776}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000777
Anna Zaksda046772012-02-11 21:02:40 +0000778void MallocChecker::checkEndPath(CheckerContext &C) const {
779 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000780 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000781
Jordy Rose09cef092010-08-18 04:26:59 +0000782 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000783 RefState RS = I->second;
784 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000785 ExplodedNode *N = C.addTransition(state);
786 if (N)
787 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000788 }
789 }
790}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000791
Anna Zaks91c2a112012-02-08 23:16:56 +0000792bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
793 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000794 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000795 const RefState *RS = state->get<RegionState>(Sym);
796 if (!RS)
797 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000798
Anna Zaks91c2a112012-02-08 23:16:56 +0000799 if (RS->isAllocated()) {
800 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
801 C.addTransition(state);
802 return true;
803 }
804 return false;
805}
806
Anna Zaks66c40402012-02-14 21:55:24 +0000807void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
808 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
809 return;
810
811 // Check use after free, when a freed pointer is passed to a call.
812 ProgramStateRef State = C.getState();
813 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
814 E = CE->arg_end(); I != E; ++I) {
815 const Expr *A = *I;
816 if (A->getType().getTypePtr()->isAnyPointerType()) {
817 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
818 if (!Sym)
819 continue;
820 if (checkUseAfterFree(Sym, C, A))
821 return;
822 }
823 }
824}
825
Anna Zaks91c2a112012-02-08 23:16:56 +0000826void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
827 const Expr *E = S->getRetValue();
828 if (!E)
829 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000830
831 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000832 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000833 if (!Sym)
834 return;
835
Anna Zaks0860cd02012-02-11 21:44:39 +0000836 // Check if we are returning freed memory.
Anna Zaks15d0ae12012-02-11 23:46:36 +0000837 if (checkUseAfterFree(Sym, C, S))
838 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000839
840 // Check if the symbol is escaping.
Anna Zaks91c2a112012-02-08 23:16:56 +0000841 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000842}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000843
Anna Zaks91c2a112012-02-08 23:16:56 +0000844bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
845 const Stmt *S) const {
846 assert(Sym);
847 const RefState *RS = C.getState()->get<RegionState>(Sym);
848 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000849 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000850 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000851 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000852 "after it is freed."));
853
854 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
855 if (S)
856 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000857 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000858 C.EmitReport(R);
859 return true;
860 }
861 }
862 return false;
863}
864
Zhongxing Xuc8023782010-03-10 04:58:55 +0000865// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000866void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
867 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000868 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000869 if (Sym)
870 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000871}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000872
Anna Zaks4fb54872012-02-11 21:02:35 +0000873//===----------------------------------------------------------------------===//
874// Check various ways a symbol can be invalidated.
875// TODO: This logic (the next 3 functions) is copied/similar to the
876// RetainRelease checker. We might want to factor this out.
877//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000878
Anna Zaks4fb54872012-02-11 21:02:35 +0000879// Stop tracking symbols when a value escapes as a result of checkBind.
880// A value escapes in three possible cases:
881// (1) we are binding to something that is not a memory region.
882// (2) we are binding to a memregion that does not have stack storage
883// (3) we are binding to a memregion with stack storage that the store
884// does not understand.
885void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
886 CheckerContext &C) const {
887 // Are we storing to something that causes the value to "escape"?
888 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000889 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000890
Anna Zaks4fb54872012-02-11 21:02:35 +0000891 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
892 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000893
Anna Zaks4fb54872012-02-11 21:02:35 +0000894 if (!escapes) {
895 // To test (3), generate a new state with the binding added. If it is
896 // the same state, then it escapes (since the store cannot represent
897 // the binding).
898 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000899 }
900 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000901
902 // If our store can represent the binding and we aren't storing to something
903 // that doesn't have local storage then just return and have the simulation
904 // state continue as is.
905 if (!escapes)
906 return;
907
908 // Otherwise, find all symbols referenced by 'val' that we are tracking
909 // and stop tracking them.
910 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
911 C.addTransition(state);
912}
913
914// If a symbolic region is assumed to NULL (or another constant), stop tracking
915// it - assuming that allocation failed on this path.
916ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
917 SVal Cond,
918 bool Assumption) const {
919 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +0000920 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
921 // If the symbol is assumed to NULL or another constant, this will
922 // return an APSInt*.
923 if (state->getSymVal(I.getKey()))
924 state = state->remove<RegionState>(I.getKey());
925 }
926
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000927 // Realloc returns 0 when reallocation fails, which means that we should
928 // restore the state of the pointer being reallocated.
929 SymRefToSymRefTy RP = state->get<ReallocPairs>();
930 for (SymRefToSymRefTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
931 // If the symbol is assumed to NULL or another constant, this will
932 // return an APSInt*.
933 if (state->getSymVal(I.getKey())) {
934 const RefState *RS = state->get<RegionState>(I.getData());
935 if (RS) {
936 if (RS->isReleased())
937 state = state->set<RegionState>(I.getData(),
938 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksb276bd92012-02-14 00:26:13 +0000939 else if (RS->isAllocated())
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000940 state = state->set<RegionState>(I.getData(),
941 RefState::getReleased(RS->getStmt()));
942 }
943 state = state->remove<ReallocPairs>(I.getKey());
944 }
945 }
946
Anna Zaks4fb54872012-02-11 21:02:35 +0000947 return state;
948}
949
Anna Zaks66c40402012-02-14 21:55:24 +0000950// Check if the function is not known to us. So, for example, we could
951// conservatively assume it can free/reallocate it's pointer arguments.
952// (We assume that the pointers cannot escape through calls to system
953// functions not handled by this checker.)
954bool MallocChecker::hasUnknownBehavior(const FunctionDecl *FD,
955 ProgramStateRef State) const {
956 ASTContext &ASTC = State->getStateManager().getContext();
957
958 // If it's one of the allocation functions we can reason about, we model it's
959 // behavior explicitly.
960 if (isMemFunction(FD, ASTC)) {
961 return false;
962 }
963
964 // If it's a system call, we know it does not free the memory.
965 SourceManager &SM = ASTC.getSourceManager();
966 if (SM.isInSystemHeader(FD->getLocation())) {
967 return false;
968 }
969
970 // Otherwise, assume that the function can free memory.
971 return true;
972}
973
Anna Zaks4fb54872012-02-11 21:02:35 +0000974// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
975// escapes, when we are tracking p), do not track the symbol as we cannot reason
976// about it anymore.
977ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +0000978MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +0000979 const StoreManager::InvalidatedSymbols *invalidated,
980 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000981 ArrayRef<const MemRegion *> Regions,
982 const CallOrObjCMessage *Call) const {
Anna Zaks4fb54872012-02-11 21:02:35 +0000983 if (!invalidated)
Anna Zaks66c40402012-02-14 21:55:24 +0000984 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +0000985 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +0000986
987 const FunctionDecl *FD = (Call ? dyn_cast<FunctionDecl>(Call->getDecl()) : 0);
988
989 // If it's a call which might free or reallocate memory, we assume that all
990 // regions (explicit and implicit) escaped. Otherwise, whitelist explicit
991 // pointers; we still can track them.
992 if (!(FD && hasUnknownBehavior(FD, State))) {
993 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
994 E = ExplicitRegions.end(); I != E; ++I) {
995 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
996 WhitelistedSymbols.insert(R->getSymbol());
997 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000998 }
999
1000 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1001 E = invalidated->end(); I!=E; ++I) {
1002 SymbolRef sym = *I;
1003 if (WhitelistedSymbols.count(sym))
1004 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001005 // The symbol escaped.
1006 if (const RefState *RS = State->get<RegionState>(sym))
1007 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001008 }
Anna Zaks66c40402012-02-14 21:55:24 +00001009 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001010}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001011
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001012PathDiagnosticPiece *
1013MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1014 const ExplodedNode *PrevN,
1015 BugReporterContext &BRC,
1016 BugReport &BR) {
1017 const RefState *RS = N->getState()->get<RegionState>(Sym);
1018 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1019 if (!RS && !RSPrev)
1020 return 0;
1021
1022 // We expect the interesting locations be StmtPoints corresponding to call
1023 // expressions. We do not support indirect function calls as of now.
1024 const CallExpr *CE = 0;
1025 if (isa<StmtPoint>(N->getLocation()))
1026 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
1027 if (!CE)
1028 return 0;
1029 const FunctionDecl *funDecl = CE->getDirectCallee();
1030 if (!funDecl)
1031 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001032
1033 // Find out if this is an interesting point and what is the kind.
1034 const char *Msg = 0;
1035 if (isAllocated(RS, RSPrev))
1036 Msg = "Memory is allocated here";
1037 else if (isReleased(RS, RSPrev))
1038 Msg = "Memory is released here";
1039 if (!Msg)
1040 return 0;
1041
1042 // Generate the extra diagnostic.
1043 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
1044 N->getLocationContext());
1045 return new PathDiagnosticEventPiece(Pos, Msg);
1046}
1047
1048
Anna Zaks231361a2012-02-08 23:16:52 +00001049#define REGISTER_CHECKER(name) \
1050void ento::register##name(CheckerManager &mgr) {\
1051 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001052}
Anna Zaks231361a2012-02-08 23:16:52 +00001053
1054REGISTER_CHECKER(MallocPessimistic)
1055REGISTER_CHECKER(MallocOptimistic)