blob: 086dbd8fdd368483bcf6184a5839977f12e1da2d [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 {
Zhongxing Xub94b81a2009-12-31 06:13:07 +000027 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped } 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; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000034 bool isReleased() const { return K == Released; }
35 bool isEscaped() const { return K == Escaped; }
36
37 bool operator==(const RefState &X) const {
38 return K == X.K && S == X.S;
39 }
40
Zhongxing Xub94b81a2009-12-31 06:13:07 +000041 static RefState getAllocateUnchecked(const Stmt *s) {
42 return RefState(AllocateUnchecked, s);
43 }
44 static RefState getAllocateFailed() {
45 return RefState(AllocateFailed, 0);
46 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000047 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
48 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
49
50 void Profile(llvm::FoldingSetNodeID &ID) const {
51 ID.AddInteger(K);
52 ID.AddPointer(S);
53 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000054};
55
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000056class RegionState {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +000057
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000058class MallocChecker : public CheckerVisitor<MallocChecker> {
Zhongxing Xu589c0f22009-11-12 08:38:56 +000059 BuiltinBug *BT_DoubleFree;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +000060 BuiltinBug *BT_Leak;
Zhongxing Xuc8023782010-03-10 04:58:55 +000061 BuiltinBug *BT_UseFree;
Zhongxing Xud9c84c82009-12-12 12:29:38 +000062 IdentifierInfo *II_malloc, *II_free, *II_realloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000063
64public:
Zhongxing Xud9c84c82009-12-12 12:29:38 +000065 MallocChecker()
Zhongxing Xuc8023782010-03-10 04:58:55 +000066 : BT_DoubleFree(0), BT_Leak(0), BT_UseFree(0),
67 II_malloc(0), II_free(0), II_realloc(0) {}
Zhongxing Xu589c0f22009-11-12 08:38:56 +000068 static void *getTag();
Zhongxing Xua49c6b72009-12-11 03:09:01 +000069 bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
Zhongxing Xu7b760962009-11-13 07:25:27 +000070 void EvalDeadSymbols(CheckerContext &C,const Stmt *S,SymbolReaper &SymReaper);
Zhongxing Xu243fde92009-11-17 07:54:15 +000071 void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +000072 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000073 const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption);
Zhongxing Xuc8023782010-03-10 04:58:55 +000074 void VisitLocation(CheckerContext &C, const Stmt *S, SVal l);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000075
Zhongxing Xu7b760962009-11-13 07:25:27 +000076private:
Zhongxing Xu589c0f22009-11-12 08:38:56 +000077 void MallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000078 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
Zhongxing Xu3ed04d32010-01-18 08:54:31 +000079 const Expr *SizeEx, const GRState *state);
Zhongxing Xu589c0f22009-11-12 08:38:56 +000080 void FreeMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000081 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
82 const GRState *state);
83
84 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xu589c0f22009-11-12 08:38:56 +000085};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000086} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +000087
Zhongxing Xub94b81a2009-12-31 06:13:07 +000088typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
89
Zhongxing Xu589c0f22009-11-12 08:38:56 +000090namespace clang {
Zhongxing Xu243fde92009-11-17 07:54:15 +000091 template <>
Zhongxing Xu589c0f22009-11-12 08:38:56 +000092 struct GRStateTrait<RegionState>
93 : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > {
94 static void *GDMIndex() { return MallocChecker::getTag(); }
95 };
96}
97
Zhongxing Xu7b760962009-11-13 07:25:27 +000098void clang::RegisterMallocChecker(GRExprEngine &Eng) {
99 Eng.registerCheck(new MallocChecker());
100}
101
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000102void *MallocChecker::getTag() {
103 static int x;
104 return &x;
105}
106
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000107bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
108 const GRState *state = C.getState();
109 const Expr *Callee = CE->getCallee();
Ted Kremenek13976632010-02-08 16:18:51 +0000110 SVal L = state->getSVal(Callee);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000111
112 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000113 if (!FD)
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000114 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000115
116 ASTContext &Ctx = C.getASTContext();
117 if (!II_malloc)
118 II_malloc = &Ctx.Idents.get("malloc");
119 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000120 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000121 if (!II_realloc)
122 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000123
124 if (FD->getIdentifier() == II_malloc) {
125 MallocMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000126 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000127 }
128
129 if (FD->getIdentifier() == II_free) {
130 FreeMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000131 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000132 }
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000133
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000134 if (FD->getIdentifier() == II_realloc) {
135 ReallocMem(C, CE);
136 return true;
137 }
138
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000139 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000140}
141
142void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000143 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), C.getState());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000144 C.addTransition(state);
145}
146
147const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
148 const CallExpr *CE,
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000149 const Expr *SizeEx,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000150 const GRState *state) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000151 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
152 ValueManager &ValMgr = C.getValueManager();
153
154 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
155
Ted Kremenek13976632010-02-08 16:18:51 +0000156 SVal Size = state->getSVal(SizeEx);
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000157
158 state = C.getEngine().getStoreManager().setExtent(state, RetVal.getAsRegion(),
159 Size);
160
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000161 state = state->BindExpr(CE, RetVal);
162
163 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000164 assert(Sym);
165 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000166 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000167}
168
169void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000170 const GRState *state = FreeMemAux(C, CE, C.getState());
171
172 if (state)
173 C.addTransition(state);
174}
175
176const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
177 const GRState *state) {
Ted Kremenek13976632010-02-08 16:18:51 +0000178 SVal ArgVal = state->getSVal(CE->getArg(0));
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000179
180 // If ptr is NULL, no operation is preformed.
181 if (ArgVal.isZeroConstant())
182 return state;
183
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000184 SymbolRef Sym = ArgVal.getAsLocSymbol();
Zhongxing Xu8e98ac12010-05-13 08:26:32 +0000185
186 // Various cases could lead to non-symbol values here.
187 if (!Sym)
188 return state;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000189
190 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000191
192 // If the symbol has not been tracked, return. This is possible when free() is
193 // called on a pointer that does not get its pointee directly from malloc().
194 // Full support of this requires inter-procedural analysis.
195 if (!RS)
196 return state;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000197
198 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000199 if (RS->isReleased()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000200 ExplodedNode *N = C.GenerateSink();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000201 if (N) {
202 if (!BT_DoubleFree)
203 BT_DoubleFree = new BuiltinBug("Double free",
204 "Try to free a memory block that has been released");
205 // FIXME: should find where it's freed last time.
206 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000207 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000208 C.EmitReport(R);
209 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000210 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000211 }
212
213 // Normal free.
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000214 return state->set<RegionState>(Sym, RefState::getReleased(CE));
215}
216
217void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
218 const GRState *state = C.getState();
219 const Expr *Arg0 = CE->getArg(0);
Ted Kremenek13976632010-02-08 16:18:51 +0000220 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000221
222 ValueManager &ValMgr = C.getValueManager();
223 SValuator &SVator = C.getSValuator();
224
225 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
226
227 // If the ptr is NULL, the call is equivalent to malloc(size).
228 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
229 // Hack: set the NULL symbolic region to released to suppress false warning.
230 // In the future we should add more states for allocated regions, e.g.,
231 // CheckedNull, CheckedNonNull.
232
233 SymbolRef Sym = Arg0Val.getAsLocSymbol();
234 if (Sym)
235 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
236
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000237 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000238 C.addTransition(stateMalloc);
239 }
240
241 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
242 const Expr *Arg1 = CE->getArg(1);
243 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek13976632010-02-08 16:18:51 +0000244 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000245 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
246 ValMgr.makeIntValWithPtrWidth(0, false));
247
248 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
249 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero);
250 if (stateFree)
251 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
252 }
253
254 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
255 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero);
256 if (stateFree) {
257 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000258 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
259 stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000260 C.addTransition(stateRealloc);
261 }
262 }
263 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000264}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000265
266void MallocChecker::EvalDeadSymbols(CheckerContext &C, const Stmt *S,
267 SymbolReaper &SymReaper) {
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000268 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
269 E = SymReaper.dead_end(); I != E; ++I) {
270 SymbolRef Sym = *I;
271 const GRState *state = C.getState();
272 const RefState *RS = state->get<RegionState>(Sym);
273 if (!RS)
274 return;
275
Zhongxing Xu243fde92009-11-17 07:54:15 +0000276 if (RS->isAllocated()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000277 ExplodedNode *N = C.GenerateSink();
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000278 if (N) {
279 if (!BT_Leak)
280 BT_Leak = new BuiltinBug("Memory leak",
281 "Allocated memory never released. Potential memory leak.");
282 // FIXME: where it is allocated.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000283 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000284 C.EmitReport(R);
285 }
286 }
287 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000288}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000289
290void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
291 GRExprEngine &Eng) {
Zhongxing Xuf605aae2009-11-22 13:22:34 +0000292 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000293 const GRState *state = B.getState();
294 typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap;
295 SymMap M = state->get<RegionState>();
296
297 for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
298 RefState RS = I->second;
299 if (RS.isAllocated()) {
300 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
301 if (N) {
302 if (!BT_Leak)
303 BT_Leak = new BuiltinBug("Memory leak",
304 "Allocated memory never released. Potential memory leak.");
305 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
306 Eng.getBugReporter().EmitReport(R);
307 }
308 }
309 }
310}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000311
312void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
313 const Expr *RetE = S->getRetValue();
314 if (!RetE)
315 return;
316
317 const GRState *state = C.getState();
318
Ted Kremenek13976632010-02-08 16:18:51 +0000319 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000320
321 if (!Sym)
322 return;
323
324 const RefState *RS = state->get<RegionState>(Sym);
325 if (!RS)
326 return;
327
328 // FIXME: check other cases.
329 if (RS->isAllocated())
330 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
331
Ted Kremenek19d67b52009-11-23 22:22:01 +0000332 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000333}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000334
335const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
336 bool Assumption) {
337 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
338 // FIXME: should also check symbols assumed to non-null.
339
340 RegionStateTy RS = state->get<RegionState>();
341
342 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
343 if (state->getSymVal(I.getKey()))
344 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
345 }
346
347 return state;
348}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000349
350// Check if the location is a freed symbolic region.
351void MallocChecker::VisitLocation(CheckerContext &C, const Stmt *S, SVal l) {
352 SymbolRef Sym = l.getLocSymbolInBase();
353 if (Sym) {
354 const RefState *RS = C.getState()->get<RegionState>(Sym);
355 if (RS)
356 if (RS->isReleased()) {
357 ExplodedNode *N = C.GenerateSink();
358 if (!BT_UseFree)
359 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
360 " it is freed.");
361
362 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
363 N);
364 C.EmitReport(R);
365 }
366 }
367}