blob: 7f36f74578088d8ffbbd3fc7e19699c7c7cc2515 [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 Xud9c84c82009-12-12 12:29:38 +000060 IdentifierInfo *II_malloc, *II_free, *II_realloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000061
62public:
Zhongxing Xud9c84c82009-12-12 12:29:38 +000063 MallocChecker()
64 : BT_DoubleFree(0), BT_Leak(0), II_malloc(0), II_free(0), II_realloc(0) {}
Zhongxing Xu589c0f22009-11-12 08:38:56 +000065 static void *getTag();
Zhongxing Xua49c6b72009-12-11 03:09:01 +000066 bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
Zhongxing Xu7b760962009-11-13 07:25:27 +000067 void EvalDeadSymbols(CheckerContext &C,const Stmt *S,SymbolReaper &SymReaper);
Zhongxing Xu243fde92009-11-17 07:54:15 +000068 void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +000069 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000070 const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption);
71
Zhongxing Xu7b760962009-11-13 07:25:27 +000072private:
Zhongxing Xu589c0f22009-11-12 08:38:56 +000073 void MallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000074 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
Zhongxing Xu3ed04d32010-01-18 08:54:31 +000075 const Expr *SizeEx, const GRState *state);
Zhongxing Xu589c0f22009-11-12 08:38:56 +000076 void FreeMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000077 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
78 const GRState *state);
79
80 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xu589c0f22009-11-12 08:38:56 +000081};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000082} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +000083
Zhongxing Xub94b81a2009-12-31 06:13:07 +000084typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
85
Zhongxing Xu589c0f22009-11-12 08:38:56 +000086namespace clang {
Zhongxing Xu243fde92009-11-17 07:54:15 +000087 template <>
Zhongxing Xu589c0f22009-11-12 08:38:56 +000088 struct GRStateTrait<RegionState>
89 : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > {
90 static void *GDMIndex() { return MallocChecker::getTag(); }
91 };
92}
93
Zhongxing Xu7b760962009-11-13 07:25:27 +000094void clang::RegisterMallocChecker(GRExprEngine &Eng) {
95 Eng.registerCheck(new MallocChecker());
96}
97
Zhongxing Xu589c0f22009-11-12 08:38:56 +000098void *MallocChecker::getTag() {
99 static int x;
100 return &x;
101}
102
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000103bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
104 const GRState *state = C.getState();
105 const Expr *Callee = CE->getCallee();
Zhongxing Xu6f8c4302010-02-08 09:30:02 +0000106 SVal L = state->getExprVal(Callee);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000107
108 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000109 if (!FD)
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000110 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000111
112 ASTContext &Ctx = C.getASTContext();
113 if (!II_malloc)
114 II_malloc = &Ctx.Idents.get("malloc");
115 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000116 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000117 if (!II_realloc)
118 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000119
120 if (FD->getIdentifier() == II_malloc) {
121 MallocMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000122 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000123 }
124
125 if (FD->getIdentifier() == II_free) {
126 FreeMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000127 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000128 }
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000129
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000130 if (FD->getIdentifier() == II_realloc) {
131 ReallocMem(C, CE);
132 return true;
133 }
134
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000135 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000136}
137
138void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000139 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), C.getState());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000140 C.addTransition(state);
141}
142
143const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
144 const CallExpr *CE,
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000145 const Expr *SizeEx,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000146 const GRState *state) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000147 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
148 ValueManager &ValMgr = C.getValueManager();
149
150 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
151
Zhongxing Xu6f8c4302010-02-08 09:30:02 +0000152 SVal Size = state->getExprVal(SizeEx);
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000153
154 state = C.getEngine().getStoreManager().setExtent(state, RetVal.getAsRegion(),
155 Size);
156
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000157 state = state->BindExpr(CE, RetVal);
158
159 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000160 assert(Sym);
161 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000162 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000163}
164
165void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000166 const GRState *state = FreeMemAux(C, CE, C.getState());
167
168 if (state)
169 C.addTransition(state);
170}
171
172const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
173 const GRState *state) {
Zhongxing Xu6f8c4302010-02-08 09:30:02 +0000174 SVal ArgVal = state->getExprVal(CE->getArg(0));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000175 SymbolRef Sym = ArgVal.getAsLocSymbol();
176 assert(Sym);
177
178 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000179
180 // If the symbol has not been tracked, return. This is possible when free() is
181 // called on a pointer that does not get its pointee directly from malloc().
182 // Full support of this requires inter-procedural analysis.
183 if (!RS)
184 return state;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000185
186 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000187 if (RS->isReleased()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000188 ExplodedNode *N = C.GenerateSink();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000189 if (N) {
190 if (!BT_DoubleFree)
191 BT_DoubleFree = new BuiltinBug("Double free",
192 "Try to free a memory block that has been released");
193 // FIXME: should find where it's freed last time.
194 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000195 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000196 C.EmitReport(R);
197 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000198 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000199 }
200
201 // Normal free.
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000202 return state->set<RegionState>(Sym, RefState::getReleased(CE));
203}
204
205void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
206 const GRState *state = C.getState();
207 const Expr *Arg0 = CE->getArg(0);
Zhongxing Xu6f8c4302010-02-08 09:30:02 +0000208 DefinedOrUnknownSVal Arg0Val =
209 cast<DefinedOrUnknownSVal>(state->getExprVal(Arg0));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000210
211 ValueManager &ValMgr = C.getValueManager();
212 SValuator &SVator = C.getSValuator();
213
214 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
215
216 // If the ptr is NULL, the call is equivalent to malloc(size).
217 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
218 // Hack: set the NULL symbolic region to released to suppress false warning.
219 // In the future we should add more states for allocated regions, e.g.,
220 // CheckedNull, CheckedNonNull.
221
222 SymbolRef Sym = Arg0Val.getAsLocSymbol();
223 if (Sym)
224 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
225
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000226 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000227 C.addTransition(stateMalloc);
228 }
229
230 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
231 const Expr *Arg1 = CE->getArg(1);
232 DefinedOrUnknownSVal Arg1Val =
Zhongxing Xu6f8c4302010-02-08 09:30:02 +0000233 cast<DefinedOrUnknownSVal>(stateNotEqual->getExprVal(Arg1));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000234 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
235 ValMgr.makeIntValWithPtrWidth(0, false));
236
237 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
238 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero);
239 if (stateFree)
240 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
241 }
242
243 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
244 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero);
245 if (stateFree) {
246 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000247 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
248 stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000249 C.addTransition(stateRealloc);
250 }
251 }
252 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000253}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000254
255void MallocChecker::EvalDeadSymbols(CheckerContext &C, const Stmt *S,
256 SymbolReaper &SymReaper) {
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000257 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
258 E = SymReaper.dead_end(); I != E; ++I) {
259 SymbolRef Sym = *I;
260 const GRState *state = C.getState();
261 const RefState *RS = state->get<RegionState>(Sym);
262 if (!RS)
263 return;
264
Zhongxing Xu243fde92009-11-17 07:54:15 +0000265 if (RS->isAllocated()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000266 ExplodedNode *N = C.GenerateSink();
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000267 if (N) {
268 if (!BT_Leak)
269 BT_Leak = new BuiltinBug("Memory leak",
270 "Allocated memory never released. Potential memory leak.");
271 // FIXME: where it is allocated.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000272 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000273 C.EmitReport(R);
274 }
275 }
276 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000277}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000278
279void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
280 GRExprEngine &Eng) {
Zhongxing Xuf605aae2009-11-22 13:22:34 +0000281 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000282 const GRState *state = B.getState();
283 typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap;
284 SymMap M = state->get<RegionState>();
285
286 for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
287 RefState RS = I->second;
288 if (RS.isAllocated()) {
289 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
290 if (N) {
291 if (!BT_Leak)
292 BT_Leak = new BuiltinBug("Memory leak",
293 "Allocated memory never released. Potential memory leak.");
294 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
295 Eng.getBugReporter().EmitReport(R);
296 }
297 }
298 }
299}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000300
301void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
302 const Expr *RetE = S->getRetValue();
303 if (!RetE)
304 return;
305
306 const GRState *state = C.getState();
307
Zhongxing Xu6f8c4302010-02-08 09:30:02 +0000308 SymbolRef Sym = state->getExprVal(RetE).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000309
310 if (!Sym)
311 return;
312
313 const RefState *RS = state->get<RegionState>(Sym);
314 if (!RS)
315 return;
316
317 // FIXME: check other cases.
318 if (RS->isAllocated())
319 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
320
Ted Kremenek19d67b52009-11-23 22:22:01 +0000321 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000322}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000323
324const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
325 bool Assumption) {
326 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
327 // FIXME: should also check symbols assumed to non-null.
328
329 RegionStateTy RS = state->get<RegionState>();
330
331 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
332 if (state->getSymVal(I.getKey()))
333 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
334 }
335
336 return state;
337}