blob: 72f6f815efbb7abe6e57dd842b5f923787cd0f43 [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 {
Ted Kremenekdde201b2010-08-06 21:12:55 +000027 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
28 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000029 const Stmt *S;
30
Zhongxing Xu7fb14642009-12-11 00:55:44 +000031public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000032 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
33
Zhongxing Xub94b81a2009-12-31 06:13:07 +000034 bool isAllocated() const { return K == AllocateUnchecked; }
Chris Lattnerfae96222010-09-03 04:34:38 +000035 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000036 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000037 //bool isEscaped() const { return K == Escaped; }
38 //bool isRelinquished() const { return K == Relinquished; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000039
40 bool operator==(const RefState &X) const {
41 return K == X.K && S == X.S;
42 }
43
Zhongxing Xub94b81a2009-12-31 06:13:07 +000044 static RefState getAllocateUnchecked(const Stmt *s) {
45 return RefState(AllocateUnchecked, s);
46 }
47 static RefState getAllocateFailed() {
48 return RefState(AllocateFailed, 0);
49 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000050 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
51 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000052 static RefState getRelinquished(const Stmt *s) {
53 return RefState(Relinquished, s);
54 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000055
56 void Profile(llvm::FoldingSetNodeID &ID) const {
57 ID.AddInteger(K);
58 ID.AddPointer(S);
59 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000060};
61
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000062class RegionState {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +000063
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000064class MallocChecker : public CheckerVisitor<MallocChecker> {
Zhongxing Xu589c0f22009-11-12 08:38:56 +000065 BuiltinBug *BT_DoubleFree;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +000066 BuiltinBug *BT_Leak;
Zhongxing Xuc8023782010-03-10 04:58:55 +000067 BuiltinBug *BT_UseFree;
Ted Kremenekdd0e4902010-07-31 01:52:11 +000068 BuiltinBug *BT_UseRelinquished;
Jordy Rose43859f62010-06-07 19:32:37 +000069 BuiltinBug *BT_BadFree;
Zhongxing Xua5ce9662010-06-01 03:01:33 +000070 IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000071
72public:
Zhongxing Xud9c84c82009-12-12 12:29:38 +000073 MallocChecker()
Ted Kremenekdde201b2010-08-06 21:12:55 +000074 : BT_DoubleFree(0), BT_Leak(0), BT_UseFree(0), BT_UseRelinquished(0),
75 BT_BadFree(0),
Zhongxing Xua5ce9662010-06-01 03:01:33 +000076 II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Zhongxing Xu589c0f22009-11-12 08:38:56 +000077 static void *getTag();
Ted Kremenek9c149532010-12-01 21:57:22 +000078 bool evalCallExpr(CheckerContext &C, const CallExpr *CE);
79 void evalDeadSymbols(CheckerContext &C, SymbolReaper &SymReaper);
80 void evalEndPath(GREndPathNodeBuilder &B, void *tag, GRExprEngine &Eng);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +000081 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
Ted Kremenek9c149532010-12-01 21:57:22 +000082 const GRState *evalAssume(const GRState *state, SVal Cond, bool Assumption,
Jordy Rose72905cf2010-08-04 07:10:57 +000083 bool *respondsToCallback);
Zhongxing Xuc8023782010-03-10 04:58:55 +000084 void VisitLocation(CheckerContext &C, const Stmt *S, SVal l);
Ted Kremenek79d73042010-09-02 00:56:20 +000085 virtual void PreVisitBind(CheckerContext &C, const Stmt *StoreE,
86 SVal location, SVal val);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000087
Zhongxing Xu7b760962009-11-13 07:25:27 +000088private:
Zhongxing Xu589c0f22009-11-12 08:38:56 +000089 void MallocMem(CheckerContext &C, const CallExpr *CE);
Ted Kremenekdde201b2010-08-06 21:12:55 +000090 void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
91 const OwnershipAttr* Att);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000092 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +000093 const Expr *SizeEx, SVal Init,
94 const GRState *state) {
95 return MallocMemAux(C, CE, state->getSVal(SizeEx), Init, state);
96 }
97 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
98 SVal SizeEx, SVal Init,
99 const GRState *state);
100
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000101 void FreeMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose2a479922010-08-12 08:54:03 +0000102 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
103 const OwnershipAttr* Att);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000104 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000105 const GRState *state, unsigned Num, bool Hold);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000106
107 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000108 void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000109
110 bool SummarizeValue(llvm::raw_ostream& os, SVal V);
111 bool SummarizeRegion(llvm::raw_ostream& os, const MemRegion *MR);
112 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000113};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000114} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000115
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000116typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
117
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000118namespace clang {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000119 template <>
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000120 struct GRStateTrait<RegionState>
Jordy Rose09cef092010-08-18 04:26:59 +0000121 : public GRStatePartialTrait<RegionStateTy> {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000122 static void *GDMIndex() { return MallocChecker::getTag(); }
123 };
124}
125
Zhongxing Xu7b760962009-11-13 07:25:27 +0000126void clang::RegisterMallocChecker(GRExprEngine &Eng) {
127 Eng.registerCheck(new MallocChecker());
128}
129
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000130void *MallocChecker::getTag() {
131 static int x;
132 return &x;
133}
134
Ted Kremenek9c149532010-12-01 21:57:22 +0000135bool MallocChecker::evalCallExpr(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000136 const GRState *state = C.getState();
137 const Expr *Callee = CE->getCallee();
Ted Kremenek13976632010-02-08 16:18:51 +0000138 SVal L = state->getSVal(Callee);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000139
140 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000141 if (!FD)
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000142 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000143
144 ASTContext &Ctx = C.getASTContext();
145 if (!II_malloc)
146 II_malloc = &Ctx.Idents.get("malloc");
147 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000148 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000149 if (!II_realloc)
150 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000151 if (!II_calloc)
152 II_calloc = &Ctx.Idents.get("calloc");
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000153
154 if (FD->getIdentifier() == II_malloc) {
155 MallocMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000156 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000157 }
158
159 if (FD->getIdentifier() == II_free) {
160 FreeMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000161 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000162 }
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000163
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000164 if (FD->getIdentifier() == II_realloc) {
165 ReallocMem(C, CE);
166 return true;
167 }
168
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000169 if (FD->getIdentifier() == II_calloc) {
170 CallocMem(C, CE);
171 return true;
172 }
173
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000174 // Check all the attributes, if there are any.
175 // There can be multiple of these attributes.
176 bool rv = false;
177 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000178 for (specific_attr_iterator<OwnershipAttr>
179 i = FD->specific_attr_begin<OwnershipAttr>(),
180 e = FD->specific_attr_end<OwnershipAttr>();
181 i != e; ++i) {
182 switch ((*i)->getOwnKind()) {
183 case OwnershipAttr::Returns: {
184 MallocMemReturnsAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000185 rv = true;
186 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000187 }
188 case OwnershipAttr::Takes:
189 case OwnershipAttr::Holds: {
190 FreeMemAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000191 rv = true;
192 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000193 }
Jordy Rose2a479922010-08-12 08:54:03 +0000194 default:
Jordy Rose2a479922010-08-12 08:54:03 +0000195 break;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000196 }
197 }
198 }
199 return rv;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000200}
201
202void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000203 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
204 C.getState());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000205 C.addTransition(state);
206}
207
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000208void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
209 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000210 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000211 return;
212
Sean Huntcf807c42010-08-18 23:23:40 +0000213 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000214 if (I != E) {
215 const GRState *state =
216 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
217 C.addTransition(state);
218 return;
219 }
220 const GRState *state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
221 C.getState());
222 C.addTransition(state);
223}
224
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000225const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
226 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000227 SVal Size, SVal Init,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000228 const GRState *state) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000229 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
230 ValueManager &ValMgr = C.getValueManager();
231
Jordy Rose32f26562010-07-04 00:00:41 +0000232 // Set the return value.
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000233 SVal RetVal = ValMgr.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
Jordy Rose32f26562010-07-04 00:00:41 +0000234 state = state->BindExpr(CE, RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000235
Jordy Rose32f26562010-07-04 00:00:41 +0000236 // Fill the region with the initialization value.
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000237 state = state->bindDefault(RetVal, Init);
238
Jordy Rose32f26562010-07-04 00:00:41 +0000239 // Set the region's extent equal to the Size parameter.
240 const SymbolicRegion *R = cast<SymbolicRegion>(RetVal.getAsRegion());
241 DefinedOrUnknownSVal Extent = R->getExtent(ValMgr);
242 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
243
Ted Kremenek846eabd2010-12-01 21:28:31 +0000244 SValBuilder &svalBuilder = ValMgr.getSValBuilder();
Jordy Rose32f26562010-07-04 00:00:41 +0000245 DefinedOrUnknownSVal ExtentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000246 svalBuilder.evalEQ(state, Extent, DefinedSize);
Ted Kremenek28f47b92010-12-01 22:16:56 +0000247 state = state->assume(ExtentMatchesSize, true);
Jordy Rose32f26562010-07-04 00:00:41 +0000248
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000249 SymbolRef Sym = RetVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000250 assert(Sym);
251 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000252 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000253}
254
255void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000256 const GRState *state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000257
258 if (state)
259 C.addTransition(state);
260}
261
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000262void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Jordy Rose2a479922010-08-12 08:54:03 +0000263 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000264 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000265 return;
266
Sean Huntcf807c42010-08-18 23:23:40 +0000267 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
268 I != E; ++I) {
269 const GRState *state = FreeMemAux(C, CE, C.getState(), *I,
270 Att->getOwnKind() == OwnershipAttr::Holds);
271 if (state)
272 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000273 }
274}
275
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000276const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000277 const GRState *state, unsigned Num,
278 bool Hold) {
279 const Expr *ArgExpr = CE->getArg(Num);
Jordy Rose43859f62010-06-07 19:32:37 +0000280 SVal ArgVal = state->getSVal(ArgExpr);
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000281
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000282 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
283
284 // Check for null dereferences.
285 if (!isa<Loc>(location))
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000286 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000287
288 // FIXME: Technically using 'Assume' here can result in a path
289 // bifurcation. In such cases we need to return two states, not just one.
290 const GRState *notNullState, *nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000291 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000292
293 // The explicit NULL case, no operation is performed.
294 if (nullState && !notNullState)
295 return nullState;
296
297 assert(notNullState);
298
Jordy Rose43859f62010-06-07 19:32:37 +0000299 // Unknown values could easily be okay
300 // Undefined values are handled elsewhere
301 if (ArgVal.isUnknownOrUndef())
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000302 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000303
Jordy Rose43859f62010-06-07 19:32:37 +0000304 const MemRegion *R = ArgVal.getAsRegion();
305
306 // Nonlocs can't be freed, of course.
307 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
308 if (!R) {
309 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
310 return NULL;
311 }
312
313 R = R->StripCasts();
314
315 // Blocks might show up as heap data, but should not be free()d
316 if (isa<BlockDataRegion>(R)) {
317 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
318 return NULL;
319 }
320
321 const MemSpaceRegion *MS = R->getMemorySpace();
322
323 // Parameters, locals, statics, and globals shouldn't be freed.
324 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
325 // FIXME: at the time this code was written, malloc() regions were
326 // represented by conjured symbols, which are all in UnknownSpaceRegion.
327 // This means that there isn't actually anything from HeapSpaceRegion
328 // that should be freed, even though we allow it here.
329 // Of course, free() can work on memory allocated outside the current
330 // function, so UnknownSpaceRegion is always a possibility.
331 // False negatives are better than false positives.
332
333 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
334 return NULL;
335 }
336
337 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
338 // Various cases could lead to non-symbol values here.
339 // For now, ignore them.
340 if (!SR)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000341 return notNullState;
Jordy Rose43859f62010-06-07 19:32:37 +0000342
343 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000344 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000345
346 // If the symbol has not been tracked, return. This is possible when free() is
347 // called on a pointer that does not get its pointee directly from malloc().
348 // Full support of this requires inter-procedural analysis.
349 if (!RS)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000350 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000351
352 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000353 if (RS->isReleased()) {
Ted Kremenek8c912302010-08-06 21:12:53 +0000354 if (ExplodedNode *N = C.GenerateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000355 if (!BT_DoubleFree)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000356 BT_DoubleFree
357 = new BuiltinBug("Double free",
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000358 "Try to free a memory block that has been released");
359 // FIXME: should find where it's freed last time.
360 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000361 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000362 C.EmitReport(R);
363 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000364 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000365 }
366
367 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000368 if (Hold)
369 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
370 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000371}
372
Jordy Rose43859f62010-06-07 19:32:37 +0000373bool MallocChecker::SummarizeValue(llvm::raw_ostream& os, SVal V) {
374 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
375 os << "an integer (" << IntVal->getValue() << ")";
376 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
377 os << "a constant address (" << ConstAddr->getValue() << ")";
378 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
379 os << "the address of the label '"
380 << Label->getLabel()->getID()->getName()
381 << "'";
382 else
383 return false;
384
385 return true;
386}
387
388bool MallocChecker::SummarizeRegion(llvm::raw_ostream& os,
389 const MemRegion *MR) {
390 switch (MR->getKind()) {
391 case MemRegion::FunctionTextRegionKind: {
392 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
393 if (FD)
394 os << "the address of the function '" << FD << "'";
395 else
396 os << "the address of a function";
397 return true;
398 }
399 case MemRegion::BlockTextRegionKind:
400 os << "block text";
401 return true;
402 case MemRegion::BlockDataRegionKind:
403 // FIXME: where the block came from?
404 os << "a block";
405 return true;
406 default: {
407 const MemSpaceRegion *MS = MR->getMemorySpace();
408
409 switch (MS->getKind()) {
410 case MemRegion::StackLocalsSpaceRegionKind: {
411 const VarRegion *VR = dyn_cast<VarRegion>(MR);
412 const VarDecl *VD;
413 if (VR)
414 VD = VR->getDecl();
415 else
416 VD = NULL;
417
418 if (VD)
419 os << "the address of the local variable '" << VD->getName() << "'";
420 else
421 os << "the address of a local stack variable";
422 return true;
423 }
424 case MemRegion::StackArgumentsSpaceRegionKind: {
425 const VarRegion *VR = dyn_cast<VarRegion>(MR);
426 const VarDecl *VD;
427 if (VR)
428 VD = VR->getDecl();
429 else
430 VD = NULL;
431
432 if (VD)
433 os << "the address of the parameter '" << VD->getName() << "'";
434 else
435 os << "the address of a parameter";
436 return true;
437 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000438 case MemRegion::NonStaticGlobalSpaceRegionKind:
439 case MemRegion::StaticGlobalSpaceRegionKind: {
Jordy Rose43859f62010-06-07 19:32:37 +0000440 const VarRegion *VR = dyn_cast<VarRegion>(MR);
441 const VarDecl *VD;
442 if (VR)
443 VD = VR->getDecl();
444 else
445 VD = NULL;
446
447 if (VD) {
448 if (VD->isStaticLocal())
449 os << "the address of the static variable '" << VD->getName() << "'";
450 else
451 os << "the address of the global variable '" << VD->getName() << "'";
452 } else
453 os << "the address of a global variable";
454 return true;
455 }
456 default:
457 return false;
458 }
459 }
460 }
461}
462
463void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
464 SourceRange range) {
Ted Kremenek8c912302010-08-06 21:12:53 +0000465 if (ExplodedNode *N = C.GenerateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000466 if (!BT_BadFree)
467 BT_BadFree = new BuiltinBug("Bad free");
468
469 llvm::SmallString<100> buf;
470 llvm::raw_svector_ostream os(buf);
471
472 const MemRegion *MR = ArgVal.getAsRegion();
473 if (MR) {
474 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
475 MR = ER->getSuperRegion();
476
477 // Special case for alloca()
478 if (isa<AllocaRegion>(MR))
479 os << "Argument to free() was allocated by alloca(), not malloc()";
480 else {
481 os << "Argument to free() is ";
482 if (SummarizeRegion(os, MR))
483 os << ", which is not memory allocated by malloc()";
484 else
485 os << "not memory allocated by malloc()";
486 }
487 } else {
488 os << "Argument to free() is ";
489 if (SummarizeValue(os, ArgVal))
490 os << ", which is not memory allocated by malloc()";
491 else
492 os << "not memory allocated by malloc()";
493 }
494
Jordy Rose31041242010-06-08 22:59:01 +0000495 EnhancedBugReport *R = new EnhancedBugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000496 R->addRange(range);
497 C.EmitReport(R);
498 }
499}
500
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000501void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
502 const GRState *state = C.getState();
503 const Expr *Arg0 = CE->getArg(0);
Ted Kremenek13976632010-02-08 16:18:51 +0000504 DefinedOrUnknownSVal Arg0Val=cast<DefinedOrUnknownSVal>(state->getSVal(Arg0));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000505
506 ValueManager &ValMgr = C.getValueManager();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000507 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000508
Ted Kremenek9c149532010-12-01 21:57:22 +0000509 DefinedOrUnknownSVal PtrEQ = svalBuilder.evalEQ(state, Arg0Val, ValMgr.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000510
511 // If the ptr is NULL, the call is equivalent to malloc(size).
Ted Kremenek28f47b92010-12-01 22:16:56 +0000512 if (const GRState *stateEqual = state->assume(PtrEQ, true)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000513 // Hack: set the NULL symbolic region to released to suppress false warning.
514 // In the future we should add more states for allocated regions, e.g.,
515 // CheckedNull, CheckedNonNull.
516
517 SymbolRef Sym = Arg0Val.getAsLocSymbol();
518 if (Sym)
519 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
520
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000521 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
522 UndefinedVal(), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000523 C.addTransition(stateMalloc);
524 }
525
Ted Kremenek28f47b92010-12-01 22:16:56 +0000526 if (const GRState *stateNotEqual = state->assume(PtrEQ, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000527 const Expr *Arg1 = CE->getArg(1);
528 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek13976632010-02-08 16:18:51 +0000529 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Ted Kremenek9c149532010-12-01 21:57:22 +0000530 DefinedOrUnknownSVal SizeZero = svalBuilder.evalEQ(stateNotEqual, Arg1Val,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000531 ValMgr.makeIntValWithPtrWidth(0, false));
532
Ted Kremenek28f47b92010-12-01 22:16:56 +0000533 if (const GRState *stateSizeZero = stateNotEqual->assume(SizeZero, true)) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000534 const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero, 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000535 if (stateFree)
536 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
537 }
538
Ted Kremenek28f47b92010-12-01 22:16:56 +0000539 if (const GRState *stateSizeNotZero=stateNotEqual->assume(SizeZero,false)) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000540 const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero, 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000541 if (stateFree) {
542 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000543 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000544 UnknownVal(), stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000545 C.addTransition(stateRealloc);
546 }
547 }
548 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000549}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000550
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000551void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
552 const GRState *state = C.getState();
553
554 ValueManager &ValMgr = C.getValueManager();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000555 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000556
557 SVal Count = state->getSVal(CE->getArg(0));
558 SVal EleSize = state->getSVal(CE->getArg(1));
Ted Kremenek9c149532010-12-01 21:57:22 +0000559 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, Count, EleSize,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000560 ValMgr.getContext().getSizeType());
561
562 SVal Zero = ValMgr.makeZeroVal(ValMgr.getContext().CharTy);
563
564 state = MallocMemAux(C, CE, TotalSize, Zero, state);
565 C.addTransition(state);
566}
567
Ted Kremenek9c149532010-12-01 21:57:22 +0000568void MallocChecker::evalDeadSymbols(CheckerContext &C,SymbolReaper &SymReaper) {
Zhongxing Xu173ff562010-08-15 08:19:57 +0000569 if (!SymReaper.hasDeadSymbols())
570 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000571
Zhongxing Xu173ff562010-08-15 08:19:57 +0000572 const GRState *state = C.getState();
573 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000574 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000575
576 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
577 if (SymReaper.isDead(I->first)) {
578 if (I->second.isAllocated()) {
Zhongxing Xu649a33a2010-08-17 00:36:37 +0000579 if (ExplodedNode *N = C.GenerateNode()) {
Zhongxing Xu173ff562010-08-15 08:19:57 +0000580 if (!BT_Leak)
581 BT_Leak = new BuiltinBug("Memory leak",
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000582 "Allocated memory never released. Potential memory leak.");
Zhongxing Xu173ff562010-08-15 08:19:57 +0000583 // FIXME: where it is allocated.
584 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
585 C.EmitReport(R);
586 }
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000587 }
Jordy Rose90760142010-08-18 04:33:47 +0000588
589 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000590 RS = F.remove(RS, I->first);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000591 }
592 }
Jordy Rose90760142010-08-18 04:33:47 +0000593
594 state = state->set<RegionState>(RS);
595 C.GenerateNode(state);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000596}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000597
Ted Kremenek9c149532010-12-01 21:57:22 +0000598void MallocChecker::evalEndPath(GREndPathNodeBuilder &B, void *tag,
Zhongxing Xu243fde92009-11-17 07:54:15 +0000599 GRExprEngine &Eng) {
Zhongxing Xuf605aae2009-11-22 13:22:34 +0000600 SaveAndRestore<bool> OldHasGen(B.HasGeneratedNode);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000601 const GRState *state = B.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000602 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000603
Jordy Rose09cef092010-08-18 04:26:59 +0000604 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000605 RefState RS = I->second;
606 if (RS.isAllocated()) {
607 ExplodedNode *N = B.generateNode(state, tag, B.getPredecessor());
608 if (N) {
609 if (!BT_Leak)
610 BT_Leak = new BuiltinBug("Memory leak",
611 "Allocated memory never released. Potential memory leak.");
612 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
613 Eng.getBugReporter().EmitReport(R);
614 }
615 }
616 }
617}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000618
619void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
620 const Expr *RetE = S->getRetValue();
621 if (!RetE)
622 return;
623
624 const GRState *state = C.getState();
625
Ted Kremenek13976632010-02-08 16:18:51 +0000626 SymbolRef Sym = state->getSVal(RetE).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000627
628 if (!Sym)
629 return;
630
631 const RefState *RS = state->get<RegionState>(Sym);
632 if (!RS)
633 return;
634
635 // FIXME: check other cases.
636 if (RS->isAllocated())
637 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
638
Ted Kremenek19d67b52009-11-23 22:22:01 +0000639 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000640}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000641
Ted Kremenek9c149532010-12-01 21:57:22 +0000642const GRState *MallocChecker::evalAssume(const GRState *state, SVal Cond,
Jordy Rose72905cf2010-08-04 07:10:57 +0000643 bool Assumption,
644 bool * /* respondsToCallback */) {
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000645 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
646 // FIXME: should also check symbols assumed to non-null.
647
648 RegionStateTy RS = state->get<RegionState>();
649
650 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
651 if (state->getSymVal(I.getKey()))
652 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
653 }
654
655 return state;
656}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000657
658// Check if the location is a freed symbolic region.
659void MallocChecker::VisitLocation(CheckerContext &C, const Stmt *S, SVal l) {
660 SymbolRef Sym = l.getLocSymbolInBase();
661 if (Sym) {
662 const RefState *RS = C.getState()->get<RegionState>(Sym);
Ted Kremenekcea68652010-08-06 21:12:49 +0000663 if (RS && RS->isReleased()) {
664 if (ExplodedNode *N = C.GenerateNode()) {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000665 if (!BT_UseFree)
666 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
667 " it is freed.");
668
669 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
670 N);
671 C.EmitReport(R);
672 }
Ted Kremenekcea68652010-08-06 21:12:49 +0000673 }
Zhongxing Xuc8023782010-03-10 04:58:55 +0000674 }
675}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000676
677void MallocChecker::PreVisitBind(CheckerContext &C,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000678 const Stmt *StoreE,
679 SVal location,
680 SVal val) {
681 // The PreVisitBind implements the same algorithm as already used by the
682 // Objective C ownership checker: if the pointer escaped from this scope by
683 // assignment, let it go. However, assigning to fields of a stack-storage
684 // structure does not transfer ownership.
685
686 const GRState *state = C.getState();
687 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
688
689 // Check for null dereferences.
690 if (!isa<Loc>(l))
691 return;
692
693 // Before checking if the state is null, check if 'val' has a RefState.
694 // Only then should we check for null and bifurcate the state.
695 SymbolRef Sym = val.getLocSymbolInBase();
696 if (Sym) {
697 if (const RefState *RS = state->get<RegionState>(Sym)) {
698 // If ptr is NULL, no operation is performed.
699 const GRState *notNullState, *nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000700 llvm::tie(notNullState, nullState) = state->assume(l);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000701
702 // Generate a transition for 'nullState' to record the assumption
703 // that the state was null.
704 if (nullState)
705 C.addTransition(nullState);
706
707 if (!notNullState)
708 return;
709
710 if (RS->isAllocated()) {
711 // Something we presently own is being assigned somewhere.
712 const MemRegion *AR = location.getAsRegion();
713 if (!AR)
714 return;
715 AR = AR->StripCasts()->getBaseRegion();
716 do {
717 // If it is on the stack, we still own it.
718 if (AR->hasStackNonParametersStorage())
719 break;
720
721 // If the state can't represent this binding, we still own it.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000722 if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
723 UnknownVal())))
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000724 break;
725
726 // We no longer own this pointer.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000727 notNullState =
728 notNullState->set<RegionState>(Sym,
729 RefState::getRelinquished(StoreE));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000730 }
731 while (false);
732 }
733 C.addTransition(notNullState);
734 }
735 }
736}