blob: 430a77a5704c9612b73d7651c9232d8657cb1cfa [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"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000023#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000024#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000025#include "llvm/ADT/STLExtras.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000026using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000027using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000028
29namespace {
30
Zhongxing Xu7fb14642009-12-11 00:55:44 +000031class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000032 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
33 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000034 const Stmt *S;
35
Zhongxing Xu7fb14642009-12-11 00:55:44 +000036public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000037 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
38
Zhongxing Xub94b81a2009-12-31 06:13:07 +000039 bool isAllocated() const { return K == AllocateUnchecked; }
Chris Lattnerfae96222010-09-03 04:34:38 +000040 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000041 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000042 //bool isEscaped() const { return K == Escaped; }
43 //bool isRelinquished() const { return K == Relinquished; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000044
45 bool operator==(const RefState &X) const {
46 return K == X.K && S == X.S;
47 }
48
Zhongxing Xub94b81a2009-12-31 06:13:07 +000049 static RefState getAllocateUnchecked(const Stmt *s) {
50 return RefState(AllocateUnchecked, s);
51 }
52 static RefState getAllocateFailed() {
53 return RefState(AllocateFailed, 0);
54 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000055 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
56 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000057 static RefState getRelinquished(const Stmt *s) {
58 return RefState(Relinquished, s);
59 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000060
61 void Profile(llvm::FoldingSetNodeID &ID) const {
62 ID.AddInteger(K);
63 ID.AddPointer(S);
64 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000065};
66
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000067class RegionState {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +000068
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
151 /// The bug visitor which allows us to print extra diagnostics along the
152 /// BugReport path. For example, showing the allocation site of the leaked
153 /// region.
154 class MallocBugVisitor : public BugReporterVisitor {
155 protected:
156 // The allocated region symbol tracked by the main analysis.
157 SymbolRef Sym;
158
159 public:
160 MallocBugVisitor(SymbolRef S) : Sym(S) {}
161 virtual ~MallocBugVisitor() {}
162
163 void Profile(llvm::FoldingSetNodeID &ID) const {
164 static int X = 0;
165 ID.AddPointer(&X);
166 ID.AddPointer(Sym);
167 }
168
169 inline bool isAllocated(const RefState *S, const RefState *SPrev) {
170 // Did not track -> allocated. Other state (released) -> allocated.
171 return ((S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
172 }
173
174 inline bool isReleased(const RefState *S, const RefState *SPrev) {
175 // Did not track -> released. Other state (allocated) -> released.
176 return ((S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
177 }
178
179 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
180 const ExplodedNode *PrevN,
181 BugReporterContext &BRC,
182 BugReport &BR);
183 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000184};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000185} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000186
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000187typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
188
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000189namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000190namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000191 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000192 struct ProgramStateTrait<RegionState>
193 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000194 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000195 };
196}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000197}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000198
Anna Zaks4fb54872012-02-11 21:02:35 +0000199namespace {
200class StopTrackingCallback : public SymbolVisitor {
201 ProgramStateRef state;
202public:
203 StopTrackingCallback(ProgramStateRef st) : state(st) {}
204 ProgramStateRef getState() const { return state; }
205
206 bool VisitSymbol(SymbolRef sym) {
207 state = state->remove<RegionState>(sym);
208 return true;
209 }
210};
211} // end anonymous namespace
212
Anna Zaksb319e022012-02-08 20:13:28 +0000213void MallocChecker::initIdentifierInfo(CheckerContext &C) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000214 ASTContext &Ctx = C.getASTContext();
215 if (!II_malloc)
216 II_malloc = &Ctx.Idents.get("malloc");
217 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000218 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000219 if (!II_realloc)
220 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000221 if (!II_calloc)
222 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000223}
224
225void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
226 const FunctionDecl *FD = C.getCalleeDecl(CE);
227 if (!FD)
228 return;
229 initIdentifierInfo(C);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000230
231 if (FD->getIdentifier() == II_malloc) {
232 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000233 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000234 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000235 if (FD->getIdentifier() == II_realloc) {
236 ReallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000237 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000238 }
239
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000240 if (FD->getIdentifier() == II_calloc) {
241 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000242 return;
243 }
244
245 if (FD->getIdentifier() == II_free) {
246 FreeMem(C, CE);
247 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000248 }
249
Anna Zaks91c2a112012-02-08 23:16:56 +0000250 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000251 // Check all the attributes, if there are any.
252 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000253 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000254 for (specific_attr_iterator<OwnershipAttr>
255 i = FD->specific_attr_begin<OwnershipAttr>(),
256 e = FD->specific_attr_end<OwnershipAttr>();
257 i != e; ++i) {
258 switch ((*i)->getOwnKind()) {
259 case OwnershipAttr::Returns: {
260 MallocMemReturnsAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000261 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000262 }
263 case OwnershipAttr::Takes:
264 case OwnershipAttr::Holds: {
265 FreeMemAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000266 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000267 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000268 }
269 }
270 }
Anna Zaks91c2a112012-02-08 23:16:56 +0000271
272 if (Filter.CMallocPessimistic) {
273 ProgramStateRef State = C.getState();
274 // The pointer might escape through a function call.
275 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
276 E = CE->arg_end(); I != E; ++I) {
277 const Expr *A = *I;
278 if (A->getType().getTypePtr()->isAnyPointerType()) {
279 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
280 if (!Sym)
Anna Zakse9ef5622012-02-10 01:11:00 +0000281 continue;
Anna Zaks91c2a112012-02-08 23:16:56 +0000282 checkEscape(Sym, A, C);
283 checkUseAfterFree(Sym, C, A);
284 }
285 }
286 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000287}
288
289void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000290 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000291 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000292 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000293}
294
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000295void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
296 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000297 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000298 return;
299
Sean Huntcf807c42010-08-18 23:23:40 +0000300 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000301 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000302 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000303 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000304 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000305 return;
306 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000307 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000308 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000309 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000310}
311
Anna Zaksb319e022012-02-08 20:13:28 +0000312ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000313 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000314 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000315 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000316 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000317
Anna Zaksb319e022012-02-08 20:13:28 +0000318 // Get the return value.
319 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000320
Jordy Rose32f26562010-07-04 00:00:41 +0000321 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000322 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000323
Jordy Rose32f26562010-07-04 00:00:41 +0000324 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000325 const SymbolicRegion *R =
326 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
327 if (!R || !isa<DefinedOrUnknownSVal>(Size))
328 return 0;
329
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000330 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000331 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000332 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000333 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000334
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000335 state = state->assume(extentMatchesSize, true);
336 assert(state);
337
338 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000339 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000340
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000341 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000342 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000343}
344
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000345void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000346 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000347
348 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000349 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000350}
351
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000352void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000353 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000354 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000355 return;
356
Sean Huntcf807c42010-08-18 23:23:40 +0000357 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
358 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000359 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000360 FreeMemAux(C, CE, C.getState(), *I,
361 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000362 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000363 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000364 }
365}
366
Ted Kremenek8bef8232012-01-26 21:29:00 +0000367ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000368 const CallExpr *CE,
369 ProgramStateRef state,
370 unsigned Num,
371 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000372 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000373 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000374 if (!isa<DefinedOrUnknownSVal>(ArgVal))
375 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000376 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
377
378 // Check for null dereferences.
379 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000380 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000381
382 // FIXME: Technically using 'Assume' here can result in a path
383 // bifurcation. In such cases we need to return two states, not just one.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000384 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000385 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000386
387 // The explicit NULL case, no operation is performed.
388 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000389 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000390
391 assert(notNullState);
392
Jordy Rose43859f62010-06-07 19:32:37 +0000393 // Unknown values could easily be okay
394 // Undefined values are handled elsewhere
395 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000396 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000397
Jordy Rose43859f62010-06-07 19:32:37 +0000398 const MemRegion *R = ArgVal.getAsRegion();
399
400 // Nonlocs can't be freed, of course.
401 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
402 if (!R) {
403 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000404 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000405 }
406
407 R = R->StripCasts();
408
409 // Blocks might show up as heap data, but should not be free()d
410 if (isa<BlockDataRegion>(R)) {
411 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000412 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000413 }
414
415 const MemSpaceRegion *MS = R->getMemorySpace();
416
417 // Parameters, locals, statics, and globals shouldn't be freed.
418 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
419 // FIXME: at the time this code was written, malloc() regions were
420 // represented by conjured symbols, which are all in UnknownSpaceRegion.
421 // This means that there isn't actually anything from HeapSpaceRegion
422 // that should be freed, even though we allow it here.
423 // Of course, free() can work on memory allocated outside the current
424 // function, so UnknownSpaceRegion is always a possibility.
425 // False negatives are better than false positives.
426
427 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000428 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000429 }
430
431 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
432 // Various cases could lead to non-symbol values here.
433 // For now, ignore them.
434 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000435 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000436
437 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000438 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000439
440 // If the symbol has not been tracked, return. This is possible when free() is
441 // called on a pointer that does not get its pointee directly from malloc().
442 // Full support of this requires inter-procedural analysis.
443 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000444 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000445
446 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000447 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000448 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000449 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000450 BT_DoubleFree.reset(
451 new BuiltinBug("Double free",
452 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000453 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000454 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000455 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000456 C.EmitReport(R);
457 }
Anna Zaksb319e022012-02-08 20:13:28 +0000458 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000459 }
460
461 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000462 if (Hold)
463 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
464 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000465}
466
Ted Kremenek9c378f72011-08-12 23:37:29 +0000467bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000468 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
469 os << "an integer (" << IntVal->getValue() << ")";
470 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
471 os << "a constant address (" << ConstAddr->getValue() << ")";
472 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000473 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000474 else
475 return false;
476
477 return true;
478}
479
Ted Kremenek9c378f72011-08-12 23:37:29 +0000480bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000481 const MemRegion *MR) {
482 switch (MR->getKind()) {
483 case MemRegion::FunctionTextRegionKind: {
484 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
485 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000486 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000487 else
488 os << "the address of a function";
489 return true;
490 }
491 case MemRegion::BlockTextRegionKind:
492 os << "block text";
493 return true;
494 case MemRegion::BlockDataRegionKind:
495 // FIXME: where the block came from?
496 os << "a block";
497 return true;
498 default: {
499 const MemSpaceRegion *MS = MR->getMemorySpace();
500
Anna Zakseb31a762012-01-04 23:54:01 +0000501 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000502 const VarRegion *VR = dyn_cast<VarRegion>(MR);
503 const VarDecl *VD;
504 if (VR)
505 VD = VR->getDecl();
506 else
507 VD = NULL;
508
509 if (VD)
510 os << "the address of the local variable '" << VD->getName() << "'";
511 else
512 os << "the address of a local stack variable";
513 return true;
514 }
Anna Zakseb31a762012-01-04 23:54:01 +0000515
516 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000517 const VarRegion *VR = dyn_cast<VarRegion>(MR);
518 const VarDecl *VD;
519 if (VR)
520 VD = VR->getDecl();
521 else
522 VD = NULL;
523
524 if (VD)
525 os << "the address of the parameter '" << VD->getName() << "'";
526 else
527 os << "the address of a parameter";
528 return true;
529 }
Anna Zakseb31a762012-01-04 23:54:01 +0000530
531 if (isa<GlobalsSpaceRegion>(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 if (VD->isStaticLocal())
541 os << "the address of the static variable '" << VD->getName() << "'";
542 else
543 os << "the address of the global variable '" << VD->getName() << "'";
544 } else
545 os << "the address of a global variable";
546 return true;
547 }
Anna Zakseb31a762012-01-04 23:54:01 +0000548
549 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000550 }
551 }
552}
553
554void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000555 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000556 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000557 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000558 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000559
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000560 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000561 llvm::raw_svector_ostream os(buf);
562
563 const MemRegion *MR = ArgVal.getAsRegion();
564 if (MR) {
565 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
566 MR = ER->getSuperRegion();
567
568 // Special case for alloca()
569 if (isa<AllocaRegion>(MR))
570 os << "Argument to free() was allocated by alloca(), not malloc()";
571 else {
572 os << "Argument to free() is ";
573 if (SummarizeRegion(os, MR))
574 os << ", which is not memory allocated by malloc()";
575 else
576 os << "not memory allocated by malloc()";
577 }
578 } else {
579 os << "Argument to free() is ";
580 if (SummarizeValue(os, ArgVal))
581 os << ", which is not memory allocated by malloc()";
582 else
583 os << "not memory allocated by malloc()";
584 }
585
Anna Zakse172e8b2011-08-17 23:00:25 +0000586 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000587 R->addRange(range);
588 C.EmitReport(R);
589 }
590}
591
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000592void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000593 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000594 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000595 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000596 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
597 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
598 return;
599 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000600
Ted Kremenek846eabd2010-12-01 21:28:31 +0000601 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000602
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000603 DefinedOrUnknownSVal PtrEQ =
604 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000605
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000606 // Get the size argument. If there is no size arg then give up.
607 const Expr *Arg1 = CE->getArg(1);
608 if (!Arg1)
609 return;
610
611 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000612 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
613 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
614 return;
615 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000616
617 // Compare the size argument to 0.
618 DefinedOrUnknownSVal SizeZero =
619 svalBuilder.evalEQ(state, Arg1Val,
620 svalBuilder.makeIntValWithPtrWidth(0, false));
621
622 // If the ptr is NULL and the size is not 0, the call is equivalent to
623 // malloc(size).
Ted Kremenek8bef8232012-01-26 21:29:00 +0000624 ProgramStateRef stateEqual = state->assume(PtrEQ, true);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000625 if (stateEqual && state->assume(SizeZero, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000626 // Hack: set the NULL symbolic region to released to suppress false warning.
627 // In the future we should add more states for allocated regions, e.g.,
628 // CheckedNull, CheckedNonNull.
629
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000630 SymbolRef Sym = arg0Val.getAsLocSymbol();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000631 if (Sym)
632 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
633
Ted Kremenek8bef8232012-01-26 21:29:00 +0000634 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000635 UndefinedVal(), stateEqual);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000636 C.addTransition(stateMalloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000637 }
638
Ted Kremenek8bef8232012-01-26 21:29:00 +0000639 if (ProgramStateRef stateNotEqual = state->assume(PtrEQ, false)) {
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000640 // If the size is 0, free the memory.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000641 if (ProgramStateRef stateSizeZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000642 stateNotEqual->assume(SizeZero, true))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000643 if (ProgramStateRef stateFree =
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000644 FreeMemAux(C, CE, stateSizeZero, 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000645
Zhongxing Xud56763f2011-09-01 04:53:59 +0000646 // Bind the return value to NULL because it is now free.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000647 C.addTransition(stateFree->BindExpr(CE, LCtx,
648 svalBuilder.makeNull(), true));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000649 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000650 if (ProgramStateRef stateSizeNotZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000651 stateNotEqual->assume(SizeZero,false))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000652 if (ProgramStateRef stateFree = FreeMemAux(C, CE, stateSizeNotZero,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000653 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000654 // FIXME: We should copy the content of the original buffer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000655 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000656 UnknownVal(), stateFree);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000657 C.addTransition(stateRealloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000658 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000659 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000660}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000661
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000662void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000663 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000664 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000665 const LocationContext *LCtx = C.getLocationContext();
666 SVal count = state->getSVal(CE->getArg(0), LCtx);
667 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000668 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
669 svalBuilder.getContext().getSizeType());
670 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000671
Anna Zaks0bd6b112011-10-26 21:06:34 +0000672 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000673}
674
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000675void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
676 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000677{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000678 if (!SymReaper.hasDeadSymbols())
679 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000680
Ted Kremenek8bef8232012-01-26 21:29:00 +0000681 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000682 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000683 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000684
Ted Kremenek217470e2011-07-28 23:07:51 +0000685 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000686 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000687 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
688 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000689 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000690 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000691 Errors.push_back(I->first);
692 }
Jordy Rose90760142010-08-18 04:33:47 +0000693 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000694 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000695
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000696 }
697 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000698
Anna Zaks0bd6b112011-10-26 21:06:34 +0000699 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000700
Ted Kremenek217470e2011-07-28 23:07:51 +0000701 if (N && generateReport) {
702 if (!BT_Leak)
703 BT_Leak.reset(new BuiltinBug("Memory leak",
Anna Zaksf8c17b72012-02-09 06:48:19 +0000704 "Allocated memory never released. Potential memory leak."));
705 for (llvm::SmallVector<SymbolRef, 2>::iterator
706 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
707 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
708 R->addVisitor(new MallocBugVisitor(*I));
709 C.EmitReport(R);
710 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000711 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000712}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000713
Anna Zaksaf498a22011-10-25 19:56:48 +0000714void MallocChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000715 ProgramStateRef state = Ctx.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000716 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000717
Jordy Rose09cef092010-08-18 04:26:59 +0000718 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000719 RefState RS = I->second;
720 if (RS.isAllocated()) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000721 ExplodedNode *N = Ctx.addTransition(state);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000722 if (N) {
723 if (!BT_Leak)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000724 BT_Leak.reset(new BuiltinBug("Memory leak",
725 "Allocated memory never released. Potential memory leak."));
Zhongxing Xu243fde92009-11-17 07:54:15 +0000726 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000727 R->addVisitor(new MallocBugVisitor(I->first));
Anna Zaksaf498a22011-10-25 19:56:48 +0000728 Ctx.EmitReport(R);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000729 }
730 }
731 }
732}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000733
Anna Zaks91c2a112012-02-08 23:16:56 +0000734bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
735 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000736 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000737 const RefState *RS = state->get<RegionState>(Sym);
738 if (!RS)
739 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000740
Anna Zaks91c2a112012-02-08 23:16:56 +0000741 if (RS->isAllocated()) {
742 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
743 C.addTransition(state);
744 return true;
745 }
746 return false;
747}
748
749void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
750 const Expr *E = S->getRetValue();
751 if (!E)
752 return;
753 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000754 if (!Sym)
755 return;
756
Anna Zaks91c2a112012-02-08 23:16:56 +0000757 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000758}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000759
Anna Zaks91c2a112012-02-08 23:16:56 +0000760bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
761 const Stmt *S) const {
762 assert(Sym);
763 const RefState *RS = C.getState()->get<RegionState>(Sym);
764 if (RS && RS->isReleased()) {
765 if (ExplodedNode *N = C.addTransition()) {
766 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000767 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000768 "after it is freed."));
769
770 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
771 if (S)
772 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000773 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000774 C.EmitReport(R);
775 return true;
776 }
777 }
778 return false;
779}
780
Zhongxing Xuc8023782010-03-10 04:58:55 +0000781// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000782void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
783 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000784 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000785 if (Sym)
786 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000787}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000788
Anna Zaks4fb54872012-02-11 21:02:35 +0000789//===----------------------------------------------------------------------===//
790// Check various ways a symbol can be invalidated.
791// TODO: This logic (the next 3 functions) is copied/similar to the
792// RetainRelease checker. We might want to factor this out.
793//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000794
Anna Zaks4fb54872012-02-11 21:02:35 +0000795// Stop tracking symbols when a value escapes as a result of checkBind.
796// A value escapes in three possible cases:
797// (1) we are binding to something that is not a memory region.
798// (2) we are binding to a memregion that does not have stack storage
799// (3) we are binding to a memregion with stack storage that the store
800// does not understand.
801void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
802 CheckerContext &C) const {
803 // Are we storing to something that causes the value to "escape"?
804 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000805 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000806
Anna Zaks4fb54872012-02-11 21:02:35 +0000807 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
808 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000809
Anna Zaks4fb54872012-02-11 21:02:35 +0000810 if (!escapes) {
811 // To test (3), generate a new state with the binding added. If it is
812 // the same state, then it escapes (since the store cannot represent
813 // the binding).
814 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000815 }
816 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000817
818 // If our store can represent the binding and we aren't storing to something
819 // that doesn't have local storage then just return and have the simulation
820 // state continue as is.
821 if (!escapes)
822 return;
823
824 // Otherwise, find all symbols referenced by 'val' that we are tracking
825 // and stop tracking them.
826 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
827 C.addTransition(state);
828}
829
830// If a symbolic region is assumed to NULL (or another constant), stop tracking
831// it - assuming that allocation failed on this path.
832ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
833 SVal Cond,
834 bool Assumption) const {
835 RegionStateTy RS = state->get<RegionState>();
836
837 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
838 // If the symbol is assumed to NULL or another constant, this will
839 // return an APSInt*.
840 if (state->getSymVal(I.getKey()))
841 state = state->remove<RegionState>(I.getKey());
842 }
843
844 return state;
845}
846
847// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
848// escapes, when we are tracking p), do not track the symbol as we cannot reason
849// about it anymore.
850ProgramStateRef
851MallocChecker::checkRegionChanges(ProgramStateRef state,
852 const StoreManager::InvalidatedSymbols *invalidated,
853 ArrayRef<const MemRegion *> ExplicitRegions,
854 ArrayRef<const MemRegion *> Regions) const {
855 if (!invalidated)
856 return state;
857
858 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
859 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
860 E = ExplicitRegions.end(); I != E; ++I) {
861 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
862 WhitelistedSymbols.insert(SR->getSymbol());
863 }
864
865 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
866 E = invalidated->end(); I!=E; ++I) {
867 SymbolRef sym = *I;
868 if (WhitelistedSymbols.count(sym))
869 continue;
870 // Don't track the symbol.
871 state = state->remove<RegionState>(sym);
872 }
873 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000874}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000875
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000876PathDiagnosticPiece *
877MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
878 const ExplodedNode *PrevN,
879 BugReporterContext &BRC,
880 BugReport &BR) {
881 const RefState *RS = N->getState()->get<RegionState>(Sym);
882 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
883 if (!RS && !RSPrev)
884 return 0;
885
886 // We expect the interesting locations be StmtPoints corresponding to call
887 // expressions. We do not support indirect function calls as of now.
888 const CallExpr *CE = 0;
889 if (isa<StmtPoint>(N->getLocation()))
890 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
891 if (!CE)
892 return 0;
893 const FunctionDecl *funDecl = CE->getDirectCallee();
894 if (!funDecl)
895 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000896
897 // Find out if this is an interesting point and what is the kind.
898 const char *Msg = 0;
899 if (isAllocated(RS, RSPrev))
900 Msg = "Memory is allocated here";
901 else if (isReleased(RS, RSPrev))
902 Msg = "Memory is released here";
903 if (!Msg)
904 return 0;
905
906 // Generate the extra diagnostic.
907 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
908 N->getLocationContext());
909 return new PathDiagnosticEventPiece(Pos, Msg);
910}
911
912
Anna Zaks231361a2012-02-08 23:16:52 +0000913#define REGISTER_CHECKER(name) \
914void ento::register##name(CheckerManager &mgr) {\
915 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000916}
Anna Zaks231361a2012-02-08 23:16:52 +0000917
918REGISTER_CHECKER(MallocPessimistic)
919REGISTER_CHECKER(MallocOptimistic)