blob: 4ed309513e3f812fbcd7fa2b02c8d85bbad4ae8c [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 Kremenekdd0e4902010-07-31 01:52:11 +000027 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped, Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000028 const Stmt *S;
29
Zhongxing Xu7fb14642009-12-11 00:55:44 +000030public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000031 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
32
Zhongxing Xub94b81a2009-12-31 06:13:07 +000033 bool isAllocated() const { return K == AllocateUnchecked; }
Ted Kremenekdd0e4902010-07-31 01:52:11 +000034 bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000035 bool isReleased() const { return K == Released; }
36 bool isEscaped() const { return K == Escaped; }
Ted Kremenekdd0e4902010-07-31 01:52:11 +000037 bool isRelinquished() const { return K == Relinquished; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000038
39 bool operator==(const RefState &X) const {
40 return K == X.K && S == X.S;
41 }
42
Zhongxing Xub94b81a2009-12-31 06:13:07 +000043 static RefState getAllocateUnchecked(const Stmt *s) {
44 return RefState(AllocateUnchecked, s);
45 }
46 static RefState getAllocateFailed() {
47 return RefState(AllocateFailed, 0);
48 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000049 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
50 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdd0e4902010-07-31 01:52:11 +000051 static RefState getRelinquished(const Stmt *s) { return RefState(Relinquished, s); }
Zhongxing Xu243fde92009-11-17 07:54:15 +000052
53 void Profile(llvm::FoldingSetNodeID &ID) const {
54 ID.AddInteger(K);
55 ID.AddPointer(S);
56 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000057};
58
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000059class RegionState {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +000060
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000061class MallocChecker : public CheckerVisitor<MallocChecker> {
Zhongxing Xu589c0f22009-11-12 08:38:56 +000062 BuiltinBug *BT_DoubleFree;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +000063 BuiltinBug *BT_Leak;
Zhongxing Xuc8023782010-03-10 04:58:55 +000064 BuiltinBug *BT_UseFree;
Ted Kremenekdd0e4902010-07-31 01:52:11 +000065 BuiltinBug *BT_UseRelinquished;
Jordy Rose43859f62010-06-07 19:32:37 +000066 BuiltinBug *BT_BadFree;
Zhongxing Xua5ce9662010-06-01 03:01:33 +000067 IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000068
69public:
Zhongxing Xud9c84c82009-12-12 12:29:38 +000070 MallocChecker()
Ted Kremenekdd0e4902010-07-31 01:52:11 +000071 : BT_DoubleFree(0), BT_Leak(0), BT_UseFree(0), BT_UseRelinquished(0), BT_BadFree(0),
Zhongxing Xua5ce9662010-06-01 03:01:33 +000072 II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Zhongxing Xu589c0f22009-11-12 08:38:56 +000073 static void *getTag();
Zhongxing Xua49c6b72009-12-11 03:09:01 +000074 bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
Jordy Rose7dadf792010-07-01 20:09:55 +000075 void EvalDeadSymbols(CheckerContext &C, SymbolReaper &SymReaper);
Zhongxing Xu243fde92009-11-17 07:54:15 +000076 void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +000077 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000078 const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption);
Zhongxing Xuc8023782010-03-10 04:58:55 +000079 void VisitLocation(CheckerContext &C, const Stmt *S, SVal l);
Ted Kremenekdd0e4902010-07-31 01:52:11 +000080 virtual void PreVisitBind(CheckerContext &C, const Stmt *AssignE,
81 const Stmt *StoreE, SVal location,
82 SVal val);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000083
Zhongxing Xu7b760962009-11-13 07:25:27 +000084private:
Zhongxing Xu589c0f22009-11-12 08:38:56 +000085 void MallocMem(CheckerContext &C, const CallExpr *CE);
Ted Kremenekdd0e4902010-07-31 01:52:11 +000086 void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE, const OwnershipAttr* Att);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000087 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +000088 const Expr *SizeEx, SVal Init,
89 const GRState *state) {
90 return MallocMemAux(C, CE, state->getSVal(SizeEx), Init, state);
91 }
92 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
93 SVal SizeEx, SVal Init,
94 const GRState *state);
95
Zhongxing Xu589c0f22009-11-12 08:38:56 +000096 void FreeMem(CheckerContext &C, const CallExpr *CE);
Ted Kremenekdd0e4902010-07-31 01:52:11 +000097 void FreeMemAttr(CheckerContext &C, const CallExpr *CE, const OwnershipAttr* Att);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000098 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +000099 const GRState *state, unsigned Num, bool Hold);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000100
101 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000102 void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000103
104 bool SummarizeValue(llvm::raw_ostream& os, SVal V);
105 bool SummarizeRegion(llvm::raw_ostream& os, const MemRegion *MR);
106 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000107};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000108} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000109
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000110typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
111
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000112namespace clang {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000113 template <>
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000114 struct GRStateTrait<RegionState>
115 : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > {
116 static void *GDMIndex() { return MallocChecker::getTag(); }
117 };
118}
119
Zhongxing Xu7b760962009-11-13 07:25:27 +0000120void clang::RegisterMallocChecker(GRExprEngine &Eng) {
121 Eng.registerCheck(new MallocChecker());
122}
123
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000124void *MallocChecker::getTag() {
125 static int x;
126 return &x;
127}
128
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000129bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
130 const GRState *state = C.getState();
131 const Expr *Callee = CE->getCallee();
Ted Kremenek13976632010-02-08 16:18:51 +0000132 SVal L = state->getSVal(Callee);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000133
134 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000135 if (!FD)
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000136 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000137
138 ASTContext &Ctx = C.getASTContext();
139 if (!II_malloc)
140 II_malloc = &Ctx.Idents.get("malloc");
141 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000142 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000143 if (!II_realloc)
144 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000145 if (!II_calloc)
146 II_calloc = &Ctx.Idents.get("calloc");
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000147
148 if (FD->getIdentifier() == II_malloc) {
149 MallocMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000150 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000151 }
152
153 if (FD->getIdentifier() == II_free) {
154 FreeMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000155 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000156 }
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000157
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000158 if (FD->getIdentifier() == II_realloc) {
159 ReallocMem(C, CE);
160 return true;
161 }
162
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000163 if (FD->getIdentifier() == II_calloc) {
164 CallocMem(C, CE);
165 return true;
166 }
167
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000168 // Check all the attributes, if there are any.
169 // There can be multiple of these attributes.
170 bool rv = false;
171 if (FD->hasAttrs()) {
172 for (const Attr *attr = FD->getAttrs(); attr; attr = attr->getNext()) {
173 if(const OwnershipAttr* Att = dyn_cast<OwnershipAttr>(attr)) {
174 switch (Att->getKind()) {
175 case OwnershipAttr::Returns: {
176 MallocMemReturnsAttr(C, CE, Att);
177 rv = true;
178 break;
179 }
180 case OwnershipAttr::Takes:
181 case OwnershipAttr::Holds: {
182 FreeMemAttr(C, CE, Att);
183 rv = true;
184 break;
185 }
186 default:
187 break;
188 }
189 }
190 }
191 }
192 return rv;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000193}
194
195void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000196 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
197 C.getState());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000198 C.addTransition(state);
199}
200
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000201void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
202 const OwnershipAttr* Att) {
203 if (!Att->isModule("malloc"))
204 return;
205
206 const unsigned *I = Att->begin(), *E = Att->end();
207 if (I != E) {
208 const GRState *state =
209 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
210 C.addTransition(state);
211 return;
212 }
213 const GRState *state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
214 C.getState());
215 C.addTransition(state);
216}
217
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000218const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
219 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000220 SVal Size, SVal Init,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000221 const GRState *state) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000222 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
223 ValueManager &ValMgr = C.getValueManager();
224
Jordy Rose32f26562010-07-04 00:00:41 +0000225 // Set the return value.
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000226 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
Jordy Rose32f26562010-07-04 00:00:41 +0000227 state = state->BindExpr(CE, RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000228
Jordy Rose32f26562010-07-04 00:00:41 +0000229 // Fill the region with the initialization value.
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000230 state = state->bindDefault(RetVal, Init);
231
Jordy Rose32f26562010-07-04 00:00:41 +0000232 // Set the region's extent equal to the Size parameter.
233 const SymbolicRegion *R = cast<SymbolicRegion>(RetVal.getAsRegion());
234 DefinedOrUnknownSVal Extent = R->getExtent(ValMgr);
235 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
236
237 SValuator &SVator = ValMgr.getSValuator();
238 DefinedOrUnknownSVal ExtentMatchesSize =
239 SVator.EvalEQ(state, Extent, DefinedSize);
240 state = state->Assume(ExtentMatchesSize, true);
241
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000242 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000243 assert(Sym);
244 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000245 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000246}
247
248void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000249 const GRState *state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000250
251 if (state)
252 C.addTransition(state);
253}
254
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000255void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
256 const OwnershipAttr* Att) {
257 if (!Att->isModule("malloc"))
258 return;
259
260 for (const unsigned *I = Att->begin(), *E = Att->end(); I != E; ++I) {
261 const GRState *state =
262 FreeMemAux(C, CE, C.getState(), *I, Att->isKind(OwnershipAttr::Holds));
263 if (state)
264 C.addTransition(state);
265 }
266}
267
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000268const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000269 const GRState *state, unsigned Num,
270 bool Hold) {
271 const Expr *ArgExpr = CE->getArg(Num);
Jordy Rose43859f62010-06-07 19:32:37 +0000272 SVal ArgVal = state->getSVal(ArgExpr);
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000273
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000274 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
275
276 // Check for null dereferences.
277 if (!isa<Loc>(location))
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000278 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000279
280 // FIXME: Technically using 'Assume' here can result in a path
281 // bifurcation. In such cases we need to return two states, not just one.
282 const GRState *notNullState, *nullState;
283 llvm::tie(notNullState, nullState) = state->Assume(location);
284
285 // The explicit NULL case, no operation is performed.
286 if (nullState && !notNullState)
287 return nullState;
288
289 assert(notNullState);
290
Jordy Rose43859f62010-06-07 19:32:37 +0000291 // Unknown values could easily be okay
292 // Undefined values are handled elsewhere
293 if (ArgVal.isUnknownOrUndef())
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000294 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000295
Jordy Rose43859f62010-06-07 19:32:37 +0000296 const MemRegion *R = ArgVal.getAsRegion();
297
298 // Nonlocs can't be freed, of course.
299 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
300 if (!R) {
301 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
302 return NULL;
303 }
304
305 R = R->StripCasts();
306
307 // Blocks might show up as heap data, but should not be free()d
308 if (isa<BlockDataRegion>(R)) {
309 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
310 return NULL;
311 }
312
313 const MemSpaceRegion *MS = R->getMemorySpace();
314
315 // Parameters, locals, statics, and globals shouldn't be freed.
316 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
317 // FIXME: at the time this code was written, malloc() regions were
318 // represented by conjured symbols, which are all in UnknownSpaceRegion.
319 // This means that there isn't actually anything from HeapSpaceRegion
320 // that should be freed, even though we allow it here.
321 // Of course, free() can work on memory allocated outside the current
322 // function, so UnknownSpaceRegion is always a possibility.
323 // False negatives are better than false positives.
324
325 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
326 return NULL;
327 }
328
329 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
330 // Various cases could lead to non-symbol values here.
331 // For now, ignore them.
332 if (!SR)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000333 return notNullState;
Jordy Rose43859f62010-06-07 19:32:37 +0000334
335 SymbolRef Sym = SR->getSymbol();
336
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000337 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000338
339 // If the symbol has not been tracked, return. This is possible when free() is
340 // called on a pointer that does not get its pointee directly from malloc().
341 // Full support of this requires inter-procedural analysis.
342 if (!RS)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000343 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000344
345 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000346 if (RS->isReleased()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000347 ExplodedNode *N = C.GenerateSink();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000348 if (N) {
349 if (!BT_DoubleFree)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000350 BT_DoubleFree
351 = new BuiltinBug("Double free",
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000352 "Try to free a memory block that has been released");
353 // FIXME: should find where it's freed last time.
354 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000355 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000356 C.EmitReport(R);
357 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000358 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000359 }
360
361 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000362 if (Hold)
363 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
364 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000365}
366
Jordy Rose43859f62010-06-07 19:32:37 +0000367bool MallocChecker::SummarizeValue(llvm::raw_ostream& os, SVal V) {
368 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
369 os << "an integer (" << IntVal->getValue() << ")";
370 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
371 os << "a constant address (" << ConstAddr->getValue() << ")";
372 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
373 os << "the address of the label '"
374 << Label->getLabel()->getID()->getName()
375 << "'";
376 else
377 return false;
378
379 return true;
380}
381
382bool MallocChecker::SummarizeRegion(llvm::raw_ostream& os,
383 const MemRegion *MR) {
384 switch (MR->getKind()) {
385 case MemRegion::FunctionTextRegionKind: {
386 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
387 if (FD)
388 os << "the address of the function '" << FD << "'";
389 else
390 os << "the address of a function";
391 return true;
392 }
393 case MemRegion::BlockTextRegionKind:
394 os << "block text";
395 return true;
396 case MemRegion::BlockDataRegionKind:
397 // FIXME: where the block came from?
398 os << "a block";
399 return true;
400 default: {
401 const MemSpaceRegion *MS = MR->getMemorySpace();
402
403 switch (MS->getKind()) {
404 case MemRegion::StackLocalsSpaceRegionKind: {
405 const VarRegion *VR = dyn_cast<VarRegion>(MR);
406 const VarDecl *VD;
407 if (VR)
408 VD = VR->getDecl();
409 else
410 VD = NULL;
411
412 if (VD)
413 os << "the address of the local variable '" << VD->getName() << "'";
414 else
415 os << "the address of a local stack variable";
416 return true;
417 }
418 case MemRegion::StackArgumentsSpaceRegionKind: {
419 const VarRegion *VR = dyn_cast<VarRegion>(MR);
420 const VarDecl *VD;
421 if (VR)
422 VD = VR->getDecl();
423 else
424 VD = NULL;
425
426 if (VD)
427 os << "the address of the parameter '" << VD->getName() << "'";
428 else
429 os << "the address of a parameter";
430 return true;
431 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000432 case MemRegion::NonStaticGlobalSpaceRegionKind:
433 case MemRegion::StaticGlobalSpaceRegionKind: {
Jordy Rose43859f62010-06-07 19:32:37 +0000434 const VarRegion *VR = dyn_cast<VarRegion>(MR);
435 const VarDecl *VD;
436 if (VR)
437 VD = VR->getDecl();
438 else
439 VD = NULL;
440
441 if (VD) {
442 if (VD->isStaticLocal())
443 os << "the address of the static variable '" << VD->getName() << "'";
444 else
445 os << "the address of the global variable '" << VD->getName() << "'";
446 } else
447 os << "the address of a global variable";
448 return true;
449 }
450 default:
451 return false;
452 }
453 }
454 }
455}
456
457void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
458 SourceRange range) {
459 ExplodedNode *N = C.GenerateSink();
460 if (N) {
461 if (!BT_BadFree)
462 BT_BadFree = new BuiltinBug("Bad free");
463
464 llvm::SmallString<100> buf;
465 llvm::raw_svector_ostream os(buf);
466
467 const MemRegion *MR = ArgVal.getAsRegion();
468 if (MR) {
469 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
470 MR = ER->getSuperRegion();
471
472 // Special case for alloca()
473 if (isa<AllocaRegion>(MR))
474 os << "Argument to free() was allocated by alloca(), not malloc()";
475 else {
476 os << "Argument to free() is ";
477 if (SummarizeRegion(os, MR))
478 os << ", which is not memory allocated by malloc()";
479 else
480 os << "not memory allocated by malloc()";
481 }
482 } else {
483 os << "Argument to free() is ";
484 if (SummarizeValue(os, ArgVal))
485 os << ", which is not memory allocated by malloc()";
486 else
487 os << "not memory allocated by malloc()";
488 }
489
Jordy Rose31041242010-06-08 22:59:01 +0000490 EnhancedBugReport *R = new EnhancedBugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000491 R->addRange(range);
492 C.EmitReport(R);
493 }
494}
495
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000496void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
497 const GRState *state = C.getState();
498 const Expr *Arg0 = CE->getArg(0);
Ted Kremenek13976632010-02-08 16:18:51 +0000499 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000500
501 ValueManager &ValMgr = C.getValueManager();
502 SValuator &SVator = C.getSValuator();
503
504 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
505
506 // If the ptr is NULL, the call is equivalent to malloc(size).
507 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
508 // Hack: set the NULL symbolic region to released to suppress false warning.
509 // In the future we should add more states for allocated regions, e.g.,
510 // CheckedNull, CheckedNonNull.
511
512 SymbolRef Sym = Arg0Val.getAsLocSymbol();
513 if (Sym)
514 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
515
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000516 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
517 UndefinedVal(), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000518 C.addTransition(stateMalloc);
519 }
520
521 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
522 const Expr *Arg1 = CE->getArg(1);
523 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek13976632010-02-08 16:18:51 +0000524 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000525 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
526 ValMgr.makeIntValWithPtrWidth(0, false));
527
528 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000529 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero, 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000530 if (stateFree)
531 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
532 }
533
534 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000535 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero, 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000536 if (stateFree) {
537 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000538 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000539 UnknownVal(), stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000540 C.addTransition(stateRealloc);
541 }
542 }
543 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000544}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000545
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000546void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
547 const GRState *state = C.getState();
548
549 ValueManager &ValMgr = C.getValueManager();
550 SValuator &SVator = C.getSValuator();
551
552 SVal Count = state->getSVal(CE->getArg(0));
553 SVal EleSize = state->getSVal(CE->getArg(1));
554 SVal TotalSize = SVator.EvalBinOp(state, BinaryOperator::Mul, Count, EleSize,
555 ValMgr.getContext().getSizeType());
556
557 SVal Zero = ValMgr.makeZeroVal(ValMgr.getContext().CharTy);
558
559 state = MallocMemAux(C, CE, TotalSize, Zero, state);
560 C.addTransition(state);
561}
562
Jordy Rose7dadf792010-07-01 20:09:55 +0000563void MallocChecker::EvalDeadSymbols(CheckerContext &C,SymbolReaper &SymReaper) {
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000564 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
565 E = SymReaper.dead_end(); I != E; ++I) {
566 SymbolRef Sym = *I;
567 const GRState *state = C.getState();
568 const RefState *RS = state->get<RegionState>(Sym);
569 if (!RS)
570 return;
571
Zhongxing Xu243fde92009-11-17 07:54:15 +0000572 if (RS->isAllocated()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000573 ExplodedNode *N = C.GenerateSink();
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000574 if (N) {
575 if (!BT_Leak)
576 BT_Leak = new BuiltinBug("Memory leak",
577 "Allocated memory never released. Potential memory leak.");
578 // FIXME: where it is allocated.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000579 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000580 C.EmitReport(R);
581 }
582 }
583 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000584}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000585
586void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
587 GRExprEngine &Eng) {
Zhongxing Xuf605aae2009-11-22 13:22:34 +0000588 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000589 const GRState *state = B.getState();
590 typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap;
591 SymMap M = state->get<RegionState>();
592
593 for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
594 RefState RS = I->second;
595 if (RS.isAllocated()) {
596 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
597 if (N) {
598 if (!BT_Leak)
599 BT_Leak = new BuiltinBug("Memory leak",
600 "Allocated memory never released. Potential memory leak.");
601 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
602 Eng.getBugReporter().EmitReport(R);
603 }
604 }
605 }
606}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000607
608void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
609 const Expr *RetE = S->getRetValue();
610 if (!RetE)
611 return;
612
613 const GRState *state = C.getState();
614
Ted Kremenek13976632010-02-08 16:18:51 +0000615 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000616
617 if (!Sym)
618 return;
619
620 const RefState *RS = state->get<RegionState>(Sym);
621 if (!RS)
622 return;
623
624 // FIXME: check other cases.
625 if (RS->isAllocated())
626 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
627
Ted Kremenek19d67b52009-11-23 22:22:01 +0000628 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000629}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000630
631const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
632 bool Assumption) {
633 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
634 // FIXME: should also check symbols assumed to non-null.
635
636 RegionStateTy RS = state->get<RegionState>();
637
638 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
639 if (state->getSymVal(I.getKey()))
640 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
641 }
642
643 return state;
644}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000645
646// Check if the location is a freed symbolic region.
647void MallocChecker::VisitLocation(CheckerContext &C, const Stmt *S, SVal l) {
648 SymbolRef Sym = l.getLocSymbolInBase();
649 if (Sym) {
650 const RefState *RS = C.getState()->get<RegionState>(Sym);
651 if (RS)
652 if (RS->isReleased()) {
653 ExplodedNode *N = C.GenerateSink();
654 if (!BT_UseFree)
655 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
656 " it is freed.");
657
658 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
659 N);
660 C.EmitReport(R);
661 }
662 }
663}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000664
665void MallocChecker::PreVisitBind(CheckerContext &C,
666 const Stmt *AssignE,
667 const Stmt *StoreE,
668 SVal location,
669 SVal val) {
670 // The PreVisitBind implements the same algorithm as already used by the
671 // Objective C ownership checker: if the pointer escaped from this scope by
672 // assignment, let it go. However, assigning to fields of a stack-storage
673 // structure does not transfer ownership.
674
675 const GRState *state = C.getState();
676 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
677
678 // Check for null dereferences.
679 if (!isa<Loc>(l))
680 return;
681
682 // Before checking if the state is null, check if 'val' has a RefState.
683 // Only then should we check for null and bifurcate the state.
684 SymbolRef Sym = val.getLocSymbolInBase();
685 if (Sym) {
686 if (const RefState *RS = state->get<RegionState>(Sym)) {
687 // If ptr is NULL, no operation is performed.
688 const GRState *notNullState, *nullState;
689 llvm::tie(notNullState, nullState) = state->Assume(l);
690
691 // Generate a transition for 'nullState' to record the assumption
692 // that the state was null.
693 if (nullState)
694 C.addTransition(nullState);
695
696 if (!notNullState)
697 return;
698
699 if (RS->isAllocated()) {
700 // Something we presently own is being assigned somewhere.
701 const MemRegion *AR = location.getAsRegion();
702 if (!AR)
703 return;
704 AR = AR->StripCasts()->getBaseRegion();
705 do {
706 // If it is on the stack, we still own it.
707 if (AR->hasStackNonParametersStorage())
708 break;
709
710 // If the state can't represent this binding, we still own it.
711 if (notNullState == (notNullState->bindLoc(cast<Loc>(location), UnknownVal())))
712 break;
713
714 // We no longer own this pointer.
715 notNullState = notNullState->set<RegionState>(Sym, RefState::getRelinquished(StoreE));
716 }
717 while (false);
718 }
719 C.addTransition(notNullState);
720 }
721 }
722}