blob: 22b8b29f7850a947d82910230997997fb73187f4 [file] [log] [blame]
Zhongxing Xu88cca6b2009-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 Xuc4902a52009-11-13 07:25:27 +000015#include "GRExprEngineExperimentalChecks.h"
Benjamin Kramerc0483222010-03-27 21:19:47 +000016#include "clang/Checker/BugReporter/BugType.h"
Ted Kremenekd6b87082010-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 Xu88cca6b2009-11-12 08:38:56 +000021#include "llvm/ADT/ImmutableMap.h"
22using namespace clang;
23
24namespace {
25
Zhongxing Xu1239de12009-12-11 00:55:44 +000026class RefState {
Zhongxing Xub0e15df2009-12-31 06:13:07 +000027 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped } K;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000028 const Stmt *S;
29
Zhongxing Xu1239de12009-12-11 00:55:44 +000030public:
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000031 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
32
Zhongxing Xub0e15df2009-12-31 06:13:07 +000033 bool isAllocated() const { return K == AllocateUnchecked; }
Zhongxing Xu4668c7e2009-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 Xub0e15df2009-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 Xu4668c7e2009-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 Xu88cca6b2009-11-12 08:38:56 +000054};
55
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +000056class RegionState {};
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000057
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +000058class MallocChecker : public CheckerVisitor<MallocChecker> {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000059 BuiltinBug *BT_DoubleFree;
Zhongxing Xuc7460962009-11-13 07:48:11 +000060 BuiltinBug *BT_Leak;
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +000061 BuiltinBug *BT_UseFree;
Zhongxing Xu527ff6d2010-06-01 03:01:33 +000062 IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000063
64public:
Zhongxing Xuc0484fa2009-12-12 12:29:38 +000065 MallocChecker()
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +000066 : BT_DoubleFree(0), BT_Leak(0), BT_UseFree(0),
Zhongxing Xu527ff6d2010-06-01 03:01:33 +000067 II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000068 static void *getTag();
Zhongxing Xu9cb53b82009-12-11 03:09:01 +000069 bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
Zhongxing Xuc4902a52009-11-13 07:25:27 +000070 void EvalDeadSymbols(CheckerContext &C,const Stmt *S,SymbolReaper &SymReaper);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000071 void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng);
Zhongxing Xu23baa012009-11-17 08:58:18 +000072 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000073 const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption);
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +000074 void VisitLocation(CheckerContext &C, const Stmt *S, SVal l);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000075
Zhongxing Xuc4902a52009-11-13 07:25:27 +000076private:
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000077 void MallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +000078 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +000079 const Expr *SizeEx, SVal Init,
80 const GRState *state) {
81 return MallocMemAux(C, CE, state->getSVal(SizeEx), Init, state);
82 }
83 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
84 SVal SizeEx, SVal Init,
85 const GRState *state);
86
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000087 void FreeMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +000088 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
89 const GRState *state);
90
91 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +000092 void CallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000093};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +000094} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000095
Zhongxing Xub0e15df2009-12-31 06:13:07 +000096typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
97
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000098namespace clang {
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000099 template <>
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000100 struct GRStateTrait<RegionState>
101 : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > {
102 static void *GDMIndex() { return MallocChecker::getTag(); }
103 };
104}
105
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000106void clang::RegisterMallocChecker(GRExprEngine &Eng) {
107 Eng.registerCheck(new MallocChecker());
108}
109
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000110void *MallocChecker::getTag() {
111 static int x;
112 return &x;
113}
114
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000115bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
116 const GRState *state = C.getState();
117 const Expr *Callee = CE->getCallee();
Ted Kremenek57f09892010-02-08 16:18:51 +0000118 SVal L = state->getSVal(Callee);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000119
120 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000121 if (!FD)
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000122 return false;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000123
124 ASTContext &Ctx = C.getASTContext();
125 if (!II_malloc)
126 II_malloc = &Ctx.Idents.get("malloc");
127 if (!II_free)
Zhongxing Xuc7460962009-11-13 07:48:11 +0000128 II_free = &Ctx.Idents.get("free");
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000129 if (!II_realloc)
130 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000131 if (!II_calloc)
132 II_calloc = &Ctx.Idents.get("calloc");
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000133
134 if (FD->getIdentifier() == II_malloc) {
135 MallocMem(C, CE);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000136 return true;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000137 }
138
139 if (FD->getIdentifier() == II_free) {
140 FreeMem(C, CE);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000141 return true;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000142 }
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000143
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000144 if (FD->getIdentifier() == II_realloc) {
145 ReallocMem(C, CE);
146 return true;
147 }
148
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000149 if (FD->getIdentifier() == II_calloc) {
150 CallocMem(C, CE);
151 return true;
152 }
153
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000154 return false;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000155}
156
157void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000158 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
159 C.getState());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000160 C.addTransition(state);
161}
162
163const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
164 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000165 SVal Size, SVal Init,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000166 const GRState *state) {
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000167 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
168 ValueManager &ValMgr = C.getValueManager();
169
170 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
171
Zhongxing Xu228b0d42010-01-18 08:54:31 +0000172 state = C.getEngine().getStoreManager().setExtent(state, RetVal.getAsRegion(),
173 Size);
174
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000175 state = state->bindDefault(RetVal, Init);
176
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000177 state = state->BindExpr(CE, RetVal);
178
179 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000180 assert(Sym);
181 // Set the symbol's state to Allocated.
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000182 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000183}
184
185void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000186 const GRState *state = FreeMemAux(C, CE, C.getState());
187
188 if (state)
189 C.addTransition(state);
190}
191
192const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
193 const GRState *state) {
Ted Kremenek57f09892010-02-08 16:18:51 +0000194 SVal ArgVal = state->getSVal(CE->getArg(0));
Zhongxing Xube36ecb2010-02-14 06:49:48 +0000195
196 // If ptr is NULL, no operation is preformed.
197 if (ArgVal.isZeroConstant())
198 return state;
199
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000200 SymbolRef Sym = ArgVal.getAsLocSymbol();
Zhongxing Xu6e8417c2010-05-13 08:26:32 +0000201
202 // Various cases could lead to non-symbol values here.
203 if (!Sym)
204 return state;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000205
206 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +0000207
208 // If the symbol has not been tracked, return. This is possible when free() is
209 // called on a pointer that does not get its pointee directly from malloc().
210 // Full support of this requires inter-procedural analysis.
211 if (!RS)
212 return state;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000213
214 // Check double free.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000215 if (RS->isReleased()) {
Ted Kremenekf5735152009-11-23 22:22:01 +0000216 ExplodedNode *N = C.GenerateSink();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000217 if (N) {
218 if (!BT_DoubleFree)
219 BT_DoubleFree = new BuiltinBug("Double free",
220 "Try to free a memory block that has been released");
221 // FIXME: should find where it's freed last time.
222 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerf4c511b2009-11-14 12:08:24 +0000223 BT_DoubleFree->getDescription(), N);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000224 C.EmitReport(R);
225 }
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000226 return NULL;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000227 }
228
229 // Normal free.
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000230 return state->set<RegionState>(Sym, RefState::getReleased(CE));
231}
232
233void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
234 const GRState *state = C.getState();
235 const Expr *Arg0 = CE->getArg(0);
Ted Kremenek57f09892010-02-08 16:18:51 +0000236 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000237
238 ValueManager &ValMgr = C.getValueManager();
239 SValuator &SVator = C.getSValuator();
240
241 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
242
243 // If the ptr is NULL, the call is equivalent to malloc(size).
244 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
245 // Hack: set the NULL symbolic region to released to suppress false warning.
246 // In the future we should add more states for allocated regions, e.g.,
247 // CheckedNull, CheckedNonNull.
248
249 SymbolRef Sym = Arg0Val.getAsLocSymbol();
250 if (Sym)
251 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
252
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000253 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
254 UndefinedVal(), stateEqual);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000255 C.addTransition(stateMalloc);
256 }
257
258 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
259 const Expr *Arg1 = CE->getArg(1);
260 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek57f09892010-02-08 16:18:51 +0000261 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000262 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
263 ValMgr.makeIntValWithPtrWidth(0, false));
264
265 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
266 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero);
267 if (stateFree)
268 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
269 }
270
271 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
272 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero);
273 if (stateFree) {
274 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu228b0d42010-01-18 08:54:31 +0000275 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000276 UnknownVal(), stateFree);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000277 C.addTransition(stateRealloc);
278 }
279 }
280 }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000281}
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000282
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000283void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
284 const GRState *state = C.getState();
285
286 ValueManager &ValMgr = C.getValueManager();
287 SValuator &SVator = C.getSValuator();
288
289 SVal Count = state->getSVal(CE->getArg(0));
290 SVal EleSize = state->getSVal(CE->getArg(1));
291 SVal TotalSize = SVator.EvalBinOp(state, BinaryOperator::Mul, Count, EleSize,
292 ValMgr.getContext().getSizeType());
293
294 SVal Zero = ValMgr.makeZeroVal(ValMgr.getContext().CharTy);
295
296 state = MallocMemAux(C, CE, TotalSize, Zero, state);
297 C.addTransition(state);
298}
299
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000300void MallocChecker::EvalDeadSymbols(CheckerContext &C, const Stmt *S,
301 SymbolReaper &SymReaper) {
Zhongxing Xuc7460962009-11-13 07:48:11 +0000302 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
303 E = SymReaper.dead_end(); I != E; ++I) {
304 SymbolRef Sym = *I;
305 const GRState *state = C.getState();
306 const RefState *RS = state->get<RegionState>(Sym);
307 if (!RS)
308 return;
309
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000310 if (RS->isAllocated()) {
Ted Kremenekf5735152009-11-23 22:22:01 +0000311 ExplodedNode *N = C.GenerateSink();
Zhongxing Xuc7460962009-11-13 07:48:11 +0000312 if (N) {
313 if (!BT_Leak)
314 BT_Leak = new BuiltinBug("Memory leak",
315 "Allocated memory never released. Potential memory leak.");
316 // FIXME: where it is allocated.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000317 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Zhongxing Xuc7460962009-11-13 07:48:11 +0000318 C.EmitReport(R);
319 }
320 }
321 }
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000322}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000323
324void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
325 GRExprEngine &Eng) {
Zhongxing Xu7f83e972009-11-22 13:22:34 +0000326 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000327 const GRState *state = B.getState();
328 typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap;
329 SymMap M = state->get<RegionState>();
330
331 for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
332 RefState RS = I->second;
333 if (RS.isAllocated()) {
334 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
335 if (N) {
336 if (!BT_Leak)
337 BT_Leak = new BuiltinBug("Memory leak",
338 "Allocated memory never released. Potential memory leak.");
339 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
340 Eng.getBugReporter().EmitReport(R);
341 }
342 }
343 }
344}
Zhongxing Xu23baa012009-11-17 08:58:18 +0000345
346void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
347 const Expr *RetE = S->getRetValue();
348 if (!RetE)
349 return;
350
351 const GRState *state = C.getState();
352
Ted Kremenek57f09892010-02-08 16:18:51 +0000353 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +0000354
355 if (!Sym)
356 return;
357
358 const RefState *RS = state->get<RegionState>(Sym);
359 if (!RS)
360 return;
361
362 // FIXME: check other cases.
363 if (RS->isAllocated())
364 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
365
Ted Kremenekf5735152009-11-23 22:22:01 +0000366 C.addTransition(state);
Zhongxing Xu23baa012009-11-17 08:58:18 +0000367}
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000368
369const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
370 bool Assumption) {
371 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
372 // FIXME: should also check symbols assumed to non-null.
373
374 RegionStateTy RS = state->get<RegionState>();
375
376 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
377 if (state->getSymVal(I.getKey()))
378 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
379 }
380
381 return state;
382}
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +0000383
384// Check if the location is a freed symbolic region.
385void MallocChecker::VisitLocation(CheckerContext &C, const Stmt *S, SVal l) {
386 SymbolRef Sym = l.getLocSymbolInBase();
387 if (Sym) {
388 const RefState *RS = C.getState()->get<RegionState>(Sym);
389 if (RS)
390 if (RS->isReleased()) {
391 ExplodedNode *N = C.GenerateSink();
392 if (!BT_UseFree)
393 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
394 " it is freed.");
395
396 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
397 N);
398 C.EmitReport(R);
399 }
400 }
401}