blob: 7cbb49e2d8f0b0e009e1a39d55d61317d31a6645 [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
Anna Zaksb276bd92012-02-14 00:26:13 +0000412 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000413 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000414 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000415 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000416 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000417
Jordy Rose43859f62010-06-07 19:32:37 +0000418 // Unknown values could easily be okay
419 // Undefined values are handled elsewhere
420 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000421 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000422
Jordy Rose43859f62010-06-07 19:32:37 +0000423 const MemRegion *R = ArgVal.getAsRegion();
424
425 // Nonlocs can't be freed, of course.
426 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
427 if (!R) {
428 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000429 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000430 }
431
432 R = R->StripCasts();
433
434 // Blocks might show up as heap data, but should not be free()d
435 if (isa<BlockDataRegion>(R)) {
436 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000437 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000438 }
439
440 const MemSpaceRegion *MS = R->getMemorySpace();
441
442 // Parameters, locals, statics, and globals shouldn't be freed.
443 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
444 // FIXME: at the time this code was written, malloc() regions were
445 // represented by conjured symbols, which are all in UnknownSpaceRegion.
446 // This means that there isn't actually anything from HeapSpaceRegion
447 // that should be freed, even though we allow it here.
448 // Of course, free() can work on memory allocated outside the current
449 // function, so UnknownSpaceRegion is always a possibility.
450 // False negatives are better than false positives.
451
452 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000453 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000454 }
455
456 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
457 // Various cases could lead to non-symbol values here.
458 // For now, ignore them.
459 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000460 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000461
462 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000463 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000464
465 // If the symbol has not been tracked, return. This is possible when free() is
466 // called on a pointer that does not get its pointee directly from malloc().
467 // Full support of this requires inter-procedural analysis.
468 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000469 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000470
471 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000472 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000473 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000474 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000475 BT_DoubleFree.reset(
476 new BuiltinBug("Double free",
477 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000478 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000479 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000480 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000481 C.EmitReport(R);
482 }
Anna Zaksb319e022012-02-08 20:13:28 +0000483 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000484 }
485
486 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000487 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000488 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
489 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000490}
491
Ted Kremenek9c378f72011-08-12 23:37:29 +0000492bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000493 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
494 os << "an integer (" << IntVal->getValue() << ")";
495 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
496 os << "a constant address (" << ConstAddr->getValue() << ")";
497 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000498 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000499 else
500 return false;
501
502 return true;
503}
504
Ted Kremenek9c378f72011-08-12 23:37:29 +0000505bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000506 const MemRegion *MR) {
507 switch (MR->getKind()) {
508 case MemRegion::FunctionTextRegionKind: {
509 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
510 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000511 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000512 else
513 os << "the address of a function";
514 return true;
515 }
516 case MemRegion::BlockTextRegionKind:
517 os << "block text";
518 return true;
519 case MemRegion::BlockDataRegionKind:
520 // FIXME: where the block came from?
521 os << "a block";
522 return true;
523 default: {
524 const MemSpaceRegion *MS = MR->getMemorySpace();
525
Anna Zakseb31a762012-01-04 23:54:01 +0000526 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000527 const VarRegion *VR = dyn_cast<VarRegion>(MR);
528 const VarDecl *VD;
529 if (VR)
530 VD = VR->getDecl();
531 else
532 VD = NULL;
533
534 if (VD)
535 os << "the address of the local variable '" << VD->getName() << "'";
536 else
537 os << "the address of a local stack variable";
538 return true;
539 }
Anna Zakseb31a762012-01-04 23:54:01 +0000540
541 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000542 const VarRegion *VR = dyn_cast<VarRegion>(MR);
543 const VarDecl *VD;
544 if (VR)
545 VD = VR->getDecl();
546 else
547 VD = NULL;
548
549 if (VD)
550 os << "the address of the parameter '" << VD->getName() << "'";
551 else
552 os << "the address of a parameter";
553 return true;
554 }
Anna Zakseb31a762012-01-04 23:54:01 +0000555
556 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000557 const VarRegion *VR = dyn_cast<VarRegion>(MR);
558 const VarDecl *VD;
559 if (VR)
560 VD = VR->getDecl();
561 else
562 VD = NULL;
563
564 if (VD) {
565 if (VD->isStaticLocal())
566 os << "the address of the static variable '" << VD->getName() << "'";
567 else
568 os << "the address of the global variable '" << VD->getName() << "'";
569 } else
570 os << "the address of a global variable";
571 return true;
572 }
Anna Zakseb31a762012-01-04 23:54:01 +0000573
574 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000575 }
576 }
577}
578
579void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000580 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000581 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000582 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000583 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000584
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000585 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000586 llvm::raw_svector_ostream os(buf);
587
588 const MemRegion *MR = ArgVal.getAsRegion();
589 if (MR) {
590 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
591 MR = ER->getSuperRegion();
592
593 // Special case for alloca()
594 if (isa<AllocaRegion>(MR))
595 os << "Argument to free() was allocated by alloca(), not malloc()";
596 else {
597 os << "Argument to free() is ";
598 if (SummarizeRegion(os, MR))
599 os << ", which is not memory allocated by malloc()";
600 else
601 os << "not memory allocated by malloc()";
602 }
603 } else {
604 os << "Argument to free() is ";
605 if (SummarizeValue(os, ArgVal))
606 os << ", which is not memory allocated by malloc()";
607 else
608 os << "not memory allocated by malloc()";
609 }
610
Anna Zakse172e8b2011-08-17 23:00:25 +0000611 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000612 R->addRange(range);
613 C.EmitReport(R);
614 }
615}
616
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000617void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000618 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000619 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000620 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000621 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
622 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
623 return;
624 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000625
Ted Kremenek846eabd2010-12-01 21:28:31 +0000626 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000627
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000628 DefinedOrUnknownSVal PtrEQ =
629 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000630
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000631 // Get the size argument. If there is no size arg then give up.
632 const Expr *Arg1 = CE->getArg(1);
633 if (!Arg1)
634 return;
635
636 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000637 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
638 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
639 return;
640 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000641
642 // Compare the size argument to 0.
643 DefinedOrUnknownSVal SizeZero =
644 svalBuilder.evalEQ(state, Arg1Val,
645 svalBuilder.makeIntValWithPtrWidth(0, false));
646
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000647 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
648 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
649 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
650 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
651 // We only assume exceptional states if they are definitely true; if the
652 // state is under-constrained, assume regular realloc behavior.
653 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
654 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
655
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000656 // If the ptr is NULL and the size is not 0, the call is equivalent to
657 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000658 if ( PrtIsNull && !SizeIsZero) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000659 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000660 UndefinedVal(), StatePtrIsNull);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000661 C.addTransition(stateMalloc);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000662 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000663 }
664
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000665 if (PrtIsNull && SizeIsZero)
666 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000667
Anna Zaks30838b92012-02-13 20:57:07 +0000668 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000669 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000670 SymbolRef FromPtr = arg0Val.getAsSymbol();
671 SVal RetVal = state->getSVal(CE, LCtx);
672 SymbolRef ToPtr = RetVal.getAsSymbol();
673 if (!FromPtr || !ToPtr)
674 return;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000675
676 // If the size is 0, free the memory.
677 if (SizeIsZero)
678 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000679 // The semantics of the return value are:
680 // If size was equal to 0, either NULL or a pointer suitable to be passed
681 // to free() is returned.
Anna Zaks30838b92012-02-13 20:57:07 +0000682 stateFree = stateFree->set<ReallocPairs>(ToPtr, FromPtr);
Anna Zaksb276bd92012-02-14 00:26:13 +0000683 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks30838b92012-02-13 20:57:07 +0000684 C.addTransition(stateFree);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000685 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);
Anna Zaks30838b92012-02-13 20:57:07 +0000693 if (!stateRealloc)
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000694 return;
695 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr, FromPtr);
Anna Zaksb276bd92012-02-14 00:26:13 +0000696 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000697 C.addTransition(stateRealloc);
698 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000699 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000700}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000701
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000702void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000703 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000704 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000705 const LocationContext *LCtx = C.getLocationContext();
706 SVal count = state->getSVal(CE->getArg(0), LCtx);
707 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000708 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
709 svalBuilder.getContext().getSizeType());
710 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000711
Anna Zaks0bd6b112011-10-26 21:06:34 +0000712 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000713}
714
Anna Zaksda046772012-02-11 21:02:40 +0000715void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
716 CheckerContext &C) const {
717 assert(N);
718 if (!BT_Leak) {
719 BT_Leak.reset(new BuiltinBug("Memory leak",
720 "Allocated memory never released. Potential memory leak."));
721 // Leaks should not be reported if they are post-dominated by a sink:
722 // (1) Sinks are higher importance bugs.
723 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
724 // with __noreturn functions such as assert() or exit(). We choose not
725 // to report leaks on such paths.
726 BT_Leak->setSuppressOnSink(true);
727 }
728
729 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
730 R->addVisitor(new MallocBugVisitor(Sym));
731 C.EmitReport(R);
732}
733
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000734void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
735 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000736{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000737 if (!SymReaper.hasDeadSymbols())
738 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000739
Ted Kremenek8bef8232012-01-26 21:29:00 +0000740 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000741 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000742 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000743
Ted Kremenek217470e2011-07-28 23:07:51 +0000744 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000745 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000746 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
747 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000748 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000749 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000750 Errors.push_back(I->first);
751 }
Jordy Rose90760142010-08-18 04:33:47 +0000752 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000753 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000754
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000755 }
756 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000757
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000758 // Cleanup the Realloc Pairs Map.
759 SymRefToSymRefTy RP = state->get<ReallocPairs>();
760 for (SymRefToSymRefTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
761 if (SymReaper.isDead(I->first) || SymReaper.isDead(I->second)) {
762 state = state->remove<ReallocPairs>(I->first);
763 }
764 }
765
Anna Zaks0bd6b112011-10-26 21:06:34 +0000766 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000767
Ted Kremenek217470e2011-07-28 23:07:51 +0000768 if (N && generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000769 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000770 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
771 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000772 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000773 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000774}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000775
Anna Zaksda046772012-02-11 21:02:40 +0000776void MallocChecker::checkEndPath(CheckerContext &C) const {
777 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000778 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000779
Jordy Rose09cef092010-08-18 04:26:59 +0000780 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000781 RefState RS = I->second;
782 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000783 ExplodedNode *N = C.addTransition(state);
784 if (N)
785 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000786 }
787 }
788}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000789
Anna Zaks91c2a112012-02-08 23:16:56 +0000790bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
791 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000792 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000793 const RefState *RS = state->get<RegionState>(Sym);
794 if (!RS)
795 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000796
Anna Zaks91c2a112012-02-08 23:16:56 +0000797 if (RS->isAllocated()) {
798 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
799 C.addTransition(state);
800 return true;
801 }
802 return false;
803}
804
805void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
806 const Expr *E = S->getRetValue();
807 if (!E)
808 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000809
810 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000811 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000812 if (!Sym)
813 return;
814
Anna Zaks0860cd02012-02-11 21:44:39 +0000815 // Check if we are returning freed memory.
Anna Zaks15d0ae12012-02-11 23:46:36 +0000816 if (checkUseAfterFree(Sym, C, S))
817 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000818
819 // Check if the symbol is escaping.
Anna Zaks91c2a112012-02-08 23:16:56 +0000820 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000821}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000822
Anna Zaks91c2a112012-02-08 23:16:56 +0000823bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
824 const Stmt *S) const {
825 assert(Sym);
826 const RefState *RS = C.getState()->get<RegionState>(Sym);
827 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000828 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000829 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000830 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000831 "after it is freed."));
832
833 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
834 if (S)
835 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000836 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000837 C.EmitReport(R);
838 return true;
839 }
840 }
841 return false;
842}
843
Zhongxing Xuc8023782010-03-10 04:58:55 +0000844// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000845void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
846 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000847 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000848 if (Sym)
849 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000850}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000851
Anna Zaks4fb54872012-02-11 21:02:35 +0000852//===----------------------------------------------------------------------===//
853// Check various ways a symbol can be invalidated.
854// TODO: This logic (the next 3 functions) is copied/similar to the
855// RetainRelease checker. We might want to factor this out.
856//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000857
Anna Zaks4fb54872012-02-11 21:02:35 +0000858// Stop tracking symbols when a value escapes as a result of checkBind.
859// A value escapes in three possible cases:
860// (1) we are binding to something that is not a memory region.
861// (2) we are binding to a memregion that does not have stack storage
862// (3) we are binding to a memregion with stack storage that the store
863// does not understand.
864void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
865 CheckerContext &C) const {
866 // Are we storing to something that causes the value to "escape"?
867 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000868 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000869
Anna Zaks4fb54872012-02-11 21:02:35 +0000870 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
871 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000872
Anna Zaks4fb54872012-02-11 21:02:35 +0000873 if (!escapes) {
874 // To test (3), generate a new state with the binding added. If it is
875 // the same state, then it escapes (since the store cannot represent
876 // the binding).
877 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000878 }
879 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000880
881 // If our store can represent the binding and we aren't storing to something
882 // that doesn't have local storage then just return and have the simulation
883 // state continue as is.
884 if (!escapes)
885 return;
886
887 // Otherwise, find all symbols referenced by 'val' that we are tracking
888 // and stop tracking them.
889 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
890 C.addTransition(state);
891}
892
893// If a symbolic region is assumed to NULL (or another constant), stop tracking
894// it - assuming that allocation failed on this path.
895ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
896 SVal Cond,
897 bool Assumption) const {
898 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +0000899 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
900 // If the symbol is assumed to NULL or another constant, this will
901 // return an APSInt*.
902 if (state->getSymVal(I.getKey()))
903 state = state->remove<RegionState>(I.getKey());
904 }
905
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000906 // Realloc returns 0 when reallocation fails, which means that we should
907 // restore the state of the pointer being reallocated.
908 SymRefToSymRefTy RP = state->get<ReallocPairs>();
909 for (SymRefToSymRefTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
910 // If the symbol is assumed to NULL or another constant, this will
911 // return an APSInt*.
912 if (state->getSymVal(I.getKey())) {
913 const RefState *RS = state->get<RegionState>(I.getData());
914 if (RS) {
915 if (RS->isReleased())
916 state = state->set<RegionState>(I.getData(),
917 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksb276bd92012-02-14 00:26:13 +0000918 else if (RS->isAllocated())
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000919 state = state->set<RegionState>(I.getData(),
920 RefState::getReleased(RS->getStmt()));
921 }
922 state = state->remove<ReallocPairs>(I.getKey());
923 }
924 }
925
Anna Zaks4fb54872012-02-11 21:02:35 +0000926 return state;
927}
928
929// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
930// escapes, when we are tracking p), do not track the symbol as we cannot reason
931// about it anymore.
932ProgramStateRef
933MallocChecker::checkRegionChanges(ProgramStateRef state,
934 const StoreManager::InvalidatedSymbols *invalidated,
935 ArrayRef<const MemRegion *> ExplicitRegions,
936 ArrayRef<const MemRegion *> Regions) const {
937 if (!invalidated)
938 return state;
939
940 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
941 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
942 E = ExplicitRegions.end(); I != E; ++I) {
943 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
944 WhitelistedSymbols.insert(SR->getSymbol());
945 }
946
947 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
948 E = invalidated->end(); I!=E; ++I) {
949 SymbolRef sym = *I;
950 if (WhitelistedSymbols.count(sym))
951 continue;
952 // Don't track the symbol.
953 state = state->remove<RegionState>(sym);
954 }
955 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000956}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000957
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000958PathDiagnosticPiece *
959MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
960 const ExplodedNode *PrevN,
961 BugReporterContext &BRC,
962 BugReport &BR) {
963 const RefState *RS = N->getState()->get<RegionState>(Sym);
964 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
965 if (!RS && !RSPrev)
966 return 0;
967
968 // We expect the interesting locations be StmtPoints corresponding to call
969 // expressions. We do not support indirect function calls as of now.
970 const CallExpr *CE = 0;
971 if (isa<StmtPoint>(N->getLocation()))
972 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
973 if (!CE)
974 return 0;
975 const FunctionDecl *funDecl = CE->getDirectCallee();
976 if (!funDecl)
977 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000978
979 // Find out if this is an interesting point and what is the kind.
980 const char *Msg = 0;
981 if (isAllocated(RS, RSPrev))
982 Msg = "Memory is allocated here";
983 else if (isReleased(RS, RSPrev))
984 Msg = "Memory is released here";
985 if (!Msg)
986 return 0;
987
988 // Generate the extra diagnostic.
989 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
990 N->getLocationContext());
991 return new PathDiagnosticEventPiece(Pos, Msg);
992}
993
994
Anna Zaks231361a2012-02-08 23:16:52 +0000995#define REGISTER_CHECKER(name) \
996void ento::register##name(CheckerManager &mgr) {\
997 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000998}
Anna Zaks231361a2012-02-08 23:16:52 +0000999
1000REGISTER_CHECKER(MallocPessimistic)
1001REGISTER_CHECKER(MallocOptimistic)