blob: c110e0f6f833f4e02ab5c7aa8d52e178d580135d [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 Kyrtzidis312dbec2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000016#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000017#include "clang/StaticAnalyzer/Core/CheckerManager.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000019#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000023#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000024#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000025#include "llvm/ADT/STLExtras.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000026using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000027using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000028
29namespace {
30
Zhongxing Xu7fb14642009-12-11 00:55:44 +000031class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000032 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
33 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000034 const Stmt *S;
35
Zhongxing Xu7fb14642009-12-11 00:55:44 +000036public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000037 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
38
Zhongxing Xub94b81a2009-12-31 06:13:07 +000039 bool isAllocated() const { return K == AllocateUnchecked; }
Chris Lattnerfae96222010-09-03 04:34:38 +000040 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000041 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000042 //bool isEscaped() const { return K == Escaped; }
43 //bool isRelinquished() const { return K == Relinquished; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000044
45 bool operator==(const RefState &X) const {
46 return K == X.K && S == X.S;
47 }
48
Zhongxing Xub94b81a2009-12-31 06:13:07 +000049 static RefState getAllocateUnchecked(const Stmt *s) {
50 return RefState(AllocateUnchecked, s);
51 }
52 static RefState getAllocateFailed() {
53 return RefState(AllocateFailed, 0);
54 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000055 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
56 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000057 static RefState getRelinquished(const Stmt *s) {
58 return RefState(Relinquished, s);
59 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000060
61 void Profile(llvm::FoldingSetNodeID &ID) const {
62 ID.AddInteger(K);
63 ID.AddPointer(S);
64 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000065};
66
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000067class RegionState {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +000068
Anna Zaksb319e022012-02-08 20:13:28 +000069class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000070 check::EndPath,
71 check::PreStmt<ReturnStmt>,
Anna Zaksb319e022012-02-08 20:13:28 +000072 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000073 check::Location,
74 check::Bind,
75 eval::Assume>
76{
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000077 mutable OwningPtr<BuiltinBug> BT_DoubleFree;
78 mutable OwningPtr<BuiltinBug> BT_Leak;
79 mutable OwningPtr<BuiltinBug> BT_UseFree;
80 mutable OwningPtr<BuiltinBug> BT_UseRelinquished;
81 mutable OwningPtr<BuiltinBug> BT_BadFree;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000082 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000083
84public:
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000085 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +000086
87 /// In pessimistic mode, the checker assumes that it does not know which
88 /// functions might free the memory.
89 struct ChecksFilter {
90 DefaultBool CMallocPessimistic;
91 DefaultBool CMallocOptimistic;
92 };
93
94 ChecksFilter Filter;
95
Anna Zaksb319e022012-02-08 20:13:28 +000096 void initIdentifierInfo(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000097
Anna Zaksb319e022012-02-08 20:13:28 +000098 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000099 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000100 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000101 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000102 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000103 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000104 void checkLocation(SVal l, bool isLoad, const Stmt *S,
105 CheckerContext &C) const;
106 void checkBind(SVal location, SVal val, const Stmt*S,
107 CheckerContext &C) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000108
Zhongxing Xu7b760962009-11-13 07:25:27 +0000109private:
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000110 static void MallocMem(CheckerContext &C, const CallExpr *CE);
111 static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
112 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000113 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000114 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000115 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000116 return MallocMemAux(C, CE,
117 state->getSVal(SizeEx, C.getLocationContext()),
118 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000119 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000120 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000121 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000123
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000124 void FreeMem(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose2a479922010-08-12 08:54:03 +0000125 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000126 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000127 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
128 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000129 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000130
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000131 void ReallocMem(CheckerContext &C, const CallExpr *CE) const;
132 static void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000133
Anna Zaks91c2a112012-02-08 23:16:56 +0000134 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
135 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
136 const Stmt *S = 0) const;
137
Ted Kremenek9c378f72011-08-12 23:37:29 +0000138 static bool SummarizeValue(raw_ostream &os, SVal V);
139 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000140 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000141};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000142} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000143
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000144typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
145
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000146namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000147namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000148 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000149 struct ProgramStateTrait<RegionState>
150 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000151 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000152 };
153}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000154}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000155
Anna Zaksb319e022012-02-08 20:13:28 +0000156void MallocChecker::initIdentifierInfo(CheckerContext &C) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000157 ASTContext &Ctx = C.getASTContext();
158 if (!II_malloc)
159 II_malloc = &Ctx.Idents.get("malloc");
160 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000161 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000162 if (!II_realloc)
163 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000164 if (!II_calloc)
165 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000166}
167
168void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
169 const FunctionDecl *FD = C.getCalleeDecl(CE);
170 if (!FD)
171 return;
172 initIdentifierInfo(C);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000173
174 if (FD->getIdentifier() == II_malloc) {
175 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000176 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000177 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000178 if (FD->getIdentifier() == II_realloc) {
179 ReallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000180 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000181 }
182
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000183 if (FD->getIdentifier() == II_calloc) {
184 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000185 return;
186 }
187
188 if (FD->getIdentifier() == II_free) {
189 FreeMem(C, CE);
190 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000191 }
192
Anna Zaks91c2a112012-02-08 23:16:56 +0000193 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000194 // Check all the attributes, if there are any.
195 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000196 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000197 for (specific_attr_iterator<OwnershipAttr>
198 i = FD->specific_attr_begin<OwnershipAttr>(),
199 e = FD->specific_attr_end<OwnershipAttr>();
200 i != e; ++i) {
201 switch ((*i)->getOwnKind()) {
202 case OwnershipAttr::Returns: {
203 MallocMemReturnsAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000204 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000205 }
206 case OwnershipAttr::Takes:
207 case OwnershipAttr::Holds: {
208 FreeMemAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000209 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000210 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000211 }
212 }
213 }
Anna Zaks91c2a112012-02-08 23:16:56 +0000214
215 if (Filter.CMallocPessimistic) {
216 ProgramStateRef State = C.getState();
217 // The pointer might escape through a function call.
218 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
219 E = CE->arg_end(); I != E; ++I) {
220 const Expr *A = *I;
221 if (A->getType().getTypePtr()->isAnyPointerType()) {
222 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
223 if (!Sym)
224 return;
225 checkEscape(Sym, A, C);
226 checkUseAfterFree(Sym, C, A);
227 }
228 }
229 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000230}
231
232void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000233 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000234 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000235 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000236}
237
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000238void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
239 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000240 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000241 return;
242
Sean Huntcf807c42010-08-18 23:23:40 +0000243 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000244 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000245 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000246 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000247 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000248 return;
249 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000250 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000251 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000252 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000253}
254
Anna Zaksb319e022012-02-08 20:13:28 +0000255ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000256 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000257 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000258 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000259 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000260
Anna Zaksb319e022012-02-08 20:13:28 +0000261 // Get the return value.
262 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000263
Jordy Rose32f26562010-07-04 00:00:41 +0000264 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000265 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000266
Jordy Rose32f26562010-07-04 00:00:41 +0000267 // Set the region's extent equal to the Size parameter.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000268 const SymbolicRegion *R = cast<SymbolicRegion>(retVal.getAsRegion());
269 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000270 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000271 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000272 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000273
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000274 state = state->assume(extentMatchesSize, true);
275 assert(state);
276
277 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000278 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000279
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000280 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000281 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000282}
283
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000284void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000285 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000286
287 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000288 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000289}
290
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000291void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000292 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000293 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000294 return;
295
Sean Huntcf807c42010-08-18 23:23:40 +0000296 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
297 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000298 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000299 FreeMemAux(C, CE, C.getState(), *I,
300 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000301 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000302 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000303 }
304}
305
Ted Kremenek8bef8232012-01-26 21:29:00 +0000306ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000307 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000308 ProgramStateRef state,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000309 unsigned Num,
310 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000311 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000312 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000313
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000314 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
315
316 // Check for null dereferences.
317 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000318 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000319
320 // FIXME: Technically using 'Assume' here can result in a path
321 // bifurcation. In such cases we need to return two states, not just one.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000322 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000323 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000324
325 // The explicit NULL case, no operation is performed.
326 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000327 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000328
329 assert(notNullState);
330
Jordy Rose43859f62010-06-07 19:32:37 +0000331 // Unknown values could easily be okay
332 // Undefined values are handled elsewhere
333 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000334 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000335
Jordy Rose43859f62010-06-07 19:32:37 +0000336 const MemRegion *R = ArgVal.getAsRegion();
337
338 // Nonlocs can't be freed, of course.
339 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
340 if (!R) {
341 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000342 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000343 }
344
345 R = R->StripCasts();
346
347 // Blocks might show up as heap data, but should not be free()d
348 if (isa<BlockDataRegion>(R)) {
349 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000350 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000351 }
352
353 const MemSpaceRegion *MS = R->getMemorySpace();
354
Anna Zaksb319e022012-02-08 20:13:28 +0000355 // TODO: Pessimize this. should be behinds a flag!
Jordy Rose43859f62010-06-07 19:32:37 +0000356 // Parameters, locals, statics, and globals shouldn't be freed.
357 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
358 // FIXME: at the time this code was written, malloc() regions were
359 // represented by conjured symbols, which are all in UnknownSpaceRegion.
360 // This means that there isn't actually anything from HeapSpaceRegion
361 // that should be freed, even though we allow it here.
362 // Of course, free() can work on memory allocated outside the current
363 // function, so UnknownSpaceRegion is always a possibility.
364 // False negatives are better than false positives.
365
366 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000367 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000368 }
369
370 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
371 // Various cases could lead to non-symbol values here.
372 // For now, ignore them.
373 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000374 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000375
376 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000377 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000378
379 // If the symbol has not been tracked, return. This is possible when free() is
380 // called on a pointer that does not get its pointee directly from malloc().
381 // Full support of this requires inter-procedural analysis.
382 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000383 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000384
385 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000386 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000387 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000388 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000389 BT_DoubleFree.reset(
390 new BuiltinBug("Double free",
391 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000392 // FIXME: should find where it's freed last time.
393 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000394 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000395 C.EmitReport(R);
396 }
Anna Zaksb319e022012-02-08 20:13:28 +0000397 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000398 }
399
400 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000401 if (Hold)
402 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
403 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000404}
405
Ted Kremenek9c378f72011-08-12 23:37:29 +0000406bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000407 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
408 os << "an integer (" << IntVal->getValue() << ")";
409 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
410 os << "a constant address (" << ConstAddr->getValue() << ")";
411 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000412 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000413 else
414 return false;
415
416 return true;
417}
418
Ted Kremenek9c378f72011-08-12 23:37:29 +0000419bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000420 const MemRegion *MR) {
421 switch (MR->getKind()) {
422 case MemRegion::FunctionTextRegionKind: {
423 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
424 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000425 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000426 else
427 os << "the address of a function";
428 return true;
429 }
430 case MemRegion::BlockTextRegionKind:
431 os << "block text";
432 return true;
433 case MemRegion::BlockDataRegionKind:
434 // FIXME: where the block came from?
435 os << "a block";
436 return true;
437 default: {
438 const MemSpaceRegion *MS = MR->getMemorySpace();
439
Anna Zakseb31a762012-01-04 23:54:01 +0000440 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000441 const VarRegion *VR = dyn_cast<VarRegion>(MR);
442 const VarDecl *VD;
443 if (VR)
444 VD = VR->getDecl();
445 else
446 VD = NULL;
447
448 if (VD)
449 os << "the address of the local variable '" << VD->getName() << "'";
450 else
451 os << "the address of a local stack variable";
452 return true;
453 }
Anna Zakseb31a762012-01-04 23:54:01 +0000454
455 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000456 const VarRegion *VR = dyn_cast<VarRegion>(MR);
457 const VarDecl *VD;
458 if (VR)
459 VD = VR->getDecl();
460 else
461 VD = NULL;
462
463 if (VD)
464 os << "the address of the parameter '" << VD->getName() << "'";
465 else
466 os << "the address of a parameter";
467 return true;
468 }
Anna Zakseb31a762012-01-04 23:54:01 +0000469
470 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000471 const VarRegion *VR = dyn_cast<VarRegion>(MR);
472 const VarDecl *VD;
473 if (VR)
474 VD = VR->getDecl();
475 else
476 VD = NULL;
477
478 if (VD) {
479 if (VD->isStaticLocal())
480 os << "the address of the static variable '" << VD->getName() << "'";
481 else
482 os << "the address of the global variable '" << VD->getName() << "'";
483 } else
484 os << "the address of a global variable";
485 return true;
486 }
Anna Zakseb31a762012-01-04 23:54:01 +0000487
488 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000489 }
490 }
491}
492
493void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000494 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000495 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000496 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000497 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000498
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000499 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000500 llvm::raw_svector_ostream os(buf);
501
502 const MemRegion *MR = ArgVal.getAsRegion();
503 if (MR) {
504 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
505 MR = ER->getSuperRegion();
506
507 // Special case for alloca()
508 if (isa<AllocaRegion>(MR))
509 os << "Argument to free() was allocated by alloca(), not malloc()";
510 else {
511 os << "Argument to free() is ";
512 if (SummarizeRegion(os, MR))
513 os << ", which is not memory allocated by malloc()";
514 else
515 os << "not memory allocated by malloc()";
516 }
517 } else {
518 os << "Argument to free() is ";
519 if (SummarizeValue(os, ArgVal))
520 os << ", which is not memory allocated by malloc()";
521 else
522 os << "not memory allocated by malloc()";
523 }
524
Anna Zakse172e8b2011-08-17 23:00:25 +0000525 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000526 R->addRange(range);
527 C.EmitReport(R);
528 }
529}
530
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000531void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000532 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000533 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000534 const LocationContext *LCtx = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000535 DefinedOrUnknownSVal arg0Val
Ted Kremenek5eca4822012-01-06 22:09:28 +0000536 = cast<DefinedOrUnknownSVal>(state->getSVal(arg0Expr, LCtx));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000537
Ted Kremenek846eabd2010-12-01 21:28:31 +0000538 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000539
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000540 DefinedOrUnknownSVal PtrEQ =
541 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000542
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000543 // Get the size argument. If there is no size arg then give up.
544 const Expr *Arg1 = CE->getArg(1);
545 if (!Arg1)
546 return;
547
548 // Get the value of the size argument.
549 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek5eca4822012-01-06 22:09:28 +0000550 cast<DefinedOrUnknownSVal>(state->getSVal(Arg1, LCtx));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000551
552 // Compare the size argument to 0.
553 DefinedOrUnknownSVal SizeZero =
554 svalBuilder.evalEQ(state, Arg1Val,
555 svalBuilder.makeIntValWithPtrWidth(0, false));
556
557 // If the ptr is NULL and the size is not 0, the call is equivalent to
558 // malloc(size).
Ted Kremenek8bef8232012-01-26 21:29:00 +0000559 ProgramStateRef stateEqual = state->assume(PtrEQ, true);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000560 if (stateEqual && state->assume(SizeZero, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000561 // Hack: set the NULL symbolic region to released to suppress false warning.
562 // In the future we should add more states for allocated regions, e.g.,
563 // CheckedNull, CheckedNonNull.
564
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000565 SymbolRef Sym = arg0Val.getAsLocSymbol();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000566 if (Sym)
567 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
568
Ted Kremenek8bef8232012-01-26 21:29:00 +0000569 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000570 UndefinedVal(), stateEqual);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000571 C.addTransition(stateMalloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000572 }
573
Ted Kremenek8bef8232012-01-26 21:29:00 +0000574 if (ProgramStateRef stateNotEqual = state->assume(PtrEQ, false)) {
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000575 // If the size is 0, free the memory.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000576 if (ProgramStateRef stateSizeZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000577 stateNotEqual->assume(SizeZero, true))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000578 if (ProgramStateRef stateFree =
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000579 FreeMemAux(C, CE, stateSizeZero, 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000580
Zhongxing Xud56763f2011-09-01 04:53:59 +0000581 // Bind the return value to NULL because it is now free.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000582 C.addTransition(stateFree->BindExpr(CE, LCtx,
583 svalBuilder.makeNull(), true));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000584 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000585 if (ProgramStateRef stateSizeNotZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000586 stateNotEqual->assume(SizeZero,false))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000587 if (ProgramStateRef stateFree = FreeMemAux(C, CE, stateSizeNotZero,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000588 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000589 // FIXME: We should copy the content of the original buffer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000590 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000591 UnknownVal(), stateFree);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000592 C.addTransition(stateRealloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000593 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000594 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000595}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000596
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000597void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000598 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000599 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000600 const LocationContext *LCtx = C.getLocationContext();
601 SVal count = state->getSVal(CE->getArg(0), LCtx);
602 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000603 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
604 svalBuilder.getContext().getSizeType());
605 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000606
Anna Zaks0bd6b112011-10-26 21:06:34 +0000607 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000608}
609
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000610void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
611 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000612{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000613 if (!SymReaper.hasDeadSymbols())
614 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000615
Ted Kremenek8bef8232012-01-26 21:29:00 +0000616 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000617 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000618 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000619
Ted Kremenek217470e2011-07-28 23:07:51 +0000620 bool generateReport = false;
621
Zhongxing Xu173ff562010-08-15 08:19:57 +0000622 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
623 if (SymReaper.isDead(I->first)) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000624 if (I->second.isAllocated())
625 generateReport = true;
Jordy Rose90760142010-08-18 04:33:47 +0000626
627 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000628 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000629
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000630 }
631 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000632
Anna Zaks0bd6b112011-10-26 21:06:34 +0000633 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000634
635 // FIXME: This does not handle when we have multiple leaks at a single
636 // place.
637 if (N && generateReport) {
638 if (!BT_Leak)
639 BT_Leak.reset(new BuiltinBug("Memory leak",
640 "Allocated memory never released. Potential memory leak."));
641 // FIXME: where it is allocated.
642 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
643 C.EmitReport(R);
644 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000645}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000646
Anna Zaksaf498a22011-10-25 19:56:48 +0000647void MallocChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000648 ProgramStateRef state = Ctx.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000649 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000650
Jordy Rose09cef092010-08-18 04:26:59 +0000651 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000652 RefState RS = I->second;
653 if (RS.isAllocated()) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000654 ExplodedNode *N = Ctx.addTransition(state);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000655 if (N) {
656 if (!BT_Leak)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000657 BT_Leak.reset(new BuiltinBug("Memory leak",
658 "Allocated memory never released. Potential memory leak."));
Zhongxing Xu243fde92009-11-17 07:54:15 +0000659 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Anna Zaksaf498a22011-10-25 19:56:48 +0000660 Ctx.EmitReport(R);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000661 }
662 }
663 }
664}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000665
Anna Zaks91c2a112012-02-08 23:16:56 +0000666bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
667 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000668 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000669 const RefState *RS = state->get<RegionState>(Sym);
670 if (!RS)
671 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000672
Anna Zaks91c2a112012-02-08 23:16:56 +0000673 if (RS->isAllocated()) {
674 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
675 C.addTransition(state);
676 return true;
677 }
678 return false;
679}
680
681void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
682 const Expr *E = S->getRetValue();
683 if (!E)
684 return;
685 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000686 if (!Sym)
687 return;
688
Anna Zaks91c2a112012-02-08 23:16:56 +0000689 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000690}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000691
Ted Kremenek8bef8232012-01-26 21:29:00 +0000692ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000693 SVal Cond,
694 bool Assumption) const {
Anna Zaks91c2a112012-02-08 23:16:56 +0000695 // If a symbolic region is assumed to NULL, set its state to AllocateFailed.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000696 // FIXME: should also check symbols assumed to non-null.
697
698 RegionStateTy RS = state->get<RegionState>();
699
700 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Zhongxing Xu2bfa3012011-04-02 03:20:45 +0000701 // If the symbol is assumed to NULL, this will return an APSInt*.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000702 if (state->getSymVal(I.getKey()))
703 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
704 }
705
706 return state;
707}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000708
Anna Zaks91c2a112012-02-08 23:16:56 +0000709bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
710 const Stmt *S) const {
711 assert(Sym);
712 const RefState *RS = C.getState()->get<RegionState>(Sym);
713 if (RS && RS->isReleased()) {
714 if (ExplodedNode *N = C.addTransition()) {
715 if (!BT_UseFree)
716 BT_UseFree.reset(new BuiltinBug("Use dynamically allocated memory "
717 "after it is freed."));
718
719 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
720 if (S)
721 R->addRange(S->getSourceRange());
722 C.EmitReport(R);
723 return true;
724 }
725 }
726 return false;
727}
728
Zhongxing Xuc8023782010-03-10 04:58:55 +0000729// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000730void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
731 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000732 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000733 if (Sym)
734 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000735}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000736
Anna Zaks390909c2011-10-06 00:43:15 +0000737void MallocChecker::checkBind(SVal location, SVal val,
738 const Stmt *BindS, CheckerContext &C) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000739 // The PreVisitBind implements the same algorithm as already used by the
740 // Objective C ownership checker: if the pointer escaped from this scope by
741 // assignment, let it go. However, assigning to fields of a stack-storage
742 // structure does not transfer ownership.
743
Ted Kremenek8bef8232012-01-26 21:29:00 +0000744 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000745 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
746
747 // Check for null dereferences.
748 if (!isa<Loc>(l))
749 return;
750
751 // Before checking if the state is null, check if 'val' has a RefState.
752 // Only then should we check for null and bifurcate the state.
753 SymbolRef Sym = val.getLocSymbolInBase();
754 if (Sym) {
755 if (const RefState *RS = state->get<RegionState>(Sym)) {
756 // If ptr is NULL, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000757 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000758 llvm::tie(notNullState, nullState) = state->assume(l);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000759
760 // Generate a transition for 'nullState' to record the assumption
761 // that the state was null.
762 if (nullState)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000763 C.addTransition(nullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000764
765 if (!notNullState)
766 return;
767
768 if (RS->isAllocated()) {
769 // Something we presently own is being assigned somewhere.
770 const MemRegion *AR = location.getAsRegion();
771 if (!AR)
772 return;
773 AR = AR->StripCasts()->getBaseRegion();
774 do {
775 // If it is on the stack, we still own it.
776 if (AR->hasStackNonParametersStorage())
777 break;
778
779 // If the state can't represent this binding, we still own it.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000780 if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
781 UnknownVal())))
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000782 break;
783
784 // We no longer own this pointer.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000785 notNullState =
786 notNullState->set<RegionState>(Sym,
Anna Zaks390909c2011-10-06 00:43:15 +0000787 RefState::getRelinquished(BindS));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000788 }
789 while (false);
790 }
Anna Zaks0bd6b112011-10-26 21:06:34 +0000791 C.addTransition(notNullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000792 }
793 }
794}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000795
Anna Zaks231361a2012-02-08 23:16:52 +0000796#define REGISTER_CHECKER(name) \
797void ento::register##name(CheckerManager &mgr) {\
798 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000799}
Anna Zaks231361a2012-02-08 23:16:52 +0000800
801REGISTER_CHECKER(MallocPessimistic)
802REGISTER_CHECKER(MallocOptimistic)