blob: b7ad4be00b94dac7c2c9375961869c61f34a2a5f [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
Zhongxing Xu7b760962009-11-13 07:25:27 +000015#include "GRExprEngineExperimentalChecks.h"
Benjamin Kramer5e2d2c22010-03-27 21:19:47 +000016#include "clang/Checker/BugReporter/BugType.h"
Ted Kremenek1309f9a2010-01-25 04:41:41 +000017#include "clang/Checker/PathSensitive/CheckerVisitor.h"
18#include "clang/Checker/PathSensitive/GRState.h"
19#include "clang/Checker/PathSensitive/GRStateTrait.h"
20#include "clang/Checker/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000021#include "llvm/ADT/ImmutableMap.h"
22using namespace clang;
23
24namespace {
25
Zhongxing Xu7fb14642009-12-11 00:55:44 +000026class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000027 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
28 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000029 const Stmt *S;
30
Zhongxing Xu7fb14642009-12-11 00:55:44 +000031public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000032 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
33
Zhongxing Xub94b81a2009-12-31 06:13:07 +000034 bool isAllocated() const { return K == AllocateUnchecked; }
Ted Kremenekdd0e4902010-07-31 01:52:11 +000035 bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000036 bool isReleased() const { return K == Released; }
37 bool isEscaped() const { return K == Escaped; }
Ted Kremenekdd0e4902010-07-31 01:52:11 +000038 bool isRelinquished() const { return K == Relinquished; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000039
40 bool operator==(const RefState &X) const {
41 return K == X.K && S == X.S;
42 }
43
Zhongxing Xub94b81a2009-12-31 06:13:07 +000044 static RefState getAllocateUnchecked(const Stmt *s) {
45 return RefState(AllocateUnchecked, s);
46 }
47 static RefState getAllocateFailed() {
48 return RefState(AllocateFailed, 0);
49 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000050 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
51 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000052 static RefState getRelinquished(const Stmt *s) {
53 return RefState(Relinquished, s);
54 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000055
56 void Profile(llvm::FoldingSetNodeID &ID) const {
57 ID.AddInteger(K);
58 ID.AddPointer(S);
59 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000060};
61
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000062class RegionState {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +000063
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000064class MallocChecker : public CheckerVisitor<MallocChecker> {
Zhongxing Xu589c0f22009-11-12 08:38:56 +000065 BuiltinBug *BT_DoubleFree;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +000066 BuiltinBug *BT_Leak;
Zhongxing Xuc8023782010-03-10 04:58:55 +000067 BuiltinBug *BT_UseFree;
Ted Kremenekdd0e4902010-07-31 01:52:11 +000068 BuiltinBug *BT_UseRelinquished;
Jordy Rose43859f62010-06-07 19:32:37 +000069 BuiltinBug *BT_BadFree;
Zhongxing Xua5ce9662010-06-01 03:01:33 +000070 IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000071
72public:
Zhongxing Xud9c84c82009-12-12 12:29:38 +000073 MallocChecker()
Ted Kremenekdde201b2010-08-06 21:12:55 +000074 : BT_DoubleFree(0), BT_Leak(0), BT_UseFree(0), BT_UseRelinquished(0),
75 BT_BadFree(0),
Zhongxing Xua5ce9662010-06-01 03:01:33 +000076 II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Zhongxing Xu589c0f22009-11-12 08:38:56 +000077 static void *getTag();
Zhongxing Xua49c6b72009-12-11 03:09:01 +000078 bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
Jordy Rose7dadf792010-07-01 20:09:55 +000079 void EvalDeadSymbols(CheckerContext &C, SymbolReaper &SymReaper);
Zhongxing Xu243fde92009-11-17 07:54:15 +000080 void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +000081 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
Jordy Rose72905cf2010-08-04 07:10:57 +000082 const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption,
83 bool *respondsToCallback);
Zhongxing Xuc8023782010-03-10 04:58:55 +000084 void VisitLocation(CheckerContext &C, const Stmt *S, SVal l);
Ted Kremenekdd0e4902010-07-31 01:52:11 +000085 virtual void PreVisitBind(CheckerContext &C, const Stmt *AssignE,
86 const Stmt *StoreE, SVal location,
87 SVal val);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000088
Zhongxing Xu7b760962009-11-13 07:25:27 +000089private:
Zhongxing Xu589c0f22009-11-12 08:38:56 +000090 void MallocMem(CheckerContext &C, const CallExpr *CE);
Ted Kremenekdde201b2010-08-06 21:12:55 +000091 void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
92 const OwnershipAttr* Att);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000093 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +000094 const Expr *SizeEx, SVal Init,
95 const GRState *state) {
96 return MallocMemAux(C, CE, state->getSVal(SizeEx), Init, state);
97 }
98 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
99 SVal SizeEx, SVal Init,
100 const GRState *state);
101
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000102 void FreeMem(CheckerContext &C, const CallExpr *CE);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000103 void FreeMemAttr(CheckerContext &C, const CallExpr *CE, const OwnershipAttr* Att);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000104 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000105 const GRState *state, unsigned Num, bool Hold);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000106
107 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000108 void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000109
110 bool SummarizeValue(llvm::raw_ostream& os, SVal V);
111 bool SummarizeRegion(llvm::raw_ostream& os, const MemRegion *MR);
112 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000113};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000114} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000115
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000116typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
117
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000118namespace clang {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000119 template <>
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000120 struct GRStateTrait<RegionState>
121 : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > {
122 static void *GDMIndex() { return MallocChecker::getTag(); }
123 };
124}
125
Zhongxing Xu7b760962009-11-13 07:25:27 +0000126void clang::RegisterMallocChecker(GRExprEngine &Eng) {
127 Eng.registerCheck(new MallocChecker());
128}
129
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000130void *MallocChecker::getTag() {
131 static int x;
132 return &x;
133}
134
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000135bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
136 const GRState *state = C.getState();
137 const Expr *Callee = CE->getCallee();
Ted Kremenek13976632010-02-08 16:18:51 +0000138 SVal L = state->getSVal(Callee);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000139
140 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000141 if (!FD)
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000142 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000143
144 ASTContext &Ctx = C.getASTContext();
145 if (!II_malloc)
146 II_malloc = &Ctx.Idents.get("malloc");
147 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000148 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000149 if (!II_realloc)
150 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000151 if (!II_calloc)
152 II_calloc = &Ctx.Idents.get("calloc");
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000153
154 if (FD->getIdentifier() == II_malloc) {
155 MallocMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000156 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000157 }
158
159 if (FD->getIdentifier() == II_free) {
160 FreeMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000161 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000162 }
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000163
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000164 if (FD->getIdentifier() == II_realloc) {
165 ReallocMem(C, CE);
166 return true;
167 }
168
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000169 if (FD->getIdentifier() == II_calloc) {
170 CallocMem(C, CE);
171 return true;
172 }
173
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000174 // Check all the attributes, if there are any.
175 // There can be multiple of these attributes.
176 bool rv = false;
177 if (FD->hasAttrs()) {
178 for (const Attr *attr = FD->getAttrs(); attr; attr = attr->getNext()) {
179 if(const OwnershipAttr* Att = dyn_cast<OwnershipAttr>(attr)) {
180 switch (Att->getKind()) {
181 case OwnershipAttr::Returns: {
182 MallocMemReturnsAttr(C, CE, Att);
183 rv = true;
184 break;
185 }
186 case OwnershipAttr::Takes:
187 case OwnershipAttr::Holds: {
188 FreeMemAttr(C, CE, Att);
189 rv = true;
190 break;
191 }
192 default:
193 break;
194 }
195 }
196 }
197 }
198 return rv;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000199}
200
201void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000202 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
203 C.getState());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000204 C.addTransition(state);
205}
206
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000207void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
208 const OwnershipAttr* Att) {
209 if (!Att->isModule("malloc"))
210 return;
211
212 const unsigned *I = Att->begin(), *E = Att->end();
213 if (I != E) {
214 const GRState *state =
215 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
216 C.addTransition(state);
217 return;
218 }
219 const GRState *state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
220 C.getState());
221 C.addTransition(state);
222}
223
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000224const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
225 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000226 SVal Size, SVal Init,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000227 const GRState *state) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000228 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
229 ValueManager &ValMgr = C.getValueManager();
230
Jordy Rose32f26562010-07-04 00:00:41 +0000231 // Set the return value.
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000232 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
Jordy Rose32f26562010-07-04 00:00:41 +0000233 state = state->BindExpr(CE, RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000234
Jordy Rose32f26562010-07-04 00:00:41 +0000235 // Fill the region with the initialization value.
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000236 state = state->bindDefault(RetVal, Init);
237
Jordy Rose32f26562010-07-04 00:00:41 +0000238 // Set the region's extent equal to the Size parameter.
239 const SymbolicRegion *R = cast<SymbolicRegion>(RetVal.getAsRegion());
240 DefinedOrUnknownSVal Extent = R->getExtent(ValMgr);
241 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
242
243 SValuator &SVator = ValMgr.getSValuator();
244 DefinedOrUnknownSVal ExtentMatchesSize =
245 SVator.EvalEQ(state, Extent, DefinedSize);
246 state = state->Assume(ExtentMatchesSize, true);
247
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000248 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000249 assert(Sym);
250 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000251 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000252}
253
254void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000255 const GRState *state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000256
257 if (state)
258 C.addTransition(state);
259}
260
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000261void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
262 const OwnershipAttr* Att) {
263 if (!Att->isModule("malloc"))
264 return;
265
266 for (const unsigned *I = Att->begin(), *E = Att->end(); I != E; ++I) {
267 const GRState *state =
268 FreeMemAux(C, CE, C.getState(), *I, Att->isKind(OwnershipAttr::Holds));
269 if (state)
270 C.addTransition(state);
271 }
272}
273
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000274const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000275 const GRState *state, unsigned Num,
276 bool Hold) {
277 const Expr *ArgExpr = CE->getArg(Num);
Jordy Rose43859f62010-06-07 19:32:37 +0000278 SVal ArgVal = state->getSVal(ArgExpr);
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000279
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000280 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
281
282 // Check for null dereferences.
283 if (!isa<Loc>(location))
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000284 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000285
286 // FIXME: Technically using 'Assume' here can result in a path
287 // bifurcation. In such cases we need to return two states, not just one.
288 const GRState *notNullState, *nullState;
289 llvm::tie(notNullState, nullState) = state->Assume(location);
290
291 // The explicit NULL case, no operation is performed.
292 if (nullState && !notNullState)
293 return nullState;
294
295 assert(notNullState);
296
Jordy Rose43859f62010-06-07 19:32:37 +0000297 // Unknown values could easily be okay
298 // Undefined values are handled elsewhere
299 if (ArgVal.isUnknownOrUndef())
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000300 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000301
Jordy Rose43859f62010-06-07 19:32:37 +0000302 const MemRegion *R = ArgVal.getAsRegion();
303
304 // Nonlocs can't be freed, of course.
305 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
306 if (!R) {
307 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
308 return NULL;
309 }
310
311 R = R->StripCasts();
312
313 // Blocks might show up as heap data, but should not be free()d
314 if (isa<BlockDataRegion>(R)) {
315 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
316 return NULL;
317 }
318
319 const MemSpaceRegion *MS = R->getMemorySpace();
320
321 // Parameters, locals, statics, and globals shouldn't be freed.
322 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
323 // FIXME: at the time this code was written, malloc() regions were
324 // represented by conjured symbols, which are all in UnknownSpaceRegion.
325 // This means that there isn't actually anything from HeapSpaceRegion
326 // that should be freed, even though we allow it here.
327 // Of course, free() can work on memory allocated outside the current
328 // function, so UnknownSpaceRegion is always a possibility.
329 // False negatives are better than false positives.
330
331 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
332 return NULL;
333 }
334
335 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
336 // Various cases could lead to non-symbol values here.
337 // For now, ignore them.
338 if (!SR)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000339 return notNullState;
Jordy Rose43859f62010-06-07 19:32:37 +0000340
341 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000342 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000343
344 // If the symbol has not been tracked, return. This is possible when free() is
345 // called on a pointer that does not get its pointee directly from malloc().
346 // Full support of this requires inter-procedural analysis.
347 if (!RS)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000348 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000349
350 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000351 if (RS->isReleased()) {
Ted Kremenek8c912302010-08-06 21:12:53 +0000352 if (ExplodedNode *N = C.GenerateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000353 if (!BT_DoubleFree)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000354 BT_DoubleFree
355 = new BuiltinBug("Double free",
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000356 "Try to free a memory block that has been released");
357 // FIXME: should find where it's freed last time.
358 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000359 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000360 C.EmitReport(R);
361 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000362 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000363 }
364
365 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000366 if (Hold)
367 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
368 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000369}
370
Jordy Rose43859f62010-06-07 19:32:37 +0000371bool MallocChecker::SummarizeValue(llvm::raw_ostream& os, SVal V) {
372 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
373 os << "an integer (" << IntVal->getValue() << ")";
374 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
375 os << "a constant address (" << ConstAddr->getValue() << ")";
376 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
377 os << "the address of the label '"
378 << Label->getLabel()->getID()->getName()
379 << "'";
380 else
381 return false;
382
383 return true;
384}
385
386bool MallocChecker::SummarizeRegion(llvm::raw_ostream& os,
387 const MemRegion *MR) {
388 switch (MR->getKind()) {
389 case MemRegion::FunctionTextRegionKind: {
390 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
391 if (FD)
392 os << "the address of the function '" << FD << "'";
393 else
394 os << "the address of a function";
395 return true;
396 }
397 case MemRegion::BlockTextRegionKind:
398 os << "block text";
399 return true;
400 case MemRegion::BlockDataRegionKind:
401 // FIXME: where the block came from?
402 os << "a block";
403 return true;
404 default: {
405 const MemSpaceRegion *MS = MR->getMemorySpace();
406
407 switch (MS->getKind()) {
408 case MemRegion::StackLocalsSpaceRegionKind: {
409 const VarRegion *VR = dyn_cast<VarRegion>(MR);
410 const VarDecl *VD;
411 if (VR)
412 VD = VR->getDecl();
413 else
414 VD = NULL;
415
416 if (VD)
417 os << "the address of the local variable '" << VD->getName() << "'";
418 else
419 os << "the address of a local stack variable";
420 return true;
421 }
422 case MemRegion::StackArgumentsSpaceRegionKind: {
423 const VarRegion *VR = dyn_cast<VarRegion>(MR);
424 const VarDecl *VD;
425 if (VR)
426 VD = VR->getDecl();
427 else
428 VD = NULL;
429
430 if (VD)
431 os << "the address of the parameter '" << VD->getName() << "'";
432 else
433 os << "the address of a parameter";
434 return true;
435 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000436 case MemRegion::NonStaticGlobalSpaceRegionKind:
437 case MemRegion::StaticGlobalSpaceRegionKind: {
Jordy Rose43859f62010-06-07 19:32:37 +0000438 const VarRegion *VR = dyn_cast<VarRegion>(MR);
439 const VarDecl *VD;
440 if (VR)
441 VD = VR->getDecl();
442 else
443 VD = NULL;
444
445 if (VD) {
446 if (VD->isStaticLocal())
447 os << "the address of the static variable '" << VD->getName() << "'";
448 else
449 os << "the address of the global variable '" << VD->getName() << "'";
450 } else
451 os << "the address of a global variable";
452 return true;
453 }
454 default:
455 return false;
456 }
457 }
458 }
459}
460
461void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
462 SourceRange range) {
Ted Kremenek8c912302010-08-06 21:12:53 +0000463 if (ExplodedNode *N = C.GenerateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000464 if (!BT_BadFree)
465 BT_BadFree = new BuiltinBug("Bad free");
466
467 llvm::SmallString<100> buf;
468 llvm::raw_svector_ostream os(buf);
469
470 const MemRegion *MR = ArgVal.getAsRegion();
471 if (MR) {
472 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
473 MR = ER->getSuperRegion();
474
475 // Special case for alloca()
476 if (isa<AllocaRegion>(MR))
477 os << "Argument to free() was allocated by alloca(), not malloc()";
478 else {
479 os << "Argument to free() is ";
480 if (SummarizeRegion(os, MR))
481 os << ", which is not memory allocated by malloc()";
482 else
483 os << "not memory allocated by malloc()";
484 }
485 } else {
486 os << "Argument to free() is ";
487 if (SummarizeValue(os, ArgVal))
488 os << ", which is not memory allocated by malloc()";
489 else
490 os << "not memory allocated by malloc()";
491 }
492
Jordy Rose31041242010-06-08 22:59:01 +0000493 EnhancedBugReport *R = new EnhancedBugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000494 R->addRange(range);
495 C.EmitReport(R);
496 }
497}
498
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000499void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
500 const GRState *state = C.getState();
501 const Expr *Arg0 = CE->getArg(0);
Ted Kremenek13976632010-02-08 16:18:51 +0000502 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000503
504 ValueManager &ValMgr = C.getValueManager();
505 SValuator &SVator = C.getSValuator();
506
507 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
508
509 // If the ptr is NULL, the call is equivalent to malloc(size).
510 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
511 // Hack: set the NULL symbolic region to released to suppress false warning.
512 // In the future we should add more states for allocated regions, e.g.,
513 // CheckedNull, CheckedNonNull.
514
515 SymbolRef Sym = Arg0Val.getAsLocSymbol();
516 if (Sym)
517 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
518
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000519 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
520 UndefinedVal(), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000521 C.addTransition(stateMalloc);
522 }
523
524 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
525 const Expr *Arg1 = CE->getArg(1);
526 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek13976632010-02-08 16:18:51 +0000527 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000528 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
529 ValMgr.makeIntValWithPtrWidth(0, false));
530
531 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000532 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero, 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000533 if (stateFree)
534 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
535 }
536
537 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000538 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero, 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000539 if (stateFree) {
540 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000541 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000542 UnknownVal(), stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000543 C.addTransition(stateRealloc);
544 }
545 }
546 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000547}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000548
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000549void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
550 const GRState *state = C.getState();
551
552 ValueManager &ValMgr = C.getValueManager();
553 SValuator &SVator = C.getSValuator();
554
555 SVal Count = state->getSVal(CE->getArg(0));
556 SVal EleSize = state->getSVal(CE->getArg(1));
557 SVal TotalSize = SVator.EvalBinOp(state, BinaryOperator::Mul, Count, EleSize,
558 ValMgr.getContext().getSizeType());
559
560 SVal Zero = ValMgr.makeZeroVal(ValMgr.getContext().CharTy);
561
562 state = MallocMemAux(C, CE, TotalSize, Zero, state);
563 C.addTransition(state);
564}
565
Jordy Rose7dadf792010-07-01 20:09:55 +0000566void MallocChecker::EvalDeadSymbols(CheckerContext &C,SymbolReaper &SymReaper) {
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000567 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
568 E = SymReaper.dead_end(); I != E; ++I) {
569 SymbolRef Sym = *I;
570 const GRState *state = C.getState();
571 const RefState *RS = state->get<RegionState>(Sym);
572 if (!RS)
573 return;
574
Zhongxing Xu243fde92009-11-17 07:54:15 +0000575 if (RS->isAllocated()) {
Ted Kremenek8c912302010-08-06 21:12:53 +0000576 if (ExplodedNode *N = C.GenerateSink()) {
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000577 if (!BT_Leak)
578 BT_Leak = new BuiltinBug("Memory leak",
579 "Allocated memory never released. Potential memory leak.");
580 // FIXME: where it is allocated.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000581 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000582 C.EmitReport(R);
583 }
584 }
585 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000586}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000587
588void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
589 GRExprEngine &Eng) {
Zhongxing Xuf605aae2009-11-22 13:22:34 +0000590 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000591 const GRState *state = B.getState();
592 typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap;
593 SymMap M = state->get<RegionState>();
594
595 for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
596 RefState RS = I->second;
597 if (RS.isAllocated()) {
598 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
599 if (N) {
600 if (!BT_Leak)
601 BT_Leak = new BuiltinBug("Memory leak",
602 "Allocated memory never released. Potential memory leak.");
603 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
604 Eng.getBugReporter().EmitReport(R);
605 }
606 }
607 }
608}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000609
610void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
611 const Expr *RetE = S->getRetValue();
612 if (!RetE)
613 return;
614
615 const GRState *state = C.getState();
616
Ted Kremenek13976632010-02-08 16:18:51 +0000617 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000618
619 if (!Sym)
620 return;
621
622 const RefState *RS = state->get<RegionState>(Sym);
623 if (!RS)
624 return;
625
626 // FIXME: check other cases.
627 if (RS->isAllocated())
628 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
629
Ted Kremenek19d67b52009-11-23 22:22:01 +0000630 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000631}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000632
633const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
Jordy Rose72905cf2010-08-04 07:10:57 +0000634 bool Assumption,
635 bool * /* respondsToCallback */) {
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000636 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
637 // FIXME: should also check symbols assumed to non-null.
638
639 RegionStateTy RS = state->get<RegionState>();
640
641 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
642 if (state->getSymVal(I.getKey()))
643 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
644 }
645
646 return state;
647}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000648
649// Check if the location is a freed symbolic region.
650void MallocChecker::VisitLocation(CheckerContext &C, const Stmt *S, SVal l) {
651 SymbolRef Sym = l.getLocSymbolInBase();
652 if (Sym) {
653 const RefState *RS = C.getState()->get<RegionState>(Sym);
Ted Kremenekcea68652010-08-06 21:12:49 +0000654 if (RS && RS->isReleased()) {
655 if (ExplodedNode *N = C.GenerateNode()) {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000656 if (!BT_UseFree)
657 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
658 " it is freed.");
659
660 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
661 N);
662 C.EmitReport(R);
663 }
Ted Kremenekcea68652010-08-06 21:12:49 +0000664 }
Zhongxing Xuc8023782010-03-10 04:58:55 +0000665 }
666}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000667
668void MallocChecker::PreVisitBind(CheckerContext &C,
669 const Stmt *AssignE,
670 const Stmt *StoreE,
671 SVal location,
672 SVal val) {
673 // The PreVisitBind implements the same algorithm as already used by the
674 // Objective C ownership checker: if the pointer escaped from this scope by
675 // assignment, let it go. However, assigning to fields of a stack-storage
676 // structure does not transfer ownership.
677
678 const GRState *state = C.getState();
679 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
680
681 // Check for null dereferences.
682 if (!isa<Loc>(l))
683 return;
684
685 // Before checking if the state is null, check if 'val' has a RefState.
686 // Only then should we check for null and bifurcate the state.
687 SymbolRef Sym = val.getLocSymbolInBase();
688 if (Sym) {
689 if (const RefState *RS = state->get<RegionState>(Sym)) {
690 // If ptr is NULL, no operation is performed.
691 const GRState *notNullState, *nullState;
692 llvm::tie(notNullState, nullState) = state->Assume(l);
693
694 // Generate a transition for 'nullState' to record the assumption
695 // that the state was null.
696 if (nullState)
697 C.addTransition(nullState);
698
699 if (!notNullState)
700 return;
701
702 if (RS->isAllocated()) {
703 // Something we presently own is being assigned somewhere.
704 const MemRegion *AR = location.getAsRegion();
705 if (!AR)
706 return;
707 AR = AR->StripCasts()->getBaseRegion();
708 do {
709 // If it is on the stack, we still own it.
710 if (AR->hasStackNonParametersStorage())
711 break;
712
713 // If the state can't represent this binding, we still own it.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000714 if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
715 UnknownVal())))
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000716 break;
717
718 // We no longer own this pointer.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000719 notNullState =
720 notNullState->set<RegionState>(Sym,
721 RefState::getRelinquished(StoreE));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000722 }
723 while (false);
724 }
725 C.addTransition(notNullState);
726 }
727 }
728}