blob: 0076e1e868711dcc247d12aba57b8bbdbcd3030b [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);
Jordy Rose2a479922010-08-12 08:54:03 +0000103 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
104 const OwnershipAttr* Att);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000105 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000106 const GRState *state, unsigned Num, bool Hold);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000107
108 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000109 void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000110
111 bool SummarizeValue(llvm::raw_ostream& os, SVal V);
112 bool SummarizeRegion(llvm::raw_ostream& os, const MemRegion *MR);
113 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000114};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000115} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000116
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000117typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
118
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000119namespace clang {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000120 template <>
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000121 struct GRStateTrait<RegionState>
Jordy Rose09cef092010-08-18 04:26:59 +0000122 : public GRStatePartialTrait<RegionStateTy> {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000123 static void *GDMIndex() { return MallocChecker::getTag(); }
124 };
125}
126
Zhongxing Xu7b760962009-11-13 07:25:27 +0000127void clang::RegisterMallocChecker(GRExprEngine &Eng) {
128 Eng.registerCheck(new MallocChecker());
129}
130
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000131void *MallocChecker::getTag() {
132 static int x;
133 return &x;
134}
135
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000136bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
137 const GRState *state = C.getState();
138 const Expr *Callee = CE->getCallee();
Ted Kremenek13976632010-02-08 16:18:51 +0000139 SVal L = state->getSVal(Callee);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000140
141 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000142 if (!FD)
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000143 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000144
145 ASTContext &Ctx = C.getASTContext();
146 if (!II_malloc)
147 II_malloc = &Ctx.Idents.get("malloc");
148 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000149 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000150 if (!II_realloc)
151 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000152 if (!II_calloc)
153 II_calloc = &Ctx.Idents.get("calloc");
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000154
155 if (FD->getIdentifier() == II_malloc) {
156 MallocMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000157 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000158 }
159
160 if (FD->getIdentifier() == II_free) {
161 FreeMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000162 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000163 }
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000164
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000165 if (FD->getIdentifier() == II_realloc) {
166 ReallocMem(C, CE);
167 return true;
168 }
169
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000170 if (FD->getIdentifier() == II_calloc) {
171 CallocMem(C, CE);
172 return true;
173 }
174
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000175 // Check all the attributes, if there are any.
176 // There can be multiple of these attributes.
177 bool rv = false;
178 if (FD->hasAttrs()) {
179 for (const Attr *attr = FD->getAttrs(); attr; attr = attr->getNext()) {
Jordy Rose2a479922010-08-12 08:54:03 +0000180 switch (attr->getKind()) {
181 case attr::OwnershipReturns:
182 MallocMemReturnsAttr(C, CE, cast<OwnershipAttr>(attr));
183 rv = true;
184 break;
185 case attr::OwnershipTakes:
186 case attr::OwnershipHolds:
187 FreeMemAttr(C, CE, cast<OwnershipAttr>(attr));
188 rv = true;
189 break;
190 default:
191 // Ignore non-ownership attributes.
192 break;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000193 }
194 }
195 }
196 return rv;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000197}
198
199void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000200 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
201 C.getState());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000202 C.addTransition(state);
203}
204
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000205void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
206 const OwnershipAttr* Att) {
207 if (!Att->isModule("malloc"))
208 return;
209
210 const unsigned *I = Att->begin(), *E = Att->end();
211 if (I != E) {
212 const GRState *state =
213 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
214 C.addTransition(state);
215 return;
216 }
217 const GRState *state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
218 C.getState());
219 C.addTransition(state);
220}
221
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000222const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
223 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000224 SVal Size, SVal Init,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000225 const GRState *state) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000226 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
227 ValueManager &ValMgr = C.getValueManager();
228
Jordy Rose32f26562010-07-04 00:00:41 +0000229 // Set the return value.
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000230 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
Jordy Rose32f26562010-07-04 00:00:41 +0000231 state = state->BindExpr(CE, RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000232
Jordy Rose32f26562010-07-04 00:00:41 +0000233 // Fill the region with the initialization value.
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000234 state = state->bindDefault(RetVal, Init);
235
Jordy Rose32f26562010-07-04 00:00:41 +0000236 // Set the region's extent equal to the Size parameter.
237 const SymbolicRegion *R = cast<SymbolicRegion>(RetVal.getAsRegion());
238 DefinedOrUnknownSVal Extent = R->getExtent(ValMgr);
239 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
240
241 SValuator &SVator = ValMgr.getSValuator();
242 DefinedOrUnknownSVal ExtentMatchesSize =
243 SVator.EvalEQ(state, Extent, DefinedSize);
244 state = state->Assume(ExtentMatchesSize, true);
245
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000246 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000247 assert(Sym);
248 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000249 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000250}
251
252void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000253 const GRState *state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000254
255 if (state)
256 C.addTransition(state);
257}
258
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000259void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Jordy Rose2a479922010-08-12 08:54:03 +0000260 const OwnershipAttr* Att) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000261 if (!Att->isModule("malloc"))
262 return;
263
264 for (const unsigned *I = Att->begin(), *E = Att->end(); I != E; ++I) {
265 const GRState *state =
Jordy Rose2a479922010-08-12 08:54:03 +0000266 FreeMemAux(C, CE, C.getState(), *I, isa<OwnershipHoldsAttr>(Att));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000267 if (state)
268 C.addTransition(state);
269 }
270}
271
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000272const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000273 const GRState *state, unsigned Num,
274 bool Hold) {
275 const Expr *ArgExpr = CE->getArg(Num);
Jordy Rose43859f62010-06-07 19:32:37 +0000276 SVal ArgVal = state->getSVal(ArgExpr);
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000277
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000278 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
279
280 // Check for null dereferences.
281 if (!isa<Loc>(location))
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000282 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000283
284 // FIXME: Technically using 'Assume' here can result in a path
285 // bifurcation. In such cases we need to return two states, not just one.
286 const GRState *notNullState, *nullState;
287 llvm::tie(notNullState, nullState) = state->Assume(location);
288
289 // The explicit NULL case, no operation is performed.
290 if (nullState && !notNullState)
291 return nullState;
292
293 assert(notNullState);
294
Jordy Rose43859f62010-06-07 19:32:37 +0000295 // Unknown values could easily be okay
296 // Undefined values are handled elsewhere
297 if (ArgVal.isUnknownOrUndef())
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000298 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000299
Jordy Rose43859f62010-06-07 19:32:37 +0000300 const MemRegion *R = ArgVal.getAsRegion();
301
302 // Nonlocs can't be freed, of course.
303 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
304 if (!R) {
305 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
306 return NULL;
307 }
308
309 R = R->StripCasts();
310
311 // Blocks might show up as heap data, but should not be free()d
312 if (isa<BlockDataRegion>(R)) {
313 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
314 return NULL;
315 }
316
317 const MemSpaceRegion *MS = R->getMemorySpace();
318
319 // Parameters, locals, statics, and globals shouldn't be freed.
320 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
321 // FIXME: at the time this code was written, malloc() regions were
322 // represented by conjured symbols, which are all in UnknownSpaceRegion.
323 // This means that there isn't actually anything from HeapSpaceRegion
324 // that should be freed, even though we allow it here.
325 // Of course, free() can work on memory allocated outside the current
326 // function, so UnknownSpaceRegion is always a possibility.
327 // False negatives are better than false positives.
328
329 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
330 return NULL;
331 }
332
333 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
334 // Various cases could lead to non-symbol values here.
335 // For now, ignore them.
336 if (!SR)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000337 return notNullState;
Jordy Rose43859f62010-06-07 19:32:37 +0000338
339 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000340 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000341
342 // If the symbol has not been tracked, return. This is possible when free() is
343 // called on a pointer that does not get its pointee directly from malloc().
344 // Full support of this requires inter-procedural analysis.
345 if (!RS)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000346 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000347
348 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000349 if (RS->isReleased()) {
Ted Kremenek8c912302010-08-06 21:12:53 +0000350 if (ExplodedNode *N = C.GenerateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000351 if (!BT_DoubleFree)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000352 BT_DoubleFree
353 = new BuiltinBug("Double free",
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000354 "Try to free a memory block that has been released");
355 // FIXME: should find where it's freed last time.
356 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000357 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000358 C.EmitReport(R);
359 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000360 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000361 }
362
363 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000364 if (Hold)
365 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
366 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000367}
368
Jordy Rose43859f62010-06-07 19:32:37 +0000369bool MallocChecker::SummarizeValue(llvm::raw_ostream& os, SVal V) {
370 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
371 os << "an integer (" << IntVal->getValue() << ")";
372 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
373 os << "a constant address (" << ConstAddr->getValue() << ")";
374 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
375 os << "the address of the label '"
376 << Label->getLabel()->getID()->getName()
377 << "'";
378 else
379 return false;
380
381 return true;
382}
383
384bool MallocChecker::SummarizeRegion(llvm::raw_ostream& os,
385 const MemRegion *MR) {
386 switch (MR->getKind()) {
387 case MemRegion::FunctionTextRegionKind: {
388 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
389 if (FD)
390 os << "the address of the function '" << FD << "'";
391 else
392 os << "the address of a function";
393 return true;
394 }
395 case MemRegion::BlockTextRegionKind:
396 os << "block text";
397 return true;
398 case MemRegion::BlockDataRegionKind:
399 // FIXME: where the block came from?
400 os << "a block";
401 return true;
402 default: {
403 const MemSpaceRegion *MS = MR->getMemorySpace();
404
405 switch (MS->getKind()) {
406 case MemRegion::StackLocalsSpaceRegionKind: {
407 const VarRegion *VR = dyn_cast<VarRegion>(MR);
408 const VarDecl *VD;
409 if (VR)
410 VD = VR->getDecl();
411 else
412 VD = NULL;
413
414 if (VD)
415 os << "the address of the local variable '" << VD->getName() << "'";
416 else
417 os << "the address of a local stack variable";
418 return true;
419 }
420 case MemRegion::StackArgumentsSpaceRegionKind: {
421 const VarRegion *VR = dyn_cast<VarRegion>(MR);
422 const VarDecl *VD;
423 if (VR)
424 VD = VR->getDecl();
425 else
426 VD = NULL;
427
428 if (VD)
429 os << "the address of the parameter '" << VD->getName() << "'";
430 else
431 os << "the address of a parameter";
432 return true;
433 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000434 case MemRegion::NonStaticGlobalSpaceRegionKind:
435 case MemRegion::StaticGlobalSpaceRegionKind: {
Jordy Rose43859f62010-06-07 19:32:37 +0000436 const VarRegion *VR = dyn_cast<VarRegion>(MR);
437 const VarDecl *VD;
438 if (VR)
439 VD = VR->getDecl();
440 else
441 VD = NULL;
442
443 if (VD) {
444 if (VD->isStaticLocal())
445 os << "the address of the static variable '" << VD->getName() << "'";
446 else
447 os << "the address of the global variable '" << VD->getName() << "'";
448 } else
449 os << "the address of a global variable";
450 return true;
451 }
452 default:
453 return false;
454 }
455 }
456 }
457}
458
459void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
460 SourceRange range) {
Ted Kremenek8c912302010-08-06 21:12:53 +0000461 if (ExplodedNode *N = C.GenerateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000462 if (!BT_BadFree)
463 BT_BadFree = new BuiltinBug("Bad free");
464
465 llvm::SmallString<100> buf;
466 llvm::raw_svector_ostream os(buf);
467
468 const MemRegion *MR = ArgVal.getAsRegion();
469 if (MR) {
470 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
471 MR = ER->getSuperRegion();
472
473 // Special case for alloca()
474 if (isa<AllocaRegion>(MR))
475 os << "Argument to free() was allocated by alloca(), not malloc()";
476 else {
477 os << "Argument to free() is ";
478 if (SummarizeRegion(os, MR))
479 os << ", which is not memory allocated by malloc()";
480 else
481 os << "not memory allocated by malloc()";
482 }
483 } else {
484 os << "Argument to free() is ";
485 if (SummarizeValue(os, ArgVal))
486 os << ", which is not memory allocated by malloc()";
487 else
488 os << "not memory allocated by malloc()";
489 }
490
Jordy Rose31041242010-06-08 22:59:01 +0000491 EnhancedBugReport *R = new EnhancedBugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000492 R->addRange(range);
493 C.EmitReport(R);
494 }
495}
496
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000497void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
498 const GRState *state = C.getState();
499 const Expr *Arg0 = CE->getArg(0);
Ted Kremenek13976632010-02-08 16:18:51 +0000500 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000501
502 ValueManager &ValMgr = C.getValueManager();
503 SValuator &SVator = C.getSValuator();
504
505 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
506
507 // If the ptr is NULL, the call is equivalent to malloc(size).
508 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
509 // Hack: set the NULL symbolic region to released to suppress false warning.
510 // In the future we should add more states for allocated regions, e.g.,
511 // CheckedNull, CheckedNonNull.
512
513 SymbolRef Sym = Arg0Val.getAsLocSymbol();
514 if (Sym)
515 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
516
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000517 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
518 UndefinedVal(), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000519 C.addTransition(stateMalloc);
520 }
521
522 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
523 const Expr *Arg1 = CE->getArg(1);
524 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek13976632010-02-08 16:18:51 +0000525 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000526 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
527 ValMgr.makeIntValWithPtrWidth(0, false));
528
529 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000530 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero, 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000531 if (stateFree)
532 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
533 }
534
535 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000536 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero, 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000537 if (stateFree) {
538 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000539 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000540 UnknownVal(), stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000541 C.addTransition(stateRealloc);
542 }
543 }
544 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000545}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000546
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000547void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
548 const GRState *state = C.getState();
549
550 ValueManager &ValMgr = C.getValueManager();
551 SValuator &SVator = C.getSValuator();
552
553 SVal Count = state->getSVal(CE->getArg(0));
554 SVal EleSize = state->getSVal(CE->getArg(1));
555 SVal TotalSize = SVator.EvalBinOp(state, BinaryOperator::Mul, Count, EleSize,
556 ValMgr.getContext().getSizeType());
557
558 SVal Zero = ValMgr.makeZeroVal(ValMgr.getContext().CharTy);
559
560 state = MallocMemAux(C, CE, TotalSize, Zero, state);
561 C.addTransition(state);
562}
563
Jordy Rose7dadf792010-07-01 20:09:55 +0000564void MallocChecker::EvalDeadSymbols(CheckerContext &C,SymbolReaper &SymReaper) {
Zhongxing Xu173ff562010-08-15 08:19:57 +0000565 if (!SymReaper.hasDeadSymbols())
566 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000567
Zhongxing Xu173ff562010-08-15 08:19:57 +0000568 const GRState *state = C.getState();
569 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000570 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000571
572 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
573 if (SymReaper.isDead(I->first)) {
574 if (I->second.isAllocated()) {
Zhongxing Xu649a33a2010-08-17 00:36:37 +0000575 if (ExplodedNode *N = C.GenerateNode()) {
Zhongxing Xu173ff562010-08-15 08:19:57 +0000576 if (!BT_Leak)
577 BT_Leak = new BuiltinBug("Memory leak",
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000578 "Allocated memory never released. Potential memory leak.");
Zhongxing Xu173ff562010-08-15 08:19:57 +0000579 // FIXME: where it is allocated.
580 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
581 C.EmitReport(R);
582 }
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000583 }
Jordy Rose90760142010-08-18 04:33:47 +0000584
585 // Remove the dead symbol from the map.
586 RS = F.Remove(RS, I->first);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000587 }
588 }
Jordy Rose90760142010-08-18 04:33:47 +0000589
590 state = state->set<RegionState>(RS);
591 C.GenerateNode(state);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000592}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000593
594void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
595 GRExprEngine &Eng) {
Zhongxing Xuf605aae2009-11-22 13:22:34 +0000596 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000597 const GRState *state = B.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000598 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000599
Jordy Rose09cef092010-08-18 04:26:59 +0000600 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000601 RefState RS = I->second;
602 if (RS.isAllocated()) {
603 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
604 if (N) {
605 if (!BT_Leak)
606 BT_Leak = new BuiltinBug("Memory leak",
607 "Allocated memory never released. Potential memory leak.");
608 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
609 Eng.getBugReporter().EmitReport(R);
610 }
611 }
612 }
613}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000614
615void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
616 const Expr *RetE = S->getRetValue();
617 if (!RetE)
618 return;
619
620 const GRState *state = C.getState();
621
Ted Kremenek13976632010-02-08 16:18:51 +0000622 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000623
624 if (!Sym)
625 return;
626
627 const RefState *RS = state->get<RegionState>(Sym);
628 if (!RS)
629 return;
630
631 // FIXME: check other cases.
632 if (RS->isAllocated())
633 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
634
Ted Kremenek19d67b52009-11-23 22:22:01 +0000635 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000636}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000637
638const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
Jordy Rose72905cf2010-08-04 07:10:57 +0000639 bool Assumption,
640 bool * /* respondsToCallback */) {
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000641 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
642 // FIXME: should also check symbols assumed to non-null.
643
644 RegionStateTy RS = state->get<RegionState>();
645
646 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
647 if (state->getSymVal(I.getKey()))
648 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
649 }
650
651 return state;
652}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000653
654// Check if the location is a freed symbolic region.
655void MallocChecker::VisitLocation(CheckerContext &C, const Stmt *S, SVal l) {
656 SymbolRef Sym = l.getLocSymbolInBase();
657 if (Sym) {
658 const RefState *RS = C.getState()->get<RegionState>(Sym);
Ted Kremenekcea68652010-08-06 21:12:49 +0000659 if (RS && RS->isReleased()) {
660 if (ExplodedNode *N = C.GenerateNode()) {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000661 if (!BT_UseFree)
662 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
663 " it is freed.");
664
665 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
666 N);
667 C.EmitReport(R);
668 }
Ted Kremenekcea68652010-08-06 21:12:49 +0000669 }
Zhongxing Xuc8023782010-03-10 04:58:55 +0000670 }
671}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000672
673void MallocChecker::PreVisitBind(CheckerContext &C,
674 const Stmt *AssignE,
675 const Stmt *StoreE,
676 SVal location,
677 SVal val) {
678 // The PreVisitBind implements the same algorithm as already used by the
679 // Objective C ownership checker: if the pointer escaped from this scope by
680 // assignment, let it go. However, assigning to fields of a stack-storage
681 // structure does not transfer ownership.
682
683 const GRState *state = C.getState();
684 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
685
686 // Check for null dereferences.
687 if (!isa<Loc>(l))
688 return;
689
690 // Before checking if the state is null, check if 'val' has a RefState.
691 // Only then should we check for null and bifurcate the state.
692 SymbolRef Sym = val.getLocSymbolInBase();
693 if (Sym) {
694 if (const RefState *RS = state->get<RegionState>(Sym)) {
695 // If ptr is NULL, no operation is performed.
696 const GRState *notNullState, *nullState;
697 llvm::tie(notNullState, nullState) = state->Assume(l);
698
699 // Generate a transition for 'nullState' to record the assumption
700 // that the state was null.
701 if (nullState)
702 C.addTransition(nullState);
703
704 if (!notNullState)
705 return;
706
707 if (RS->isAllocated()) {
708 // Something we presently own is being assigned somewhere.
709 const MemRegion *AR = location.getAsRegion();
710 if (!AR)
711 return;
712 AR = AR->StripCasts()->getBaseRegion();
713 do {
714 // If it is on the stack, we still own it.
715 if (AR->hasStackNonParametersStorage())
716 break;
717
718 // If the state can't represent this binding, we still own it.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000719 if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
720 UnknownVal())))
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000721 break;
722
723 // We no longer own this pointer.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000724 notNullState =
725 notNullState->set<RegionState>(Sym,
726 RefState::getRelinquished(StoreE));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000727 }
728 while (false);
729 }
730 C.addTransition(notNullState);
731 }
732 }
733}