blob: a08afc4b795921ddb55bf78c64e9134c450ca0d4 [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"
Ted Kremenek1309f9a2010-01-25 04:41:41 +000016#include "clang/Checker/PathSensitive/CheckerVisitor.h"
17#include "clang/Checker/PathSensitive/GRState.h"
18#include "clang/Checker/PathSensitive/GRStateTrait.h"
19#include "clang/Checker/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000020#include "llvm/ADT/ImmutableMap.h"
21using namespace clang;
22
23namespace {
24
Zhongxing Xu7fb14642009-12-11 00:55:44 +000025class RefState {
Zhongxing Xub94b81a2009-12-31 06:13:07 +000026 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000027 const Stmt *S;
28
Zhongxing Xu7fb14642009-12-11 00:55:44 +000029public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000030 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
31
Zhongxing Xub94b81a2009-12-31 06:13:07 +000032 bool isAllocated() const { return K == AllocateUnchecked; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000033 bool isReleased() const { return K == Released; }
34 bool isEscaped() const { return K == Escaped; }
35
36 bool operator==(const RefState &X) const {
37 return K == X.K && S == X.S;
38 }
39
Zhongxing Xub94b81a2009-12-31 06:13:07 +000040 static RefState getAllocateUnchecked(const Stmt *s) {
41 return RefState(AllocateUnchecked, s);
42 }
43 static RefState getAllocateFailed() {
44 return RefState(AllocateFailed, 0);
45 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000046 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
47 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
48
49 void Profile(llvm::FoldingSetNodeID &ID) const {
50 ID.AddInteger(K);
51 ID.AddPointer(S);
52 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000053};
54
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000055class RegionState {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +000056
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000057class MallocChecker : public CheckerVisitor<MallocChecker> {
Zhongxing Xu589c0f22009-11-12 08:38:56 +000058 BuiltinBug *BT_DoubleFree;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +000059 BuiltinBug *BT_Leak;
Zhongxing Xuc8023782010-03-10 04:58:55 +000060 BuiltinBug *BT_UseFree;
Zhongxing Xud9c84c82009-12-12 12:29:38 +000061 IdentifierInfo *II_malloc, *II_free, *II_realloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000062
63public:
Zhongxing Xud9c84c82009-12-12 12:29:38 +000064 MallocChecker()
Zhongxing Xuc8023782010-03-10 04:58:55 +000065 : BT_DoubleFree(0), BT_Leak(0), BT_UseFree(0),
66 II_malloc(0), II_free(0), II_realloc(0) {}
Zhongxing Xu589c0f22009-11-12 08:38:56 +000067 static void *getTag();
Zhongxing Xua49c6b72009-12-11 03:09:01 +000068 bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
Zhongxing Xu7b760962009-11-13 07:25:27 +000069 void EvalDeadSymbols(CheckerContext &C,const Stmt *S,SymbolReaper &SymReaper);
Zhongxing Xu243fde92009-11-17 07:54:15 +000070 void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +000071 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000072 const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption);
Zhongxing Xuc8023782010-03-10 04:58:55 +000073 void VisitLocation(CheckerContext &C, const Stmt *S, SVal l);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000074
Zhongxing Xu7b760962009-11-13 07:25:27 +000075private:
Zhongxing Xu589c0f22009-11-12 08:38:56 +000076 void MallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000077 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
Zhongxing Xu3ed04d32010-01-18 08:54:31 +000078 const Expr *SizeEx, const GRState *state);
Zhongxing Xu589c0f22009-11-12 08:38:56 +000079 void FreeMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000080 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
81 const GRState *state);
82
83 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xu589c0f22009-11-12 08:38:56 +000084};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000085} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +000086
Zhongxing Xub94b81a2009-12-31 06:13:07 +000087typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
88
Zhongxing Xu589c0f22009-11-12 08:38:56 +000089namespace clang {
Zhongxing Xu243fde92009-11-17 07:54:15 +000090 template <>
Zhongxing Xu589c0f22009-11-12 08:38:56 +000091 struct GRStateTrait<RegionState>
92 : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > {
93 static void *GDMIndex() { return MallocChecker::getTag(); }
94 };
95}
96
Zhongxing Xu7b760962009-11-13 07:25:27 +000097void clang::RegisterMallocChecker(GRExprEngine &Eng) {
98 Eng.registerCheck(new MallocChecker());
99}
100
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000101void *MallocChecker::getTag() {
102 static int x;
103 return &x;
104}
105
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000106bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
107 const GRState *state = C.getState();
108 const Expr *Callee = CE->getCallee();
Ted Kremenek13976632010-02-08 16:18:51 +0000109 SVal L = state->getSVal(Callee);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000110
111 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000112 if (!FD)
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000113 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000114
115 ASTContext &Ctx = C.getASTContext();
116 if (!II_malloc)
117 II_malloc = &Ctx.Idents.get("malloc");
118 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000119 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000120 if (!II_realloc)
121 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000122
123 if (FD->getIdentifier() == II_malloc) {
124 MallocMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000125 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000126 }
127
128 if (FD->getIdentifier() == II_free) {
129 FreeMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000130 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000131 }
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000132
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000133 if (FD->getIdentifier() == II_realloc) {
134 ReallocMem(C, CE);
135 return true;
136 }
137
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000138 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000139}
140
141void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000142 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), C.getState());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000143 C.addTransition(state);
144}
145
146const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
147 const CallExpr *CE,
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000148 const Expr *SizeEx,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000149 const GRState *state) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000150 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
151 ValueManager &ValMgr = C.getValueManager();
152
153 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
154
Ted Kremenek13976632010-02-08 16:18:51 +0000155 SVal Size = state->getSVal(SizeEx);
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000156
157 state = C.getEngine().getStoreManager().setExtent(state, RetVal.getAsRegion(),
158 Size);
159
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000160 state = state->BindExpr(CE, RetVal);
161
162 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000163 assert(Sym);
164 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000165 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000166}
167
168void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000169 const GRState *state = FreeMemAux(C, CE, C.getState());
170
171 if (state)
172 C.addTransition(state);
173}
174
175const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
176 const GRState *state) {
Ted Kremenek13976632010-02-08 16:18:51 +0000177 SVal ArgVal = state->getSVal(CE->getArg(0));
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000178
179 // If ptr is NULL, no operation is preformed.
180 if (ArgVal.isZeroConstant())
181 return state;
182
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000183 SymbolRef Sym = ArgVal.getAsLocSymbol();
184 assert(Sym);
185
186 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000187
188 // If the symbol has not been tracked, return. This is possible when free() is
189 // called on a pointer that does not get its pointee directly from malloc().
190 // Full support of this requires inter-procedural analysis.
191 if (!RS)
192 return state;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000193
194 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000195 if (RS->isReleased()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000196 ExplodedNode *N = C.GenerateSink();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000197 if (N) {
198 if (!BT_DoubleFree)
199 BT_DoubleFree = new BuiltinBug("Double free",
200 "Try to free a memory block that has been released");
201 // FIXME: should find where it's freed last time.
202 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000203 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000204 C.EmitReport(R);
205 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000206 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000207 }
208
209 // Normal free.
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000210 return state->set<RegionState>(Sym, RefState::getReleased(CE));
211}
212
213void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
214 const GRState *state = C.getState();
215 const Expr *Arg0 = CE->getArg(0);
Ted Kremenek13976632010-02-08 16:18:51 +0000216 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000217
218 ValueManager &ValMgr = C.getValueManager();
219 SValuator &SVator = C.getSValuator();
220
221 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
222
223 // If the ptr is NULL, the call is equivalent to malloc(size).
224 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
225 // Hack: set the NULL symbolic region to released to suppress false warning.
226 // In the future we should add more states for allocated regions, e.g.,
227 // CheckedNull, CheckedNonNull.
228
229 SymbolRef Sym = Arg0Val.getAsLocSymbol();
230 if (Sym)
231 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
232
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000233 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000234 C.addTransition(stateMalloc);
235 }
236
237 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
238 const Expr *Arg1 = CE->getArg(1);
239 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek13976632010-02-08 16:18:51 +0000240 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000241 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
242 ValMgr.makeIntValWithPtrWidth(0, false));
243
244 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
245 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero);
246 if (stateFree)
247 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
248 }
249
250 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
251 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero);
252 if (stateFree) {
253 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000254 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
255 stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000256 C.addTransition(stateRealloc);
257 }
258 }
259 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000260}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000261
262void MallocChecker::EvalDeadSymbols(CheckerContext &C, const Stmt *S,
263 SymbolReaper &SymReaper) {
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000264 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
265 E = SymReaper.dead_end(); I != E; ++I) {
266 SymbolRef Sym = *I;
267 const GRState *state = C.getState();
268 const RefState *RS = state->get<RegionState>(Sym);
269 if (!RS)
270 return;
271
Zhongxing Xu243fde92009-11-17 07:54:15 +0000272 if (RS->isAllocated()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000273 ExplodedNode *N = C.GenerateSink();
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000274 if (N) {
275 if (!BT_Leak)
276 BT_Leak = new BuiltinBug("Memory leak",
277 "Allocated memory never released. Potential memory leak.");
278 // FIXME: where it is allocated.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000279 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000280 C.EmitReport(R);
281 }
282 }
283 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000284}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000285
286void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
287 GRExprEngine &Eng) {
Zhongxing Xuf605aae2009-11-22 13:22:34 +0000288 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000289 const GRState *state = B.getState();
290 typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap;
291 SymMap M = state->get<RegionState>();
292
293 for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
294 RefState RS = I->second;
295 if (RS.isAllocated()) {
296 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
297 if (N) {
298 if (!BT_Leak)
299 BT_Leak = new BuiltinBug("Memory leak",
300 "Allocated memory never released. Potential memory leak.");
301 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
302 Eng.getBugReporter().EmitReport(R);
303 }
304 }
305 }
306}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000307
308void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
309 const Expr *RetE = S->getRetValue();
310 if (!RetE)
311 return;
312
313 const GRState *state = C.getState();
314
Ted Kremenek13976632010-02-08 16:18:51 +0000315 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000316
317 if (!Sym)
318 return;
319
320 const RefState *RS = state->get<RegionState>(Sym);
321 if (!RS)
322 return;
323
324 // FIXME: check other cases.
325 if (RS->isAllocated())
326 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
327
Ted Kremenek19d67b52009-11-23 22:22:01 +0000328 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000329}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000330
331const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
332 bool Assumption) {
333 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
334 // FIXME: should also check symbols assumed to non-null.
335
336 RegionStateTy RS = state->get<RegionState>();
337
338 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
339 if (state->getSymVal(I.getKey()))
340 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
341 }
342
343 return state;
344}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000345
346// Check if the location is a freed symbolic region.
347void MallocChecker::VisitLocation(CheckerContext &C, const Stmt *S, SVal l) {
348 SymbolRef Sym = l.getLocSymbolInBase();
349 if (Sym) {
350 const RefState *RS = C.getState()->get<RegionState>(Sym);
351 if (RS)
352 if (RS->isReleased()) {
353 ExplodedNode *N = C.GenerateSink();
354 if (!BT_UseFree)
355 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
356 " it is freed.");
357
358 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
359 N);
360 C.EmitReport(R);
361 }
362 }
363}