blob: 794740ab7203a61aec0d4e69c5ff19062d2c9798 [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
Argyrios Kyrtzidisaf1a9332011-02-08 22:30:11 +000015#include "ExperimentalChecks.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000016#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
17#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerVisitor.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/GRState.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000021#include "llvm/ADT/ImmutableMap.h"
22using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000023using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000024
25namespace {
26
Zhongxing Xu7fb14642009-12-11 00:55:44 +000027class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000028 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
29 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000030 const Stmt *S;
31
Zhongxing Xu7fb14642009-12-11 00:55:44 +000032public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000033 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
34
Zhongxing Xub94b81a2009-12-31 06:13:07 +000035 bool isAllocated() const { return K == AllocateUnchecked; }
Chris Lattnerfae96222010-09-03 04:34:38 +000036 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000037 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000038 //bool isEscaped() const { return K == Escaped; }
39 //bool isRelinquished() const { return K == Relinquished; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000040
41 bool operator==(const RefState &X) const {
42 return K == X.K && S == X.S;
43 }
44
Zhongxing Xub94b81a2009-12-31 06:13:07 +000045 static RefState getAllocateUnchecked(const Stmt *s) {
46 return RefState(AllocateUnchecked, s);
47 }
48 static RefState getAllocateFailed() {
49 return RefState(AllocateFailed, 0);
50 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000051 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
52 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000053 static RefState getRelinquished(const Stmt *s) {
54 return RefState(Relinquished, s);
55 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000056
57 void Profile(llvm::FoldingSetNodeID &ID) const {
58 ID.AddInteger(K);
59 ID.AddPointer(S);
60 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000061};
62
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000063class RegionState {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +000064
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000065class MallocChecker : public CheckerVisitor<MallocChecker> {
Zhongxing Xu589c0f22009-11-12 08:38:56 +000066 BuiltinBug *BT_DoubleFree;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +000067 BuiltinBug *BT_Leak;
Zhongxing Xuc8023782010-03-10 04:58:55 +000068 BuiltinBug *BT_UseFree;
Ted Kremenekdd0e4902010-07-31 01:52:11 +000069 BuiltinBug *BT_UseRelinquished;
Jordy Rose43859f62010-06-07 19:32:37 +000070 BuiltinBug *BT_BadFree;
Zhongxing Xua5ce9662010-06-01 03:01:33 +000071 IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000072
73public:
Zhongxing Xud9c84c82009-12-12 12:29:38 +000074 MallocChecker()
Ted Kremenekdde201b2010-08-06 21:12:55 +000075 : BT_DoubleFree(0), BT_Leak(0), BT_UseFree(0), BT_UseRelinquished(0),
76 BT_BadFree(0),
Zhongxing Xua5ce9662010-06-01 03:01:33 +000077 II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Zhongxing Xu589c0f22009-11-12 08:38:56 +000078 static void *getTag();
Ted Kremenek9c149532010-12-01 21:57:22 +000079 bool evalCallExpr(CheckerContext &C, const CallExpr *CE);
80 void evalDeadSymbols(CheckerContext &C, SymbolReaper &SymReaper);
Ted Kremeneke36de1f2011-01-11 02:34:45 +000081 void evalEndPath(EndOfFunctionNodeBuilder &B, void *tag, ExprEngine &Eng);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +000082 void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S);
Ted Kremenek9c149532010-12-01 21:57:22 +000083 const GRState *evalAssume(const GRState *state, SVal Cond, bool Assumption,
Jordy Rose72905cf2010-08-04 07:10:57 +000084 bool *respondsToCallback);
Argyrios Kyrtzidisf7fbbda2011-01-11 19:45:13 +000085 void visitLocation(CheckerContext &C, const Stmt *S, SVal l, bool isLoad);
Ted Kremenek79d73042010-09-02 00:56:20 +000086 virtual void PreVisitBind(CheckerContext &C, const Stmt *StoreE,
87 SVal location, SVal val);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000088
Zhongxing Xu7b760962009-11-13 07:25:27 +000089private:
Zhongxing Xu589c0f22009-11-12 08:38:56 +000090 void MallocMem(CheckerContext &C, const CallExpr *CE);
Ted Kremenekdde201b2010-08-06 21:12:55 +000091 void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
92 const OwnershipAttr* Att);
Zhongxing Xud9c84c82009-12-12 12:29:38 +000093 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +000094 const Expr *SizeEx, SVal Init,
95 const GRState *state) {
96 return MallocMemAux(C, CE, state->getSVal(SizeEx), Init, state);
97 }
98 const GRState *MallocMemAux(CheckerContext &C, const CallExpr *CE,
99 SVal SizeEx, SVal Init,
100 const GRState *state);
101
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000102 void FreeMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose2a479922010-08-12 08:54:03 +0000103 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
104 const OwnershipAttr* Att);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000105 const GRState *FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000106 const GRState *state, unsigned Num, bool Hold);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000107
108 void ReallocMem(CheckerContext &C, const CallExpr *CE);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000109 void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000110
111 bool SummarizeValue(llvm::raw_ostream& os, SVal V);
112 bool SummarizeRegion(llvm::raw_ostream& os, const MemRegion *MR);
113 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000114};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000115} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000116
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000117typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
118
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000119namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000120namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000121 template <>
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000122 struct GRStateTrait<RegionState>
Jordy Rose09cef092010-08-18 04:26:59 +0000123 : public GRStatePartialTrait<RegionStateTy> {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000124 static void *GDMIndex() { return MallocChecker::getTag(); }
125 };
126}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000127}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000128
Ted Kremenek9ef65372010-12-23 07:20:52 +0000129void ento::RegisterMallocChecker(ExprEngine &Eng) {
Zhongxing Xu7b760962009-11-13 07:25:27 +0000130 Eng.registerCheck(new MallocChecker());
131}
132
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000133void *MallocChecker::getTag() {
134 static int x;
135 return &x;
136}
137
Ted Kremenek9c149532010-12-01 21:57:22 +0000138bool MallocChecker::evalCallExpr(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000139 const GRState *state = C.getState();
140 const Expr *Callee = CE->getCallee();
Ted Kremenek13976632010-02-08 16:18:51 +0000141 SVal L = state->getSVal(Callee);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000142
143 const FunctionDecl *FD = L.getAsFunctionDecl();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000144 if (!FD)
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000145 return false;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000146
147 ASTContext &Ctx = C.getASTContext();
148 if (!II_malloc)
149 II_malloc = &Ctx.Idents.get("malloc");
150 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000151 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000152 if (!II_realloc)
153 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000154 if (!II_calloc)
155 II_calloc = &Ctx.Idents.get("calloc");
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000156
157 if (FD->getIdentifier() == II_malloc) {
158 MallocMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000159 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000160 }
161
162 if (FD->getIdentifier() == II_free) {
163 FreeMem(C, CE);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000164 return true;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000165 }
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000166
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000167 if (FD->getIdentifier() == II_realloc) {
168 ReallocMem(C, CE);
169 return true;
170 }
171
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000172 if (FD->getIdentifier() == II_calloc) {
173 CallocMem(C, CE);
174 return true;
175 }
176
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000177 // Check all the attributes, if there are any.
178 // There can be multiple of these attributes.
179 bool rv = false;
180 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000181 for (specific_attr_iterator<OwnershipAttr>
182 i = FD->specific_attr_begin<OwnershipAttr>(),
183 e = FD->specific_attr_end<OwnershipAttr>();
184 i != e; ++i) {
185 switch ((*i)->getOwnKind()) {
186 case OwnershipAttr::Returns: {
187 MallocMemReturnsAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000188 rv = true;
189 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000190 }
191 case OwnershipAttr::Takes:
192 case OwnershipAttr::Holds: {
193 FreeMemAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000194 rv = true;
195 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000196 }
Jordy Rose2a479922010-08-12 08:54:03 +0000197 default:
Jordy Rose2a479922010-08-12 08:54:03 +0000198 break;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000199 }
200 }
201 }
202 return rv;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000203}
204
205void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000206 const GRState *state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
207 C.getState());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000208 C.addTransition(state);
209}
210
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000211void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
212 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000213 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000214 return;
215
Sean Huntcf807c42010-08-18 23:23:40 +0000216 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000217 if (I != E) {
218 const GRState *state =
219 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
220 C.addTransition(state);
221 return;
222 }
223 const GRState *state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
224 C.getState());
225 C.addTransition(state);
226}
227
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000228const GRState *MallocChecker::MallocMemAux(CheckerContext &C,
229 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000230 SVal Size, SVal Init,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000231 const GRState *state) {
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000232 unsigned Count = C.getNodeBuilder().getCurrentBlockCount();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000233 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000234
Jordy Rose32f26562010-07-04 00:00:41 +0000235 // Set the return value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000236 SVal retVal = svalBuilder.getConjuredSymbolVal(NULL, CE, CE->getType(), Count);
237 state = state->BindExpr(CE, retVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000238
Jordy Rose32f26562010-07-04 00:00:41 +0000239 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000240 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000241
Jordy Rose32f26562010-07-04 00:00:41 +0000242 // Set the region's extent equal to the Size parameter.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000243 const SymbolicRegion *R = cast<SymbolicRegion>(retVal.getAsRegion());
244 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000245 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000246 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000247 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000248
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000249 state = state->assume(extentMatchesSize, true);
250 assert(state);
251
252 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000253 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000254
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000255 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000256 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000257}
258
259void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000260 const GRState *state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000261
262 if (state)
263 C.addTransition(state);
264}
265
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000266void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Jordy Rose2a479922010-08-12 08:54:03 +0000267 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000268 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000269 return;
270
Sean Huntcf807c42010-08-18 23:23:40 +0000271 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
272 I != E; ++I) {
273 const GRState *state = FreeMemAux(C, CE, C.getState(), *I,
274 Att->getOwnKind() == OwnershipAttr::Holds);
275 if (state)
276 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000277 }
278}
279
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000280const GRState *MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000281 const GRState *state, unsigned Num,
282 bool Hold) {
283 const Expr *ArgExpr = CE->getArg(Num);
Jordy Rose43859f62010-06-07 19:32:37 +0000284 SVal ArgVal = state->getSVal(ArgExpr);
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000285
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000286 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
287
288 // Check for null dereferences.
289 if (!isa<Loc>(location))
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000290 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000291
292 // FIXME: Technically using 'Assume' here can result in a path
293 // bifurcation. In such cases we need to return two states, not just one.
294 const GRState *notNullState, *nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000295 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000296
297 // The explicit NULL case, no operation is performed.
298 if (nullState && !notNullState)
299 return nullState;
300
301 assert(notNullState);
302
Jordy Rose43859f62010-06-07 19:32:37 +0000303 // Unknown values could easily be okay
304 // Undefined values are handled elsewhere
305 if (ArgVal.isUnknownOrUndef())
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000306 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000307
Jordy Rose43859f62010-06-07 19:32:37 +0000308 const MemRegion *R = ArgVal.getAsRegion();
309
310 // Nonlocs can't be freed, of course.
311 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
312 if (!R) {
313 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
314 return NULL;
315 }
316
317 R = R->StripCasts();
318
319 // Blocks might show up as heap data, but should not be free()d
320 if (isa<BlockDataRegion>(R)) {
321 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
322 return NULL;
323 }
324
325 const MemSpaceRegion *MS = R->getMemorySpace();
326
327 // Parameters, locals, statics, and globals shouldn't be freed.
328 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
329 // FIXME: at the time this code was written, malloc() regions were
330 // represented by conjured symbols, which are all in UnknownSpaceRegion.
331 // This means that there isn't actually anything from HeapSpaceRegion
332 // that should be freed, even though we allow it here.
333 // Of course, free() can work on memory allocated outside the current
334 // function, so UnknownSpaceRegion is always a possibility.
335 // False negatives are better than false positives.
336
337 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
338 return NULL;
339 }
340
341 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
342 // Various cases could lead to non-symbol values here.
343 // For now, ignore them.
344 if (!SR)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000345 return notNullState;
Jordy Rose43859f62010-06-07 19:32:37 +0000346
347 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000348 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000349
350 // If the symbol has not been tracked, return. This is possible when free() is
351 // called on a pointer that does not get its pointee directly from malloc().
352 // Full support of this requires inter-procedural analysis.
353 if (!RS)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000354 return notNullState;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000355
356 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000357 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000358 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000359 if (!BT_DoubleFree)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000360 BT_DoubleFree
361 = new BuiltinBug("Double free",
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000362 "Try to free a memory block that has been released");
363 // FIXME: should find where it's freed last time.
364 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000365 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000366 C.EmitReport(R);
367 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000368 return NULL;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000369 }
370
371 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000372 if (Hold)
373 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
374 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000375}
376
Jordy Rose43859f62010-06-07 19:32:37 +0000377bool MallocChecker::SummarizeValue(llvm::raw_ostream& os, SVal V) {
378 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
379 os << "an integer (" << IntVal->getValue() << ")";
380 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
381 os << "a constant address (" << ConstAddr->getValue() << ")";
382 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000383 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000384 else
385 return false;
386
387 return true;
388}
389
390bool MallocChecker::SummarizeRegion(llvm::raw_ostream& os,
391 const MemRegion *MR) {
392 switch (MR->getKind()) {
393 case MemRegion::FunctionTextRegionKind: {
394 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
395 if (FD)
396 os << "the address of the function '" << FD << "'";
397 else
398 os << "the address of a function";
399 return true;
400 }
401 case MemRegion::BlockTextRegionKind:
402 os << "block text";
403 return true;
404 case MemRegion::BlockDataRegionKind:
405 // FIXME: where the block came from?
406 os << "a block";
407 return true;
408 default: {
409 const MemSpaceRegion *MS = MR->getMemorySpace();
410
411 switch (MS->getKind()) {
412 case MemRegion::StackLocalsSpaceRegionKind: {
413 const VarRegion *VR = dyn_cast<VarRegion>(MR);
414 const VarDecl *VD;
415 if (VR)
416 VD = VR->getDecl();
417 else
418 VD = NULL;
419
420 if (VD)
421 os << "the address of the local variable '" << VD->getName() << "'";
422 else
423 os << "the address of a local stack variable";
424 return true;
425 }
426 case MemRegion::StackArgumentsSpaceRegionKind: {
427 const VarRegion *VR = dyn_cast<VarRegion>(MR);
428 const VarDecl *VD;
429 if (VR)
430 VD = VR->getDecl();
431 else
432 VD = NULL;
433
434 if (VD)
435 os << "the address of the parameter '" << VD->getName() << "'";
436 else
437 os << "the address of a parameter";
438 return true;
439 }
Ted Kremenekdcee3ce2010-07-01 20:16:50 +0000440 case MemRegion::NonStaticGlobalSpaceRegionKind:
441 case MemRegion::StaticGlobalSpaceRegionKind: {
Jordy Rose43859f62010-06-07 19:32:37 +0000442 const VarRegion *VR = dyn_cast<VarRegion>(MR);
443 const VarDecl *VD;
444 if (VR)
445 VD = VR->getDecl();
446 else
447 VD = NULL;
448
449 if (VD) {
450 if (VD->isStaticLocal())
451 os << "the address of the static variable '" << VD->getName() << "'";
452 else
453 os << "the address of the global variable '" << VD->getName() << "'";
454 } else
455 os << "the address of a global variable";
456 return true;
457 }
458 default:
459 return false;
460 }
461 }
462 }
463}
464
465void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
466 SourceRange range) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000467 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000468 if (!BT_BadFree)
469 BT_BadFree = new BuiltinBug("Bad free");
470
471 llvm::SmallString<100> buf;
472 llvm::raw_svector_ostream os(buf);
473
474 const MemRegion *MR = ArgVal.getAsRegion();
475 if (MR) {
476 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
477 MR = ER->getSuperRegion();
478
479 // Special case for alloca()
480 if (isa<AllocaRegion>(MR))
481 os << "Argument to free() was allocated by alloca(), not malloc()";
482 else {
483 os << "Argument to free() is ";
484 if (SummarizeRegion(os, MR))
485 os << ", which is not memory allocated by malloc()";
486 else
487 os << "not memory allocated by malloc()";
488 }
489 } else {
490 os << "Argument to free() is ";
491 if (SummarizeValue(os, ArgVal))
492 os << ", which is not memory allocated by malloc()";
493 else
494 os << "not memory allocated by malloc()";
495 }
496
Jordy Rose31041242010-06-08 22:59:01 +0000497 EnhancedBugReport *R = new EnhancedBugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000498 R->addRange(range);
499 C.EmitReport(R);
500 }
501}
502
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000503void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) {
504 const GRState *state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000505 const Expr *arg0Expr = CE->getArg(0);
506 DefinedOrUnknownSVal arg0Val
507 = cast<DefinedOrUnknownSVal>(state->getSVal(arg0Expr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000508
Ted Kremenek846eabd2010-12-01 21:28:31 +0000509 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000510
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000511 DefinedOrUnknownSVal PtrEQ =
512 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000513
514 // If the ptr is NULL, the call is equivalent to malloc(size).
Ted Kremenek28f47b92010-12-01 22:16:56 +0000515 if (const GRState *stateEqual = state->assume(PtrEQ, true)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000516 // Hack: set the NULL symbolic region to released to suppress false warning.
517 // In the future we should add more states for allocated regions, e.g.,
518 // CheckedNull, CheckedNonNull.
519
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000520 SymbolRef Sym = arg0Val.getAsLocSymbol();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000521 if (Sym)
522 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
523
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000524 const GRState *stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
525 UndefinedVal(), stateEqual);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000526 C.addTransition(stateMalloc);
527 }
528
Ted Kremenek28f47b92010-12-01 22:16:56 +0000529 if (const GRState *stateNotEqual = state->assume(PtrEQ, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000530 const Expr *Arg1 = CE->getArg(1);
531 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek13976632010-02-08 16:18:51 +0000532 cast<DefinedOrUnknownSVal>(stateNotEqual->getSVal(Arg1));
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000533 DefinedOrUnknownSVal SizeZero =
534 svalBuilder.evalEQ(stateNotEqual, Arg1Val,
535 svalBuilder.makeIntValWithPtrWidth(0, false));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000536
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000537 if (const GRState *stateSizeZero = stateNotEqual->assume(SizeZero, true))
538 if (const GRState *stateFree = FreeMemAux(C, CE, stateSizeZero, 0, false))
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000539 C.addTransition(stateFree->BindExpr(CE, UndefinedVal(), true));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000540
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000541 if (const GRState *stateSizeNotZero = stateNotEqual->assume(SizeZero,false))
542 if (const GRState *stateFree = FreeMemAux(C, CE, stateSizeNotZero,
543 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000544 // FIXME: We should copy the content of the original buffer.
Zhongxing Xu3ed04d32010-01-18 08:54:31 +0000545 const GRState *stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000546 UnknownVal(), stateFree);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000547 C.addTransition(stateRealloc);
548 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000549 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000550}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000551
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000552void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
553 const GRState *state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000554 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000555
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000556 SVal count = state->getSVal(CE->getArg(0));
557 SVal elementSize = state->getSVal(CE->getArg(1));
558 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
559 svalBuilder.getContext().getSizeType());
560 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000561
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000562 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000563}
564
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000565void MallocChecker::evalDeadSymbols(CheckerContext &C, SymbolReaper &SymReaper)
566{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000567 if (!SymReaper.hasDeadSymbols())
568 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000569
Zhongxing Xu173ff562010-08-15 08:19:57 +0000570 const GRState *state = C.getState();
571 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000572 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000573
574 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
575 if (SymReaper.isDead(I->first)) {
576 if (I->second.isAllocated()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000577 if (ExplodedNode *N = C.generateNode()) {
Zhongxing Xu173ff562010-08-15 08:19:57 +0000578 if (!BT_Leak)
579 BT_Leak = new BuiltinBug("Memory leak",
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000580 "Allocated memory never released. Potential memory leak.");
Zhongxing Xu173ff562010-08-15 08:19:57 +0000581 // FIXME: where it is allocated.
582 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
583 C.EmitReport(R);
584 }
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000585 }
Jordy Rose90760142010-08-18 04:33:47 +0000586
587 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000588 RS = F.remove(RS, I->first);
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000589 }
590 }
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000591 C.generateNode(state->set<RegionState>(RS));
Zhongxing Xu7b760962009-11-13 07:25:27 +0000592}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000593
Ted Kremeneke36de1f2011-01-11 02:34:45 +0000594void MallocChecker::evalEndPath(EndOfFunctionNodeBuilder &B, void *tag,
Argyrios Kyrtzidisd2592a32010-12-22 18:53:44 +0000595 ExprEngine &Eng) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000596 const GRState *state = B.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000597 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000598
Jordy Rose09cef092010-08-18 04:26:59 +0000599 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000600 RefState RS = I->second;
601 if (RS.isAllocated()) {
Argyrios Kyrtzidisf178ac82011-02-23 21:04:49 +0000602 ExplodedNode *N = B.generateNode(state);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000603 if (N) {
604 if (!BT_Leak)
605 BT_Leak = new BuiltinBug("Memory leak",
606 "Allocated memory never released. Potential memory leak.");
607 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
608 Eng.getBugReporter().EmitReport(R);
609 }
610 }
611 }
612}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000613
614void MallocChecker::PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000615 const Expr *retExpr = S->getRetValue();
616 if (!retExpr)
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000617 return;
618
619 const GRState *state = C.getState();
620
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000621 SymbolRef Sym = state->getSVal(retExpr).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000622 if (!Sym)
623 return;
624
625 const RefState *RS = state->get<RegionState>(Sym);
626 if (!RS)
627 return;
628
629 // FIXME: check other cases.
630 if (RS->isAllocated())
631 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
632
Ted Kremenek19d67b52009-11-23 22:22:01 +0000633 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000634}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000635
Ted Kremenek9c149532010-12-01 21:57:22 +0000636const GRState *MallocChecker::evalAssume(const GRState *state, SVal Cond,
Jordy Rose72905cf2010-08-04 07:10:57 +0000637 bool Assumption,
638 bool * /* respondsToCallback */) {
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000639 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
640 // FIXME: should also check symbols assumed to non-null.
641
642 RegionStateTy RS = state->get<RegionState>();
643
644 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
645 if (state->getSymVal(I.getKey()))
646 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
647 }
648
649 return state;
650}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000651
652// Check if the location is a freed symbolic region.
Argyrios Kyrtzidisf7fbbda2011-01-11 19:45:13 +0000653void MallocChecker::visitLocation(CheckerContext &C, const Stmt *S, SVal l,
654 bool isLoad) {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000655 SymbolRef Sym = l.getLocSymbolInBase();
656 if (Sym) {
657 const RefState *RS = C.getState()->get<RegionState>(Sym);
Ted Kremenekcea68652010-08-06 21:12:49 +0000658 if (RS && RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000659 if (ExplodedNode *N = C.generateNode()) {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000660 if (!BT_UseFree)
661 BT_UseFree = new BuiltinBug("Use dynamically allocated memory after"
662 " it is freed.");
663
664 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
665 N);
666 C.EmitReport(R);
667 }
Ted Kremenekcea68652010-08-06 21:12:49 +0000668 }
Zhongxing Xuc8023782010-03-10 04:58:55 +0000669 }
670}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000671
672void MallocChecker::PreVisitBind(CheckerContext &C,
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000673 const Stmt *StoreE,
674 SVal location,
675 SVal val) {
676 // The PreVisitBind implements the same algorithm as already used by the
677 // Objective C ownership checker: if the pointer escaped from this scope by
678 // assignment, let it go. However, assigning to fields of a stack-storage
679 // structure does not transfer ownership.
680
681 const GRState *state = C.getState();
682 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
683
684 // Check for null dereferences.
685 if (!isa<Loc>(l))
686 return;
687
688 // Before checking if the state is null, check if 'val' has a RefState.
689 // Only then should we check for null and bifurcate the state.
690 SymbolRef Sym = val.getLocSymbolInBase();
691 if (Sym) {
692 if (const RefState *RS = state->get<RegionState>(Sym)) {
693 // If ptr is NULL, no operation is performed.
694 const GRState *notNullState, *nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000695 llvm::tie(notNullState, nullState) = state->assume(l);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000696
697 // Generate a transition for 'nullState' to record the assumption
698 // that the state was null.
699 if (nullState)
700 C.addTransition(nullState);
701
702 if (!notNullState)
703 return;
704
705 if (RS->isAllocated()) {
706 // Something we presently own is being assigned somewhere.
707 const MemRegion *AR = location.getAsRegion();
708 if (!AR)
709 return;
710 AR = AR->StripCasts()->getBaseRegion();
711 do {
712 // If it is on the stack, we still own it.
713 if (AR->hasStackNonParametersStorage())
714 break;
715
716 // If the state can't represent this binding, we still own it.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000717 if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
718 UnknownVal())))
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000719 break;
720
721 // We no longer own this pointer.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000722 notNullState =
723 notNullState->set<RegionState>(Sym,
724 RefState::getRelinquished(StoreE));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000725 }
726 while (false);
727 }
728 C.addTransition(notNullState);
729 }
730 }
731}