blob: 98298c850bf300e4ee8fa6264d2f17102a303835 [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"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Anna Zaks15d0ae12012-02-11 23:46:36 +000023#include "clang/Basic/SourceManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000024#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000026#include "llvm/ADT/STLExtras.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000027using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000028using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000029
30namespace {
31
Zhongxing Xu7fb14642009-12-11 00:55:44 +000032class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000033 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
34 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000035 const Stmt *S;
36
Zhongxing Xu7fb14642009-12-11 00:55:44 +000037public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000038 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
39
Zhongxing Xub94b81a2009-12-31 06:13:07 +000040 bool isAllocated() const { return K == AllocateUnchecked; }
Chris Lattnerfae96222010-09-03 04:34:38 +000041 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000042 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000043 //bool isEscaped() const { return K == Escaped; }
44 //bool isRelinquished() const { return K == Relinquished; }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000045 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000046
47 bool operator==(const RefState &X) const {
48 return K == X.K && S == X.S;
49 }
50
Zhongxing Xub94b81a2009-12-31 06:13:07 +000051 static RefState getAllocateUnchecked(const Stmt *s) {
52 return RefState(AllocateUnchecked, s);
53 }
54 static RefState getAllocateFailed() {
55 return RefState(AllocateFailed, 0);
56 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000057 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
58 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000059 static RefState getRelinquished(const Stmt *s) {
60 return RefState(Relinquished, s);
61 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000062
63 void Profile(llvm::FoldingSetNodeID &ID) const {
64 ID.AddInteger(K);
65 ID.AddPointer(S);
66 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000067};
68
Anna Zaksb319e022012-02-08 20:13:28 +000069class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000070 check::EndPath,
71 check::PreStmt<ReturnStmt>,
Anna Zaksb319e022012-02-08 20:13:28 +000072 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000073 check::Location,
74 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000075 eval::Assume,
76 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000077{
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000078 mutable OwningPtr<BuiltinBug> BT_DoubleFree;
79 mutable OwningPtr<BuiltinBug> BT_Leak;
80 mutable OwningPtr<BuiltinBug> BT_UseFree;
81 mutable OwningPtr<BuiltinBug> BT_UseRelinquished;
82 mutable OwningPtr<BuiltinBug> BT_BadFree;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000083 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000084
85public:
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000086 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +000087
88 /// In pessimistic mode, the checker assumes that it does not know which
89 /// functions might free the memory.
90 struct ChecksFilter {
91 DefaultBool CMallocPessimistic;
92 DefaultBool CMallocOptimistic;
93 };
94
95 ChecksFilter Filter;
96
Anna Zaksb319e022012-02-08 20:13:28 +000097 void initIdentifierInfo(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000098
Anna Zaksb319e022012-02-08 20:13:28 +000099 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000100 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000101 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000102 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000103 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000104 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000105 void checkLocation(SVal l, bool isLoad, const Stmt *S,
106 CheckerContext &C) const;
107 void checkBind(SVal location, SVal val, const Stmt*S,
108 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000109 ProgramStateRef
110 checkRegionChanges(ProgramStateRef state,
111 const StoreManager::InvalidatedSymbols *invalidated,
112 ArrayRef<const MemRegion *> ExplicitRegions,
113 ArrayRef<const MemRegion *> Regions) const;
114 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
115 return true;
116 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000117
Zhongxing Xu7b760962009-11-13 07:25:27 +0000118private:
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000119 static void MallocMem(CheckerContext &C, const CallExpr *CE);
120 static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
121 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000123 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000124 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000125 return MallocMemAux(C, CE,
126 state->getSVal(SizeEx, C.getLocationContext()),
127 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000128 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000129 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000130 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000131 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000132
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000133 void FreeMem(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose2a479922010-08-12 08:54:03 +0000134 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000135 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000136 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
137 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000138 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000139
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000140 void ReallocMem(CheckerContext &C, const CallExpr *CE) const;
141 static void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000142
Anna Zaks91c2a112012-02-08 23:16:56 +0000143 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
144 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
145 const Stmt *S = 0) const;
146
Ted Kremenek9c378f72011-08-12 23:37:29 +0000147 static bool SummarizeValue(raw_ostream &os, SVal V);
148 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000149 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000150
Anna Zaksda046772012-02-11 21:02:40 +0000151 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
152
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000153 /// The bug visitor which allows us to print extra diagnostics along the
154 /// BugReport path. For example, showing the allocation site of the leaked
155 /// region.
156 class MallocBugVisitor : public BugReporterVisitor {
157 protected:
158 // The allocated region symbol tracked by the main analysis.
159 SymbolRef Sym;
160
161 public:
162 MallocBugVisitor(SymbolRef S) : Sym(S) {}
163 virtual ~MallocBugVisitor() {}
164
165 void Profile(llvm::FoldingSetNodeID &ID) const {
166 static int X = 0;
167 ID.AddPointer(&X);
168 ID.AddPointer(Sym);
169 }
170
171 inline bool isAllocated(const RefState *S, const RefState *SPrev) {
172 // Did not track -> allocated. Other state (released) -> allocated.
173 return ((S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
174 }
175
176 inline bool isReleased(const RefState *S, const RefState *SPrev) {
177 // Did not track -> released. Other state (allocated) -> released.
178 return ((S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
179 }
180
181 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
182 const ExplodedNode *PrevN,
183 BugReporterContext &BRC,
184 BugReport &BR);
185 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000186};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000187} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000188
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000189typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000190typedef llvm::ImmutableMap<SymbolRef, SymbolRef> SymRefToSymRefTy;
191class RegionState {};
192class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000193namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000194namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000195 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000196 struct ProgramStateTrait<RegionState>
197 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000198 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000199 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000200
201 template <>
202 struct ProgramStateTrait<ReallocPairs>
203 : public ProgramStatePartialTrait<SymRefToSymRefTy> {
204 static void *GDMIndex() { static int x; return &x; }
205 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000206}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000207}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000208
Anna Zaks4fb54872012-02-11 21:02:35 +0000209namespace {
210class StopTrackingCallback : public SymbolVisitor {
211 ProgramStateRef state;
212public:
213 StopTrackingCallback(ProgramStateRef st) : state(st) {}
214 ProgramStateRef getState() const { return state; }
215
216 bool VisitSymbol(SymbolRef sym) {
217 state = state->remove<RegionState>(sym);
218 return true;
219 }
220};
221} // end anonymous namespace
222
Anna Zaksb319e022012-02-08 20:13:28 +0000223void MallocChecker::initIdentifierInfo(CheckerContext &C) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000224 ASTContext &Ctx = C.getASTContext();
225 if (!II_malloc)
226 II_malloc = &Ctx.Idents.get("malloc");
227 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000228 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000229 if (!II_realloc)
230 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000231 if (!II_calloc)
232 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000233}
234
235void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
236 const FunctionDecl *FD = C.getCalleeDecl(CE);
237 if (!FD)
238 return;
239 initIdentifierInfo(C);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000240
241 if (FD->getIdentifier() == II_malloc) {
242 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000243 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000244 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000245 if (FD->getIdentifier() == II_realloc) {
246 ReallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000247 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000248 }
249
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000250 if (FD->getIdentifier() == II_calloc) {
251 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000252 return;
253 }
254
255 if (FD->getIdentifier() == II_free) {
256 FreeMem(C, CE);
257 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000258 }
259
Anna Zaks91c2a112012-02-08 23:16:56 +0000260 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000261 // Check all the attributes, if there are any.
262 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000263 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000264 for (specific_attr_iterator<OwnershipAttr>
265 i = FD->specific_attr_begin<OwnershipAttr>(),
266 e = FD->specific_attr_end<OwnershipAttr>();
267 i != e; ++i) {
268 switch ((*i)->getOwnKind()) {
269 case OwnershipAttr::Returns: {
270 MallocMemReturnsAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000271 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000272 }
273 case OwnershipAttr::Takes:
274 case OwnershipAttr::Holds: {
275 FreeMemAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000276 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000277 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000278 }
279 }
280 }
Anna Zaks91c2a112012-02-08 23:16:56 +0000281
Anna Zaks15d0ae12012-02-11 23:46:36 +0000282 // Check use after free, when a freed pointer is passed to a call.
283 ProgramStateRef State = C.getState();
284 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
285 E = CE->arg_end(); I != E; ++I) {
286 const Expr *A = *I;
287 if (A->getType().getTypePtr()->isAnyPointerType()) {
288 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
289 if (!Sym)
290 continue;
291 if (checkUseAfterFree(Sym, C, A))
292 return;
293 }
294 }
295
296 // The pointer might escape through a function call.
297 // TODO: This should be rewritten to take into account inlining.
Anna Zaks91c2a112012-02-08 23:16:56 +0000298 if (Filter.CMallocPessimistic) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000299 SourceLocation FLoc = FD->getLocation();
300 // We assume that the pointers cannot escape through calls to system
301 // functions.
302 if (C.getSourceManager().isInSystemHeader(FLoc))
303 return;
304
Anna Zaks91c2a112012-02-08 23:16:56 +0000305 ProgramStateRef State = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000306 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
307 E = CE->arg_end(); I != E; ++I) {
308 const Expr *A = *I;
309 if (A->getType().getTypePtr()->isAnyPointerType()) {
310 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
311 if (!Sym)
Anna Zakse9ef5622012-02-10 01:11:00 +0000312 continue;
Anna Zaks91c2a112012-02-08 23:16:56 +0000313 checkEscape(Sym, A, C);
Anna Zaks91c2a112012-02-08 23:16:56 +0000314 }
315 }
316 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000317}
318
319void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000320 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000321 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000322 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000323}
324
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000325void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
326 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000327 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000328 return;
329
Sean Huntcf807c42010-08-18 23:23:40 +0000330 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000331 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000332 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000333 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000334 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000335 return;
336 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000337 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000338 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000339 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000340}
341
Anna Zaksb319e022012-02-08 20:13:28 +0000342ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000343 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000344 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000345 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000346 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000347
Anna Zaksb319e022012-02-08 20:13:28 +0000348 // Get the return value.
349 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000350
Jordy Rose32f26562010-07-04 00:00:41 +0000351 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000352 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000353
Jordy Rose32f26562010-07-04 00:00:41 +0000354 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000355 const SymbolicRegion *R =
356 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
357 if (!R || !isa<DefinedOrUnknownSVal>(Size))
358 return 0;
359
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000360 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000361 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000362 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000363 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000364
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000365 state = state->assume(extentMatchesSize, true);
366 assert(state);
367
368 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000369 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000370
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000371 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000372 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000373}
374
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000375void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000376 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000377
378 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000379 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000380}
381
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000382void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000383 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000384 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000385 return;
386
Sean Huntcf807c42010-08-18 23:23:40 +0000387 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
388 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000389 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000390 FreeMemAux(C, CE, C.getState(), *I,
391 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000392 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000393 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000394 }
395}
396
Ted Kremenek8bef8232012-01-26 21:29:00 +0000397ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000398 const CallExpr *CE,
399 ProgramStateRef state,
400 unsigned Num,
401 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000402 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000403 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000404 if (!isa<DefinedOrUnknownSVal>(ArgVal))
405 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000406 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
407
408 // Check for null dereferences.
409 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000410 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000411
412 // FIXME: Technically using 'Assume' here can result in a path
413 // bifurcation. In such cases we need to return two states, not just one.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000414 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000415 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000416
417 // The explicit NULL case, no operation is performed.
418 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000419 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000420
421 assert(notNullState);
422
Jordy Rose43859f62010-06-07 19:32:37 +0000423 // Unknown values could easily be okay
424 // Undefined values are handled elsewhere
425 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000426 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000427
Jordy Rose43859f62010-06-07 19:32:37 +0000428 const MemRegion *R = ArgVal.getAsRegion();
429
430 // Nonlocs can't be freed, of course.
431 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
432 if (!R) {
433 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000434 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000435 }
436
437 R = R->StripCasts();
438
439 // Blocks might show up as heap data, but should not be free()d
440 if (isa<BlockDataRegion>(R)) {
441 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000442 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000443 }
444
445 const MemSpaceRegion *MS = R->getMemorySpace();
446
447 // Parameters, locals, statics, and globals shouldn't be freed.
448 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
449 // FIXME: at the time this code was written, malloc() regions were
450 // represented by conjured symbols, which are all in UnknownSpaceRegion.
451 // This means that there isn't actually anything from HeapSpaceRegion
452 // that should be freed, even though we allow it here.
453 // Of course, free() can work on memory allocated outside the current
454 // function, so UnknownSpaceRegion is always a possibility.
455 // False negatives are better than false positives.
456
457 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000458 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000459 }
460
461 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
462 // Various cases could lead to non-symbol values here.
463 // For now, ignore them.
464 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000465 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000466
467 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000468 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000469
470 // If the symbol has not been tracked, return. This is possible when free() is
471 // called on a pointer that does not get its pointee directly from malloc().
472 // Full support of this requires inter-procedural analysis.
473 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000474 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000475
476 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000477 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000478 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000479 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000480 BT_DoubleFree.reset(
481 new BuiltinBug("Double free",
482 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000483 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000484 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000485 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000486 C.EmitReport(R);
487 }
Anna Zaksb319e022012-02-08 20:13:28 +0000488 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000489 }
490
491 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000492 if (Hold)
493 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
494 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000495}
496
Ted Kremenek9c378f72011-08-12 23:37:29 +0000497bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000498 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
499 os << "an integer (" << IntVal->getValue() << ")";
500 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
501 os << "a constant address (" << ConstAddr->getValue() << ")";
502 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000503 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000504 else
505 return false;
506
507 return true;
508}
509
Ted Kremenek9c378f72011-08-12 23:37:29 +0000510bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000511 const MemRegion *MR) {
512 switch (MR->getKind()) {
513 case MemRegion::FunctionTextRegionKind: {
514 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
515 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000516 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000517 else
518 os << "the address of a function";
519 return true;
520 }
521 case MemRegion::BlockTextRegionKind:
522 os << "block text";
523 return true;
524 case MemRegion::BlockDataRegionKind:
525 // FIXME: where the block came from?
526 os << "a block";
527 return true;
528 default: {
529 const MemSpaceRegion *MS = MR->getMemorySpace();
530
Anna Zakseb31a762012-01-04 23:54:01 +0000531 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000532 const VarRegion *VR = dyn_cast<VarRegion>(MR);
533 const VarDecl *VD;
534 if (VR)
535 VD = VR->getDecl();
536 else
537 VD = NULL;
538
539 if (VD)
540 os << "the address of the local variable '" << VD->getName() << "'";
541 else
542 os << "the address of a local stack variable";
543 return true;
544 }
Anna Zakseb31a762012-01-04 23:54:01 +0000545
546 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000547 const VarRegion *VR = dyn_cast<VarRegion>(MR);
548 const VarDecl *VD;
549 if (VR)
550 VD = VR->getDecl();
551 else
552 VD = NULL;
553
554 if (VD)
555 os << "the address of the parameter '" << VD->getName() << "'";
556 else
557 os << "the address of a parameter";
558 return true;
559 }
Anna Zakseb31a762012-01-04 23:54:01 +0000560
561 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000562 const VarRegion *VR = dyn_cast<VarRegion>(MR);
563 const VarDecl *VD;
564 if (VR)
565 VD = VR->getDecl();
566 else
567 VD = NULL;
568
569 if (VD) {
570 if (VD->isStaticLocal())
571 os << "the address of the static variable '" << VD->getName() << "'";
572 else
573 os << "the address of the global variable '" << VD->getName() << "'";
574 } else
575 os << "the address of a global variable";
576 return true;
577 }
Anna Zakseb31a762012-01-04 23:54:01 +0000578
579 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000580 }
581 }
582}
583
584void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000585 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000586 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000587 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000588 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000589
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000590 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000591 llvm::raw_svector_ostream os(buf);
592
593 const MemRegion *MR = ArgVal.getAsRegion();
594 if (MR) {
595 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
596 MR = ER->getSuperRegion();
597
598 // Special case for alloca()
599 if (isa<AllocaRegion>(MR))
600 os << "Argument to free() was allocated by alloca(), not malloc()";
601 else {
602 os << "Argument to free() is ";
603 if (SummarizeRegion(os, MR))
604 os << ", which is not memory allocated by malloc()";
605 else
606 os << "not memory allocated by malloc()";
607 }
608 } else {
609 os << "Argument to free() is ";
610 if (SummarizeValue(os, ArgVal))
611 os << ", which is not memory allocated by malloc()";
612 else
613 os << "not memory allocated by malloc()";
614 }
615
Anna Zakse172e8b2011-08-17 23:00:25 +0000616 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000617 R->addRange(range);
618 C.EmitReport(R);
619 }
620}
621
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000622void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000623 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000624 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000625 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000626 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
627 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
628 return;
629 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000630
Ted Kremenek846eabd2010-12-01 21:28:31 +0000631 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000632
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000633 DefinedOrUnknownSVal PtrEQ =
634 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000635
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000636 // Get the size argument. If there is no size arg then give up.
637 const Expr *Arg1 = CE->getArg(1);
638 if (!Arg1)
639 return;
640
641 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000642 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
643 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
644 return;
645 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000646
647 // Compare the size argument to 0.
648 DefinedOrUnknownSVal SizeZero =
649 svalBuilder.evalEQ(state, Arg1Val,
650 svalBuilder.makeIntValWithPtrWidth(0, false));
651
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000652 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
653 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
654 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
655 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
656 // We only assume exceptional states if they are definitely true; if the
657 // state is under-constrained, assume regular realloc behavior.
658 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
659 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
660
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000661 // If the ptr is NULL and the size is not 0, the call is equivalent to
662 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000663 if ( PrtIsNull && !SizeIsZero) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000664 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000665 UndefinedVal(), StatePtrIsNull);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000666 C.addTransition(stateMalloc);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000667 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000668 }
669
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000670 if (PrtIsNull && SizeIsZero)
671 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000672
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000673 assert(!PrtIsNull);
674
675 // If the size is 0, free the memory.
676 if (SizeIsZero)
677 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
678 // Bind the return value to NULL because it is now free.
679 // TODO: This is tricky. Does not currently work.
680 // The semantics of the return value are:
681 // If size was equal to 0, either NULL or a pointer suitable to be passed
682 // to free() is returned.
683 C.addTransition(stateFree->BindExpr(CE, LCtx,
684 svalBuilder.makeNull(), true));
685 return;
686 }
687
688 // Default behavior.
689 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
690 // FIXME: We should copy the content of the original buffer.
691 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
692 UnknownVal(), stateFree);
693 SymbolRef FromPtr = arg0Val.getAsSymbol();
694 SVal RetVal = state->getSVal(CE, LCtx);
695 SymbolRef ToPtr = RetVal.getAsSymbol();
696 if (!stateRealloc || !FromPtr || !ToPtr)
697 return;
698 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr, FromPtr);
699 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
807void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
808 const Expr *E = S->getRetValue();
809 if (!E)
810 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000811
812 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000813 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000814 if (!Sym)
815 return;
816
Anna Zaks0860cd02012-02-11 21:44:39 +0000817 // Check if we are returning freed memory.
Anna Zaks15d0ae12012-02-11 23:46:36 +0000818 if (checkUseAfterFree(Sym, C, S))
819 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000820
821 // Check if the symbol is escaping.
Anna Zaks91c2a112012-02-08 23:16:56 +0000822 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000823}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000824
Anna Zaks91c2a112012-02-08 23:16:56 +0000825bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
826 const Stmt *S) const {
827 assert(Sym);
828 const RefState *RS = C.getState()->get<RegionState>(Sym);
829 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000830 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000831 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000832 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000833 "after it is freed."));
834
835 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
836 if (S)
837 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000838 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000839 C.EmitReport(R);
840 return true;
841 }
842 }
843 return false;
844}
845
Zhongxing Xuc8023782010-03-10 04:58:55 +0000846// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000847void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
848 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000849 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000850 if (Sym)
851 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000852}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000853
Anna Zaks4fb54872012-02-11 21:02:35 +0000854//===----------------------------------------------------------------------===//
855// Check various ways a symbol can be invalidated.
856// TODO: This logic (the next 3 functions) is copied/similar to the
857// RetainRelease checker. We might want to factor this out.
858//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000859
Anna Zaks4fb54872012-02-11 21:02:35 +0000860// Stop tracking symbols when a value escapes as a result of checkBind.
861// A value escapes in three possible cases:
862// (1) we are binding to something that is not a memory region.
863// (2) we are binding to a memregion that does not have stack storage
864// (3) we are binding to a memregion with stack storage that the store
865// does not understand.
866void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
867 CheckerContext &C) const {
868 // Are we storing to something that causes the value to "escape"?
869 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000870 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000871
Anna Zaks4fb54872012-02-11 21:02:35 +0000872 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
873 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000874
Anna Zaks4fb54872012-02-11 21:02:35 +0000875 if (!escapes) {
876 // To test (3), generate a new state with the binding added. If it is
877 // the same state, then it escapes (since the store cannot represent
878 // the binding).
879 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000880 }
881 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000882
883 // If our store can represent the binding and we aren't storing to something
884 // that doesn't have local storage then just return and have the simulation
885 // state continue as is.
886 if (!escapes)
887 return;
888
889 // Otherwise, find all symbols referenced by 'val' that we are tracking
890 // and stop tracking them.
891 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
892 C.addTransition(state);
893}
894
895// If a symbolic region is assumed to NULL (or another constant), stop tracking
896// it - assuming that allocation failed on this path.
897ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
898 SVal Cond,
899 bool Assumption) const {
900 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +0000901 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
902 // If the symbol is assumed to NULL or another constant, this will
903 // return an APSInt*.
904 if (state->getSymVal(I.getKey()))
905 state = state->remove<RegionState>(I.getKey());
906 }
907
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000908 // Realloc returns 0 when reallocation fails, which means that we should
909 // restore the state of the pointer being reallocated.
910 SymRefToSymRefTy RP = state->get<ReallocPairs>();
911 for (SymRefToSymRefTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
912 // If the symbol is assumed to NULL or another constant, this will
913 // return an APSInt*.
914 if (state->getSymVal(I.getKey())) {
915 const RefState *RS = state->get<RegionState>(I.getData());
916 if (RS) {
917 if (RS->isReleased())
918 state = state->set<RegionState>(I.getData(),
919 RefState::getAllocateUnchecked(RS->getStmt()));
920 if (RS->isAllocated())
921 state = state->set<RegionState>(I.getData(),
922 RefState::getReleased(RS->getStmt()));
923 }
924 state = state->remove<ReallocPairs>(I.getKey());
925 }
926 }
927
Anna Zaks4fb54872012-02-11 21:02:35 +0000928 return state;
929}
930
931// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
932// escapes, when we are tracking p), do not track the symbol as we cannot reason
933// about it anymore.
934ProgramStateRef
935MallocChecker::checkRegionChanges(ProgramStateRef state,
936 const StoreManager::InvalidatedSymbols *invalidated,
937 ArrayRef<const MemRegion *> ExplicitRegions,
938 ArrayRef<const MemRegion *> Regions) const {
939 if (!invalidated)
940 return state;
941
942 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
943 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
944 E = ExplicitRegions.end(); I != E; ++I) {
945 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
946 WhitelistedSymbols.insert(SR->getSymbol());
947 }
948
949 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
950 E = invalidated->end(); I!=E; ++I) {
951 SymbolRef sym = *I;
952 if (WhitelistedSymbols.count(sym))
953 continue;
954 // Don't track the symbol.
955 state = state->remove<RegionState>(sym);
956 }
957 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000958}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000959
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000960PathDiagnosticPiece *
961MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
962 const ExplodedNode *PrevN,
963 BugReporterContext &BRC,
964 BugReport &BR) {
965 const RefState *RS = N->getState()->get<RegionState>(Sym);
966 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
967 if (!RS && !RSPrev)
968 return 0;
969
970 // We expect the interesting locations be StmtPoints corresponding to call
971 // expressions. We do not support indirect function calls as of now.
972 const CallExpr *CE = 0;
973 if (isa<StmtPoint>(N->getLocation()))
974 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
975 if (!CE)
976 return 0;
977 const FunctionDecl *funDecl = CE->getDirectCallee();
978 if (!funDecl)
979 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000980
981 // Find out if this is an interesting point and what is the kind.
982 const char *Msg = 0;
983 if (isAllocated(RS, RSPrev))
984 Msg = "Memory is allocated here";
985 else if (isReleased(RS, RSPrev))
986 Msg = "Memory is released here";
987 if (!Msg)
988 return 0;
989
990 // Generate the extra diagnostic.
991 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
992 N->getLocationContext());
993 return new PathDiagnosticEventPiece(Pos, Msg);
994}
995
996
Anna Zaks231361a2012-02-08 23:16:52 +0000997#define REGISTER_CHECKER(name) \
998void ento::register##name(CheckerManager &mgr) {\
999 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001000}
Anna Zaks231361a2012-02-08 23:16:52 +00001001
1002REGISTER_CHECKER(MallocPessimistic)
1003REGISTER_CHECKER(MallocOptimistic)