blob: 3be2e0299bba881a20c31faca735b0257008be95 [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//=== 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
15#include "GRExprEngineExperimentalChecks.h"
16#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"
20#include "llvm/ADT/ImmutableMap.h"
21using namespace clang;
22
23namespace {
24
25class RefState {
26 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped } K;
27 const Stmt *S;
28
29public:
30 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
31
32 bool isAllocated() const { return K == AllocateUnchecked; }
33 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
40 static RefState getAllocateUnchecked(const Stmt *s) {
41 return RefState(AllocateUnchecked, s);
42 }
43 static RefState getAllocateFailed() {
44 return RefState(AllocateFailed, 0);
45 }
46 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 }
53};
54
55class RegionState {};
56
57class MallocChecker : public CheckerVisitor<MallocChecker> {
58 BuiltinBug *BT_DoubleFree;
59 BuiltinBug *BT_Leak;
60 IdentifierInfo *II_malloc, *II_free, *II_realloc;
61
62public:
63 MallocChecker()
64 : BT_DoubleFree(0), BT_Leak(0), II_malloc(0), II_free(0), II_realloc(0) {}
65 static void *getTag();
66 bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
67 void EvalDeadSymbols(CheckerContext &C,const Stmt *S,SymbolReaper &SymReaper);
68 void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng);
69 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
70 const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption);
71
72private:
73 void MallocMem(CheckerContext &C, const CallExpr *CE);
74 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
75 const Expr *SizeEx, const GRState *state);
76 void FreeMem(CheckerContext &C, const CallExpr *CE);
77 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
78 const GRState *state);
79
80 void ReallocMem(CheckerContext &C, const CallExpr *CE);
81};
82} // end anonymous namespace
83
84typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
85
86namespace clang {
87 template <>
88 struct GRStateTrait<RegionState>
89 : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > {
90 static void *GDMIndex() { return MallocChecker::getTag(); }
91 };
92}
93
94void clang::RegisterMallocChecker(GRExprEngine &Eng) {
95 Eng.registerCheck(new MallocChecker());
96}
97
98void *MallocChecker::getTag() {
99 static int x;
100 return &x;
101}
102
103bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
104 const GRState *state = C.getState();
105 const Expr *Callee = CE->getCallee();
106 SVal L = state->getSVal(Callee);
107
108 const FunctionDecl *FD = L.getAsFunctionDecl();
109 if (!FD)
110 return false;
111
112 ASTContext &Ctx = C.getASTContext();
113 if (!II_malloc)
114 II_malloc = &Ctx.Idents.get("malloc");
115 if (!II_free)
116 II_free = &Ctx.Idents.get("free");
117 if (!II_realloc)
118 II_realloc = &Ctx.Idents.get("realloc");
119
120 if (FD->getIdentifier() == II_malloc) {
121 MallocMem(C, CE);
122 return true;
123 }
124
125 if (FD->getIdentifier() == II_free) {
126 FreeMem(C, CE);
127 return true;
128 }
129
130 if (FD->getIdentifier() == II_realloc) {
131 ReallocMem(C, CE);
132 return true;
133 }
134
135 return false;
136}
137
138void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
139 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), C.getState());
140 C.addTransition(state);
141}
142
143const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
144 const CallExpr *CE,
145 const Expr *SizeEx,
146 const GRState *state) {
147 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
148 ValueManager &ValMgr = C.getValueManager();
149
150 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
151
152 SVal Size = state->getSVal(SizeEx);
153
154 state = C.getEngine().getStoreManager().setExtent(state, RetVal.getAsRegion(),
155 Size);
156
157 state = state->BindExpr(CE, RetVal);
158
159 SymbolRef Sym = RetVal.getAsLocSymbol();
160 assert(Sym);
161 // Set the symbol's state to Allocated.
162 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
163}
164
165void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
166 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) {
174 SVal ArgVal = state->getSVal(CE->getArg(0));
175 SymbolRef Sym = ArgVal.getAsLocSymbol();
176 assert(Sym);
177
178 const RefState *RS = state->get<RegionState>(Sym);
179
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;
185
186 // Check double free.
187 if (RS->isReleased()) {
188 ExplodedNode *N = C.GenerateSink();
189 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,
195 BT_DoubleFree->getDescription(), N);
196 C.EmitReport(R);
197 }
198 return NULL;
199 }
200
201 // Normal free.
202 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);
208 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
209
210 ValueManager &ValMgr = C.getValueManager();
211 SValuator &SVator = C.getSValuator();
212
213 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
214
215 // If the ptr is NULL, the call is equivalent to malloc(size).
216 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
217 // Hack: set the NULL symbolic region to released to suppress false warning.
218 // In the future we should add more states for allocated regions, e.g.,
219 // CheckedNull, CheckedNonNull.
220
221 SymbolRef Sym = Arg0Val.getAsLocSymbol();
222 if (Sym)
223 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
224
225 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1), stateEqual);
226 C.addTransition(stateMalloc);
227 }
228
229 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
230 const Expr *Arg1 = CE->getArg(1);
231 DefinedOrUnknownSVal Arg1Val =
232 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
233 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
234 ValMgr.makeIntValWithPtrWidth(0, false));
235
236 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
237 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero);
238 if (stateFree)
239 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
240 }
241
242 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
243 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero);
244 if (stateFree) {
245 // FIXME: We should copy the content of the original buffer.
246 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
247 stateFree);
248 C.addTransition(stateRealloc);
249 }
250 }
251 }
252}
253
254void MallocChecker::EvalDeadSymbols(CheckerContext &C, const Stmt *S,
255 SymbolReaper &SymReaper) {
256 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
257 E = SymReaper.dead_end(); I != E; ++I) {
258 SymbolRef Sym = *I;
259 const GRState *state = C.getState();
260 const RefState *RS = state->get<RegionState>(Sym);
261 if (!RS)
262 return;
263
264 if (RS->isAllocated()) {
265 ExplodedNode *N = C.GenerateSink();
266 if (N) {
267 if (!BT_Leak)
268 BT_Leak = new BuiltinBug("Memory leak",
269 "Allocated memory never released. Potential memory leak.");
270 // FIXME: where it is allocated.
271 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
272 C.EmitReport(R);
273 }
274 }
275 }
276}
277
278void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
279 GRExprEngine &Eng) {
280 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
281 const GRState *state = B.getState();
282 typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap;
283 SymMap M = state->get<RegionState>();
284
285 for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
286 RefState RS = I->second;
287 if (RS.isAllocated()) {
288 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
289 if (N) {
290 if (!BT_Leak)
291 BT_Leak = new BuiltinBug("Memory leak",
292 "Allocated memory never released. Potential memory leak.");
293 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
294 Eng.getBugReporter().EmitReport(R);
295 }
296 }
297 }
298}
299
300void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
301 const Expr *RetE = S->getRetValue();
302 if (!RetE)
303 return;
304
305 const GRState *state = C.getState();
306
307 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
308
309 if (!Sym)
310 return;
311
312 const RefState *RS = state->get<RegionState>(Sym);
313 if (!RS)
314 return;
315
316 // FIXME: check other cases.
317 if (RS->isAllocated())
318 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
319
320 C.addTransition(state);
321}
322
323const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
324 bool Assumption) {
325 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
326 // FIXME: should also check symbols assumed to non-null.
327
328 RegionStateTy RS = state->get<RegionState>();
329
330 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
331 if (state->getSymVal(I.getKey()))
332 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
333 }
334
335 return state;
336}