blob: a5bba1d8ca587eb8b99d5da4e471c9a0f78861cd [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;
Jordy Rose43859f62010-06-07 19:32:37 +000062 BuiltinBug *BT_BadFree;
Zhongxing Xua5ce9662010-06-01 03:01:33 +000063 IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000064
65public:
Zhongxing Xud9c84c82009-12-12 12:29:38 +000066 MallocChecker()
Jordy Rose43859f62010-06-07 19:32:37 +000067 : BT_DoubleFree(0), BT_Leak(0), BT_UseFree(0), BT_BadFree(0),
Zhongxing Xua5ce9662010-06-01 03:01:33 +000068 II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Zhongxing Xu589c0f22009-11-12 08:38:56 +000069 static void *getTag();
Zhongxing Xua49c6b72009-12-11 03:09:01 +000070 bool EvalCallExpr(CheckerContext &C, const CallExpr *CE);
Jordy Rose7dadf792010-07-01 20:09:55 +000071 void EvalDeadSymbols(CheckerContext &C, SymbolReaper &SymReaper);
Zhongxing Xu243fde92009-11-17 07:54:15 +000072 void EvalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +000073 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000074 const GRState *EvalAssume(const GRState *state, SVal Cond, bool Assumption);
Zhongxing Xuc8023782010-03-10 04:58:55 +000075 void VisitLocation(CheckerContext &C, const Stmt *S, SVal l);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000076
Zhongxing Xu7b760962009-11-13 07:25:27 +000077private:
Zhongxing Xu589c0f22009-11-12 08:38:56 +000078 void MallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000079 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +000080 const Expr *SizeEx, SVal Init,
81 const GRState *state) {
82 return MallocMemAux(C, CE, state->getSVal(SizeEx), Init, state);
83 }
84 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
85 SVal SizeEx, SVal Init,
86 const GRState *state);
87
Zhongxing Xu589c0f22009-11-12 08:38:56 +000088 void FreeMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000089 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
90 const GRState *state);
91
92 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xua5ce9662010-06-01 03:01:33 +000093 void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +000094
95 bool SummarizeValue(llvm::raw_ostream& os, SVal V);
96 bool SummarizeRegion(llvm::raw_ostream& os, const MemRegion *MR);
97 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range);
Zhongxing Xu589c0f22009-11-12 08:38:56 +000098};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000099} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000100
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000101typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
102
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000103namespace clang {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000104 template <>
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000105 struct GRStateTrait<RegionState>
106 : public GRStatePartialTrait<llvm::ImmutableMap<SymbolRef, RefState> > {
107 static void *GDMIndex() { return MallocChecker::getTag(); }
108 };
109}
110
Zhongxing Xu7b760962009-11-13 07:25:27 +0000111void clang::RegisterMallocChecker(GRExprEngine &Eng) {
112 Eng.registerCheck(new MallocChecker());
113}
114
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000115void *MallocChecker::getTag() {
116 static int x;
117 return &x;
118}
119
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000120bool MallocChecker::EvalCallExpr(CheckerContext &C, const CallExpr *CE) {
121 const GRState *state = C.getState();
122 const Expr *Callee = CE->getCallee();
Ted Kremenek13976632010-02-08 16:18:51 +0000123 SVal L = state->getSVal(Callee);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000124
125 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000126 if (!FD)
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000127 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000128
129 ASTContext &Ctx = C.getASTContext();
130 if (!II_malloc)
131 II_malloc = &Ctx.Idents.get("malloc");
132 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000133 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000134 if (!II_realloc)
135 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000136 if (!II_calloc)
137 II_calloc = &Ctx.Idents.get("calloc");
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000138
139 if (FD->getIdentifier() == II_malloc) {
140 MallocMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000141 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000142 }
143
144 if (FD->getIdentifier() == II_free) {
145 FreeMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000146 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000147 }
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000148
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000149 if (FD->getIdentifier() == II_realloc) {
150 ReallocMem(C, CE);
151 return true;
152 }
153
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000154 if (FD->getIdentifier() == II_calloc) {
155 CallocMem(C, CE);
156 return true;
157 }
158
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000159 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000160}
161
162void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000163 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
164 C.getState());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000165 C.addTransition(state);
166}
167
168const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
169 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000170 SVal Size, SVal Init,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000171 const GRState *state) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000172 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
173 ValueManager &ValMgr = C.getValueManager();
174
175 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
176
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000177 state = C.getEngine().getStoreManager().setExtent(state, RetVal.getAsRegion(),
178 Size);
179
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000180 state = state->bindDefault(RetVal, Init);
181
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000182 state = state->BindExpr(CE, RetVal);
183
184 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000185 assert(Sym);
186 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000187 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000188}
189
190void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000191 const GRState *state = FreeMemAux(C, CE, C.getState());
192
193 if (state)
194 C.addTransition(state);
195}
196
197const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
198 const GRState *state) {
Jordy Rose43859f62010-06-07 19:32:37 +0000199 const Expr *ArgExpr = CE->getArg(0);
200 SVal ArgVal = state->getSVal(ArgExpr);
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000201
202 // If ptr is NULL, no operation is preformed.
203 if (ArgVal.isZeroConstant())
204 return state;
Jordy Rose43859f62010-06-07 19:32:37 +0000205
206 // Unknown values could easily be okay
207 // Undefined values are handled elsewhere
208 if (ArgVal.isUnknownOrUndef())
Zhongxing Xu8e98ac12010-05-13 08:26:32 +0000209 return state;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000210
Jordy Rose43859f62010-06-07 19:32:37 +0000211 const MemRegion *R = ArgVal.getAsRegion();
212
213 // Nonlocs can't be freed, of course.
214 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
215 if (!R) {
216 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
217 return NULL;
218 }
219
220 R = R->StripCasts();
221
222 // Blocks might show up as heap data, but should not be free()d
223 if (isa<BlockDataRegion>(R)) {
224 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
225 return NULL;
226 }
227
228 const MemSpaceRegion *MS = R->getMemorySpace();
229
230 // Parameters, locals, statics, and globals shouldn't be freed.
231 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
232 // FIXME: at the time this code was written, malloc() regions were
233 // represented by conjured symbols, which are all in UnknownSpaceRegion.
234 // This means that there isn't actually anything from HeapSpaceRegion
235 // that should be freed, even though we allow it here.
236 // Of course, free() can work on memory allocated outside the current
237 // function, so UnknownSpaceRegion is always a possibility.
238 // False negatives are better than false positives.
239
240 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
241 return NULL;
242 }
243
244 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
245 // Various cases could lead to non-symbol values here.
246 // For now, ignore them.
247 if (!SR)
248 return state;
249
250 SymbolRef Sym = SR->getSymbol();
251
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000252 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000253
254 // If the symbol has not been tracked, return. This is possible when free() is
255 // called on a pointer that does not get its pointee directly from malloc().
256 // Full support of this requires inter-procedural analysis.
257 if (!RS)
258 return state;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000259
260 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000261 if (RS->isReleased()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000262 ExplodedNode *N = C.GenerateSink();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000263 if (N) {
264 if (!BT_DoubleFree)
265 BT_DoubleFree = new BuiltinBug("Double free",
266 "Try to free a memory block that has been released");
267 // FIXME: should find where it's freed last time.
268 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000269 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000270 C.EmitReport(R);
271 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000272 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000273 }
274
275 // Normal free.
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000276 return state->set<RegionState>(Sym, RefState::getReleased(CE));
277}
278
Jordy Rose43859f62010-06-07 19:32:37 +0000279bool MallocChecker::SummarizeValue(llvm::raw_ostream& os, SVal V) {
280 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
281 os << "an integer (" << IntVal->getValue() << ")";
282 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
283 os << "a constant address (" << ConstAddr->getValue() << ")";
284 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
285 os << "the address of the label '"
286 << Label->getLabel()->getID()->getName()
287 << "'";
288 else
289 return false;
290
291 return true;
292}
293
294bool MallocChecker::SummarizeRegion(llvm::raw_ostream& os,
295 const MemRegion *MR) {
296 switch (MR->getKind()) {
297 case MemRegion::FunctionTextRegionKind: {
298 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
299 if (FD)
300 os << "the address of the function '" << FD << "'";
301 else
302 os << "the address of a function";
303 return true;
304 }
305 case MemRegion::BlockTextRegionKind:
306 os << "block text";
307 return true;
308 case MemRegion::BlockDataRegionKind:
309 // FIXME: where the block came from?
310 os << "a block";
311 return true;
312 default: {
313 const MemSpaceRegion *MS = MR->getMemorySpace();
314
315 switch (MS->getKind()) {
316 case MemRegion::StackLocalsSpaceRegionKind: {
317 const VarRegion *VR = dyn_cast<VarRegion>(MR);
318 const VarDecl *VD;
319 if (VR)
320 VD = VR->getDecl();
321 else
322 VD = NULL;
323
324 if (VD)
325 os << "the address of the local variable '" << VD->getName() << "'";
326 else
327 os << "the address of a local stack variable";
328 return true;
329 }
330 case MemRegion::StackArgumentsSpaceRegionKind: {
331 const VarRegion *VR = dyn_cast<VarRegion>(MR);
332 const VarDecl *VD;
333 if (VR)
334 VD = VR->getDecl();
335 else
336 VD = NULL;
337
338 if (VD)
339 os << "the address of the parameter '" << VD->getName() << "'";
340 else
341 os << "the address of a parameter";
342 return true;
343 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000344 case MemRegion::NonStaticGlobalSpaceRegionKind:
345 case MemRegion::StaticGlobalSpaceRegionKind: {
Jordy Rose43859f62010-06-07 19:32:37 +0000346 const VarRegion *VR = dyn_cast<VarRegion>(MR);
347 const VarDecl *VD;
348 if (VR)
349 VD = VR->getDecl();
350 else
351 VD = NULL;
352
353 if (VD) {
354 if (VD->isStaticLocal())
355 os << "the address of the static variable '" << VD->getName() << "'";
356 else
357 os << "the address of the global variable '" << VD->getName() << "'";
358 } else
359 os << "the address of a global variable";
360 return true;
361 }
362 default:
363 return false;
364 }
365 }
366 }
367}
368
369void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
370 SourceRange range) {
371 ExplodedNode *N = C.GenerateSink();
372 if (N) {
373 if (!BT_BadFree)
374 BT_BadFree = new BuiltinBug("Bad free");
375
376 llvm::SmallString<100> buf;
377 llvm::raw_svector_ostream os(buf);
378
379 const MemRegion *MR = ArgVal.getAsRegion();
380 if (MR) {
381 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
382 MR = ER->getSuperRegion();
383
384 // Special case for alloca()
385 if (isa<AllocaRegion>(MR))
386 os << "Argument to free() was allocated by alloca(), not malloc()";
387 else {
388 os << "Argument to free() is ";
389 if (SummarizeRegion(os, MR))
390 os << ", which is not memory allocated by malloc()";
391 else
392 os << "not memory allocated by malloc()";
393 }
394 } else {
395 os << "Argument to free() is ";
396 if (SummarizeValue(os, ArgVal))
397 os << ", which is not memory allocated by malloc()";
398 else
399 os << "not memory allocated by malloc()";
400 }
401
Jordy Rose31041242010-06-08 22:59:01 +0000402 EnhancedBugReport *R = new EnhancedBugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000403 R->addRange(range);
404 C.EmitReport(R);
405 }
406}
407
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000408void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
409 const GRState *state = C.getState();
410 const Expr *Arg0 = CE->getArg(0);
Ted Kremenek13976632010-02-08 16:18:51 +0000411 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000412
413 ValueManager &ValMgr = C.getValueManager();
414 SValuator &SVator = C.getSValuator();
415
416 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
417
418 // If the ptr is NULL, the call is equivalent to malloc(size).
419 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
420 // Hack: set the NULL symbolic region to released to suppress false warning.
421 // In the future we should add more states for allocated regions, e.g.,
422 // CheckedNull, CheckedNonNull.
423
424 SymbolRef Sym = Arg0Val.getAsLocSymbol();
425 if (Sym)
426 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
427
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000428 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
429 UndefinedVal(), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000430 C.addTransition(stateMalloc);
431 }
432
433 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
434 const Expr *Arg1 = CE->getArg(1);
435 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek13976632010-02-08 16:18:51 +0000436 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000437 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
438 ValMgr.makeIntValWithPtrWidth(0, false));
439
440 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
441 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero);
442 if (stateFree)
443 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
444 }
445
446 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
447 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero);
448 if (stateFree) {
449 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000450 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000451 UnknownVal(), stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000452 C.addTransition(stateRealloc);
453 }
454 }
455 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000456}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000457
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000458void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
459 const GRState *state = C.getState();
460
461 ValueManager &ValMgr = C.getValueManager();
462 SValuator &SVator = C.getSValuator();
463
464 SVal Count = state->getSVal(CE->getArg(0));
465 SVal EleSize = state->getSVal(CE->getArg(1));
466 SVal TotalSize = SVator.EvalBinOp(state, BinaryOperator::Mul, Count, EleSize,
467 ValMgr.getContext().getSizeType());
468
469 SVal Zero = ValMgr.makeZeroVal(ValMgr.getContext().CharTy);
470
471 state = MallocMemAux(C, CE, TotalSize, Zero, state);
472 C.addTransition(state);
473}
474
Jordy Rose7dadf792010-07-01 20:09:55 +0000475void MallocChecker::EvalDeadSymbols(CheckerContext &C,SymbolReaper &SymReaper) {
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000476 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
477 E = SymReaper.dead_end(); I != E; ++I) {
478 SymbolRef Sym = *I;
479 const GRState *state = C.getState();
480 const RefState *RS = state->get<RegionState>(Sym);
481 if (!RS)
482 return;
483
Zhongxing Xu243fde92009-11-17 07:54:15 +0000484 if (RS->isAllocated()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000485 ExplodedNode *N = C.GenerateSink();
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000486 if (N) {
487 if (!BT_Leak)
488 BT_Leak = new BuiltinBug("Memory leak",
489 "Allocated memory never released. Potential memory leak.");
490 // FIXME: where it is allocated.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000491 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000492 C.EmitReport(R);
493 }
494 }
495 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000496}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000497
498void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
499 GRExprEngine &Eng) {
Zhongxing Xuf605aae2009-11-22 13:22:34 +0000500 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000501 const GRState *state = B.getState();
502 typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap;
503 SymMap M = state->get<RegionState>();
504
505 for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
506 RefState RS = I->second;
507 if (RS.isAllocated()) {
508 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
509 if (N) {
510 if (!BT_Leak)
511 BT_Leak = new BuiltinBug("Memory leak",
512 "Allocated memory never released. Potential memory leak.");
513 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
514 Eng.getBugReporter().EmitReport(R);
515 }
516 }
517 }
518}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000519
520void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
521 const Expr *RetE = S->getRetValue();
522 if (!RetE)
523 return;
524
525 const GRState *state = C.getState();
526
Ted Kremenek13976632010-02-08 16:18:51 +0000527 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000528
529 if (!Sym)
530 return;
531
532 const RefState *RS = state->get<RegionState>(Sym);
533 if (!RS)
534 return;
535
536 // FIXME: check other cases.
537 if (RS->isAllocated())
538 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
539
Ted Kremenek19d67b52009-11-23 22:22:01 +0000540 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000541}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000542
543const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
544 bool Assumption) {
545 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
546 // FIXME: should also check symbols assumed to non-null.
547
548 RegionStateTy RS = state->get<RegionState>();
549
550 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
551 if (state->getSymVal(I.getKey()))
552 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
553 }
554
555 return state;
556}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000557
558// Check if the location is a freed symbolic region.
559void MallocChecker::VisitLocation(CheckerContext &C, const Stmt *S, SVal l) {
560 SymbolRef Sym = l.getLocSymbolInBase();
561 if (Sym) {
562 const RefState *RS = C.getState()->get<RegionState>(Sym);
563 if (RS)
564 if (RS->isReleased()) {
565 ExplodedNode *N = C.GenerateSink();
566 if (!BT_UseFree)
567 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
568 " it is freed.");
569
570 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
571 N);
572 C.EmitReport(R);
573 }
574 }
575}