blob: dcc21ca3861992c3bef248065f7f5365fd46497c [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
Jordy Rose32f26562010-07-04 00:00:41 +0000175 // Set the return value.
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000176 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
Jordy Rose32f26562010-07-04 00:00:41 +0000177 state = state->BindExpr(CE, RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000178
Jordy Rose32f26562010-07-04 00:00:41 +0000179 // Fill the region with the initialization value.
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000180 state = state->bindDefault(RetVal, Init);
181
Jordy Rose32f26562010-07-04 00:00:41 +0000182 // Set the region's extent equal to the Size parameter.
183 const SymbolicRegion *R = cast<SymbolicRegion>(RetVal.getAsRegion());
184 DefinedOrUnknownSVal Extent = R->getExtent(ValMgr);
185 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
186
187 SValuator &SVator = ValMgr.getSValuator();
188 DefinedOrUnknownSVal ExtentMatchesSize =
189 SVator.EvalEQ(state, Extent, DefinedSize);
190 state = state->Assume(ExtentMatchesSize, true);
191
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000192 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000193 assert(Sym);
194 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000195 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000196}
197
198void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000199 const GRState *state = FreeMemAux(C, CE, C.getState());
200
201 if (state)
202 C.addTransition(state);
203}
204
205const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
206 const GRState *state) {
Jordy Rose43859f62010-06-07 19:32:37 +0000207 const Expr *ArgExpr = CE->getArg(0);
208 SVal ArgVal = state->getSVal(ArgExpr);
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000209
210 // If ptr is NULL, no operation is preformed.
211 if (ArgVal.isZeroConstant())
212 return state;
Jordy Rose43859f62010-06-07 19:32:37 +0000213
214 // Unknown values could easily be okay
215 // Undefined values are handled elsewhere
216 if (ArgVal.isUnknownOrUndef())
Zhongxing Xu8e98ac12010-05-13 08:26:32 +0000217 return state;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000218
Jordy Rose43859f62010-06-07 19:32:37 +0000219 const MemRegion *R = ArgVal.getAsRegion();
220
221 // Nonlocs can't be freed, of course.
222 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
223 if (!R) {
224 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
225 return NULL;
226 }
227
228 R = R->StripCasts();
229
230 // Blocks might show up as heap data, but should not be free()d
231 if (isa<BlockDataRegion>(R)) {
232 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
233 return NULL;
234 }
235
236 const MemSpaceRegion *MS = R->getMemorySpace();
237
238 // Parameters, locals, statics, and globals shouldn't be freed.
239 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
240 // FIXME: at the time this code was written, malloc() regions were
241 // represented by conjured symbols, which are all in UnknownSpaceRegion.
242 // This means that there isn't actually anything from HeapSpaceRegion
243 // that should be freed, even though we allow it here.
244 // Of course, free() can work on memory allocated outside the current
245 // function, so UnknownSpaceRegion is always a possibility.
246 // False negatives are better than false positives.
247
248 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
249 return NULL;
250 }
251
252 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
253 // Various cases could lead to non-symbol values here.
254 // For now, ignore them.
255 if (!SR)
256 return state;
257
258 SymbolRef Sym = SR->getSymbol();
259
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000260 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000261
262 // If the symbol has not been tracked, return. This is possible when free() is
263 // called on a pointer that does not get its pointee directly from malloc().
264 // Full support of this requires inter-procedural analysis.
265 if (!RS)
266 return state;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000267
268 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000269 if (RS->isReleased()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000270 ExplodedNode *N = C.GenerateSink();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000271 if (N) {
272 if (!BT_DoubleFree)
273 BT_DoubleFree = new BuiltinBug("Double free",
274 "Try to free a memory block that has been released");
275 // FIXME: should find where it's freed last time.
276 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000277 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000278 C.EmitReport(R);
279 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000280 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000281 }
282
283 // Normal free.
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000284 return state->set<RegionState>(Sym, RefState::getReleased(CE));
285}
286
Jordy Rose43859f62010-06-07 19:32:37 +0000287bool MallocChecker::SummarizeValue(llvm::raw_ostream& os, SVal V) {
288 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
289 os << "an integer (" << IntVal->getValue() << ")";
290 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
291 os << "a constant address (" << ConstAddr->getValue() << ")";
292 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
293 os << "the address of the label '"
294 << Label->getLabel()->getID()->getName()
295 << "'";
296 else
297 return false;
298
299 return true;
300}
301
302bool MallocChecker::SummarizeRegion(llvm::raw_ostream& os,
303 const MemRegion *MR) {
304 switch (MR->getKind()) {
305 case MemRegion::FunctionTextRegionKind: {
306 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
307 if (FD)
308 os << "the address of the function '" << FD << "'";
309 else
310 os << "the address of a function";
311 return true;
312 }
313 case MemRegion::BlockTextRegionKind:
314 os << "block text";
315 return true;
316 case MemRegion::BlockDataRegionKind:
317 // FIXME: where the block came from?
318 os << "a block";
319 return true;
320 default: {
321 const MemSpaceRegion *MS = MR->getMemorySpace();
322
323 switch (MS->getKind()) {
324 case MemRegion::StackLocalsSpaceRegionKind: {
325 const VarRegion *VR = dyn_cast<VarRegion>(MR);
326 const VarDecl *VD;
327 if (VR)
328 VD = VR->getDecl();
329 else
330 VD = NULL;
331
332 if (VD)
333 os << "the address of the local variable '" << VD->getName() << "'";
334 else
335 os << "the address of a local stack variable";
336 return true;
337 }
338 case MemRegion::StackArgumentsSpaceRegionKind: {
339 const VarRegion *VR = dyn_cast<VarRegion>(MR);
340 const VarDecl *VD;
341 if (VR)
342 VD = VR->getDecl();
343 else
344 VD = NULL;
345
346 if (VD)
347 os << "the address of the parameter '" << VD->getName() << "'";
348 else
349 os << "the address of a parameter";
350 return true;
351 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000352 case MemRegion::NonStaticGlobalSpaceRegionKind:
353 case MemRegion::StaticGlobalSpaceRegionKind: {
Jordy Rose43859f62010-06-07 19:32:37 +0000354 const VarRegion *VR = dyn_cast<VarRegion>(MR);
355 const VarDecl *VD;
356 if (VR)
357 VD = VR->getDecl();
358 else
359 VD = NULL;
360
361 if (VD) {
362 if (VD->isStaticLocal())
363 os << "the address of the static variable '" << VD->getName() << "'";
364 else
365 os << "the address of the global variable '" << VD->getName() << "'";
366 } else
367 os << "the address of a global variable";
368 return true;
369 }
370 default:
371 return false;
372 }
373 }
374 }
375}
376
377void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
378 SourceRange range) {
379 ExplodedNode *N = C.GenerateSink();
380 if (N) {
381 if (!BT_BadFree)
382 BT_BadFree = new BuiltinBug("Bad free");
383
384 llvm::SmallString<100> buf;
385 llvm::raw_svector_ostream os(buf);
386
387 const MemRegion *MR = ArgVal.getAsRegion();
388 if (MR) {
389 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
390 MR = ER->getSuperRegion();
391
392 // Special case for alloca()
393 if (isa<AllocaRegion>(MR))
394 os << "Argument to free() was allocated by alloca(), not malloc()";
395 else {
396 os << "Argument to free() is ";
397 if (SummarizeRegion(os, MR))
398 os << ", which is not memory allocated by malloc()";
399 else
400 os << "not memory allocated by malloc()";
401 }
402 } else {
403 os << "Argument to free() is ";
404 if (SummarizeValue(os, ArgVal))
405 os << ", which is not memory allocated by malloc()";
406 else
407 os << "not memory allocated by malloc()";
408 }
409
Jordy Rose31041242010-06-08 22:59:01 +0000410 EnhancedBugReport *R = new EnhancedBugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000411 R->addRange(range);
412 C.EmitReport(R);
413 }
414}
415
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000416void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
417 const GRState *state = C.getState();
418 const Expr *Arg0 = CE->getArg(0);
Ted Kremenek13976632010-02-08 16:18:51 +0000419 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000420
421 ValueManager &ValMgr = C.getValueManager();
422 SValuator &SVator = C.getSValuator();
423
424 DefinedOrUnknownSVal PtrEQ = SVator.EvalEQ(state, Arg0Val, ValMgr.makeNull());
425
426 // If the ptr is NULL, the call is equivalent to malloc(size).
427 if (const GRState *stateEqual = state->Assume(PtrEQ, true)) {
428 // Hack: set the NULL symbolic region to released to suppress false warning.
429 // In the future we should add more states for allocated regions, e.g.,
430 // CheckedNull, CheckedNonNull.
431
432 SymbolRef Sym = Arg0Val.getAsLocSymbol();
433 if (Sym)
434 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
435
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000436 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
437 UndefinedVal(), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000438 C.addTransition(stateMalloc);
439 }
440
441 if (const GRState *stateNotEqual = state->Assume(PtrEQ, false)) {
442 const Expr *Arg1 = CE->getArg(1);
443 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek13976632010-02-08 16:18:51 +0000444 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000445 DefinedOrUnknownSVal SizeZero = SVator.EvalEQ(stateNotEqual, Arg1Val,
446 ValMgr.makeIntValWithPtrWidth(0, false));
447
448 if (const GRState *stateSizeZero = stateNotEqual->Assume(SizeZero, true)) {
449 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero);
450 if (stateFree)
451 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
452 }
453
454 if (const GRState *stateSizeNotZero=stateNotEqual->Assume(SizeZero,false)) {
455 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero);
456 if (stateFree) {
457 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000458 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000459 UnknownVal(), stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000460 C.addTransition(stateRealloc);
461 }
462 }
463 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000464}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000465
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000466void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
467 const GRState *state = C.getState();
468
469 ValueManager &ValMgr = C.getValueManager();
470 SValuator &SVator = C.getSValuator();
471
472 SVal Count = state->getSVal(CE->getArg(0));
473 SVal EleSize = state->getSVal(CE->getArg(1));
474 SVal TotalSize = SVator.EvalBinOp(state, BinaryOperator::Mul, Count, EleSize,
475 ValMgr.getContext().getSizeType());
476
477 SVal Zero = ValMgr.makeZeroVal(ValMgr.getContext().CharTy);
478
479 state = MallocMemAux(C, CE, TotalSize, Zero, state);
480 C.addTransition(state);
481}
482
Jordy Rose7dadf792010-07-01 20:09:55 +0000483void MallocChecker::EvalDeadSymbols(CheckerContext &C,SymbolReaper &SymReaper) {
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000484 for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
485 E = SymReaper.dead_end(); I != E; ++I) {
486 SymbolRef Sym = *I;
487 const GRState *state = C.getState();
488 const RefState *RS = state->get<RegionState>(Sym);
489 if (!RS)
490 return;
491
Zhongxing Xu243fde92009-11-17 07:54:15 +0000492 if (RS->isAllocated()) {
Ted Kremenek19d67b52009-11-23 22:22:01 +0000493 ExplodedNode *N = C.GenerateSink();
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000494 if (N) {
495 if (!BT_Leak)
496 BT_Leak = new BuiltinBug("Memory leak",
497 "Allocated memory never released. Potential memory leak.");
498 // FIXME: where it is allocated.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000499 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000500 C.EmitReport(R);
501 }
502 }
503 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000504}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000505
506void MallocChecker::EvalEndPath(GREndPathNodeBuilder &B, void *tag,
507 GRExprEngine &Eng) {
Zhongxing Xuf605aae2009-11-22 13:22:34 +0000508 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000509 const GRState *state = B.getState();
510 typedef llvm::ImmutableMap<SymbolRef, RefState> SymMap;
511 SymMap M = state->get<RegionState>();
512
513 for (SymMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
514 RefState RS = I->second;
515 if (RS.isAllocated()) {
516 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
517 if (N) {
518 if (!BT_Leak)
519 BT_Leak = new BuiltinBug("Memory leak",
520 "Allocated memory never released. Potential memory leak.");
521 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
522 Eng.getBugReporter().EmitReport(R);
523 }
524 }
525 }
526}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000527
528void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
529 const Expr *RetE = S->getRetValue();
530 if (!RetE)
531 return;
532
533 const GRState *state = C.getState();
534
Ted Kremenek13976632010-02-08 16:18:51 +0000535 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000536
537 if (!Sym)
538 return;
539
540 const RefState *RS = state->get<RegionState>(Sym);
541 if (!RS)
542 return;
543
544 // FIXME: check other cases.
545 if (RS->isAllocated())
546 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
547
Ted Kremenek19d67b52009-11-23 22:22:01 +0000548 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000549}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000550
551const GRState *MallocChecker::EvalAssume(const GRState *state, SVal Cond,
552 bool Assumption) {
553 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
554 // FIXME: should also check symbols assumed to non-null.
555
556 RegionStateTy RS = state->get<RegionState>();
557
558 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
559 if (state->getSymVal(I.getKey()))
560 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
561 }
562
563 return state;
564}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000565
566// Check if the location is a freed symbolic region.
567void MallocChecker::VisitLocation(CheckerContext &C, const Stmt *S, SVal l) {
568 SymbolRef Sym = l.getLocSymbolInBase();
569 if (Sym) {
570 const RefState *RS = C.getState()->get<RegionState>(Sym);
571 if (RS)
572 if (RS->isReleased()) {
573 ExplodedNode *N = C.GenerateSink();
574 if (!BT_UseFree)
575 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
576 " it is freed.");
577
578 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
579 N);
580 C.EmitReport(R);
581 }
582 }
583}