blob: 8f4e805e9575f145dee4b78855b2d1147a895cd7 [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
355 // Parameters, locals, statics, and globals shouldn't be freed.
356 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
357 // FIXME: at the time this code was written, malloc() regions were
358 // represented by conjured symbols, which are all in UnknownSpaceRegion.
359 // This means that there isn't actually anything from HeapSpaceRegion
360 // that should be freed, even though we allow it here.
361 // Of course, free() can work on memory allocated outside the current
362 // function, so UnknownSpaceRegion is always a possibility.
363 // False negatives are better than false positives.
364
365 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000366 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000367 }
368
369 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
370 // Various cases could lead to non-symbol values here.
371 // For now, ignore them.
372 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000373 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000374
375 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000376 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000377
378 // If the symbol has not been tracked, return. This is possible when free() is
379 // called on a pointer that does not get its pointee directly from malloc().
380 // Full support of this requires inter-procedural analysis.
381 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000382 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000383
384 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000385 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000386 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000387 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000388 BT_DoubleFree.reset(
389 new BuiltinBug("Double free",
390 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000391 // FIXME: should find where it's freed last time.
392 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000393 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000394 C.EmitReport(R);
395 }
Anna Zaksb319e022012-02-08 20:13:28 +0000396 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000397 }
398
399 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000400 if (Hold)
401 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
402 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000403}
404
Ted Kremenek9c378f72011-08-12 23:37:29 +0000405bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000406 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
407 os << "an integer (" << IntVal->getValue() << ")";
408 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
409 os << "a constant address (" << ConstAddr->getValue() << ")";
410 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000411 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000412 else
413 return false;
414
415 return true;
416}
417
Ted Kremenek9c378f72011-08-12 23:37:29 +0000418bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000419 const MemRegion *MR) {
420 switch (MR->getKind()) {
421 case MemRegion::FunctionTextRegionKind: {
422 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
423 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000424 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000425 else
426 os << "the address of a function";
427 return true;
428 }
429 case MemRegion::BlockTextRegionKind:
430 os << "block text";
431 return true;
432 case MemRegion::BlockDataRegionKind:
433 // FIXME: where the block came from?
434 os << "a block";
435 return true;
436 default: {
437 const MemSpaceRegion *MS = MR->getMemorySpace();
438
Anna Zakseb31a762012-01-04 23:54:01 +0000439 if (isa<StackLocalsSpaceRegion>(MS)) {
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 os << "the address of the local variable '" << VD->getName() << "'";
449 else
450 os << "the address of a local stack variable";
451 return true;
452 }
Anna Zakseb31a762012-01-04 23:54:01 +0000453
454 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000455 const VarRegion *VR = dyn_cast<VarRegion>(MR);
456 const VarDecl *VD;
457 if (VR)
458 VD = VR->getDecl();
459 else
460 VD = NULL;
461
462 if (VD)
463 os << "the address of the parameter '" << VD->getName() << "'";
464 else
465 os << "the address of a parameter";
466 return true;
467 }
Anna Zakseb31a762012-01-04 23:54:01 +0000468
469 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000470 const VarRegion *VR = dyn_cast<VarRegion>(MR);
471 const VarDecl *VD;
472 if (VR)
473 VD = VR->getDecl();
474 else
475 VD = NULL;
476
477 if (VD) {
478 if (VD->isStaticLocal())
479 os << "the address of the static variable '" << VD->getName() << "'";
480 else
481 os << "the address of the global variable '" << VD->getName() << "'";
482 } else
483 os << "the address of a global variable";
484 return true;
485 }
Anna Zakseb31a762012-01-04 23:54:01 +0000486
487 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000488 }
489 }
490}
491
492void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000493 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000494 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000495 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000496 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000497
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000498 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000499 llvm::raw_svector_ostream os(buf);
500
501 const MemRegion *MR = ArgVal.getAsRegion();
502 if (MR) {
503 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
504 MR = ER->getSuperRegion();
505
506 // Special case for alloca()
507 if (isa<AllocaRegion>(MR))
508 os << "Argument to free() was allocated by alloca(), not malloc()";
509 else {
510 os << "Argument to free() is ";
511 if (SummarizeRegion(os, MR))
512 os << ", which is not memory allocated by malloc()";
513 else
514 os << "not memory allocated by malloc()";
515 }
516 } else {
517 os << "Argument to free() is ";
518 if (SummarizeValue(os, ArgVal))
519 os << ", which is not memory allocated by malloc()";
520 else
521 os << "not memory allocated by malloc()";
522 }
523
Anna Zakse172e8b2011-08-17 23:00:25 +0000524 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000525 R->addRange(range);
526 C.EmitReport(R);
527 }
528}
529
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000530void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000531 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000532 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000533 const LocationContext *LCtx = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000534 DefinedOrUnknownSVal arg0Val
Ted Kremenek5eca4822012-01-06 22:09:28 +0000535 = cast<DefinedOrUnknownSVal>(state->getSVal(arg0Expr, LCtx));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000536
Ted Kremenek846eabd2010-12-01 21:28:31 +0000537 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000538
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000539 DefinedOrUnknownSVal PtrEQ =
540 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000541
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000542 // Get the size argument. If there is no size arg then give up.
543 const Expr *Arg1 = CE->getArg(1);
544 if (!Arg1)
545 return;
546
547 // Get the value of the size argument.
548 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek5eca4822012-01-06 22:09:28 +0000549 cast<DefinedOrUnknownSVal>(state->getSVal(Arg1, LCtx));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000550
551 // Compare the size argument to 0.
552 DefinedOrUnknownSVal SizeZero =
553 svalBuilder.evalEQ(state, Arg1Val,
554 svalBuilder.makeIntValWithPtrWidth(0, false));
555
556 // If the ptr is NULL and the size is not 0, the call is equivalent to
557 // malloc(size).
Ted Kremenek8bef8232012-01-26 21:29:00 +0000558 ProgramStateRef stateEqual = state->assume(PtrEQ, true);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000559 if (stateEqual && state->assume(SizeZero, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000560 // Hack: set the NULL symbolic region to released to suppress false warning.
561 // In the future we should add more states for allocated regions, e.g.,
562 // CheckedNull, CheckedNonNull.
563
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000564 SymbolRef Sym = arg0Val.getAsLocSymbol();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000565 if (Sym)
566 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
567
Ted Kremenek8bef8232012-01-26 21:29:00 +0000568 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000569 UndefinedVal(), stateEqual);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000570 C.addTransition(stateMalloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000571 }
572
Ted Kremenek8bef8232012-01-26 21:29:00 +0000573 if (ProgramStateRef stateNotEqual = state->assume(PtrEQ, false)) {
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000574 // If the size is 0, free the memory.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000575 if (ProgramStateRef stateSizeZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000576 stateNotEqual->assume(SizeZero, true))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000577 if (ProgramStateRef stateFree =
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000578 FreeMemAux(C, CE, stateSizeZero, 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000579
Zhongxing Xud56763f2011-09-01 04:53:59 +0000580 // Bind the return value to NULL because it is now free.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000581 C.addTransition(stateFree->BindExpr(CE, LCtx,
582 svalBuilder.makeNull(), true));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000583 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000584 if (ProgramStateRef stateSizeNotZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000585 stateNotEqual->assume(SizeZero,false))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000586 if (ProgramStateRef stateFree = FreeMemAux(C, CE, stateSizeNotZero,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000587 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000588 // FIXME: We should copy the content of the original buffer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000589 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000590 UnknownVal(), stateFree);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000591 C.addTransition(stateRealloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000592 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000593 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000594}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000595
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000596void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000597 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000598 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000599 const LocationContext *LCtx = C.getLocationContext();
600 SVal count = state->getSVal(CE->getArg(0), LCtx);
601 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000602 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
603 svalBuilder.getContext().getSizeType());
604 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000605
Anna Zaks0bd6b112011-10-26 21:06:34 +0000606 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000607}
608
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000609void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
610 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000611{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000612 if (!SymReaper.hasDeadSymbols())
613 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000614
Ted Kremenek8bef8232012-01-26 21:29:00 +0000615 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000616 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000617 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000618
Ted Kremenek217470e2011-07-28 23:07:51 +0000619 bool generateReport = false;
620
Zhongxing Xu173ff562010-08-15 08:19:57 +0000621 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
622 if (SymReaper.isDead(I->first)) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000623 if (I->second.isAllocated())
624 generateReport = true;
Jordy Rose90760142010-08-18 04:33:47 +0000625
626 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000627 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000628
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000629 }
630 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000631
Anna Zaks0bd6b112011-10-26 21:06:34 +0000632 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000633
634 // FIXME: This does not handle when we have multiple leaks at a single
635 // place.
636 if (N && generateReport) {
637 if (!BT_Leak)
638 BT_Leak.reset(new BuiltinBug("Memory leak",
639 "Allocated memory never released. Potential memory leak."));
640 // FIXME: where it is allocated.
641 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
642 C.EmitReport(R);
643 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000644}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000645
Anna Zaksaf498a22011-10-25 19:56:48 +0000646void MallocChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000647 ProgramStateRef state = Ctx.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000648 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000649
Jordy Rose09cef092010-08-18 04:26:59 +0000650 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000651 RefState RS = I->second;
652 if (RS.isAllocated()) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000653 ExplodedNode *N = Ctx.addTransition(state);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000654 if (N) {
655 if (!BT_Leak)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000656 BT_Leak.reset(new BuiltinBug("Memory leak",
657 "Allocated memory never released. Potential memory leak."));
Zhongxing Xu243fde92009-11-17 07:54:15 +0000658 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Anna Zaksaf498a22011-10-25 19:56:48 +0000659 Ctx.EmitReport(R);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000660 }
661 }
662 }
663}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000664
Anna Zaks91c2a112012-02-08 23:16:56 +0000665bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
666 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000667 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000668 const RefState *RS = state->get<RegionState>(Sym);
669 if (!RS)
670 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000671
Anna Zaks91c2a112012-02-08 23:16:56 +0000672 if (RS->isAllocated()) {
673 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
674 C.addTransition(state);
675 return true;
676 }
677 return false;
678}
679
680void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
681 const Expr *E = S->getRetValue();
682 if (!E)
683 return;
684 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000685 if (!Sym)
686 return;
687
Anna Zaks91c2a112012-02-08 23:16:56 +0000688 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000689}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000690
Ted Kremenek8bef8232012-01-26 21:29:00 +0000691ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000692 SVal Cond,
693 bool Assumption) const {
Anna Zaks91c2a112012-02-08 23:16:56 +0000694 // If a symbolic region is assumed to NULL, set its state to AllocateFailed.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000695 // FIXME: should also check symbols assumed to non-null.
696
697 RegionStateTy RS = state->get<RegionState>();
698
699 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Zhongxing Xu2bfa3012011-04-02 03:20:45 +0000700 // If the symbol is assumed to NULL, this will return an APSInt*.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000701 if (state->getSymVal(I.getKey()))
702 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
703 }
704
705 return state;
706}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000707
Anna Zaks91c2a112012-02-08 23:16:56 +0000708bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
709 const Stmt *S) const {
710 assert(Sym);
711 const RefState *RS = C.getState()->get<RegionState>(Sym);
712 if (RS && RS->isReleased()) {
713 if (ExplodedNode *N = C.addTransition()) {
714 if (!BT_UseFree)
715 BT_UseFree.reset(new BuiltinBug("Use dynamically allocated memory "
716 "after it is freed."));
717
718 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
719 if (S)
720 R->addRange(S->getSourceRange());
721 C.EmitReport(R);
722 return true;
723 }
724 }
725 return false;
726}
727
Zhongxing Xuc8023782010-03-10 04:58:55 +0000728// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000729void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
730 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000731 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000732 if (Sym)
733 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000734}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000735
Anna Zaks390909c2011-10-06 00:43:15 +0000736void MallocChecker::checkBind(SVal location, SVal val,
737 const Stmt *BindS, CheckerContext &C) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000738 // The PreVisitBind implements the same algorithm as already used by the
739 // Objective C ownership checker: if the pointer escaped from this scope by
740 // assignment, let it go. However, assigning to fields of a stack-storage
741 // structure does not transfer ownership.
742
Ted Kremenek8bef8232012-01-26 21:29:00 +0000743 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000744 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
745
746 // Check for null dereferences.
747 if (!isa<Loc>(l))
748 return;
749
750 // Before checking if the state is null, check if 'val' has a RefState.
751 // Only then should we check for null and bifurcate the state.
752 SymbolRef Sym = val.getLocSymbolInBase();
753 if (Sym) {
754 if (const RefState *RS = state->get<RegionState>(Sym)) {
755 // If ptr is NULL, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000756 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000757 llvm::tie(notNullState, nullState) = state->assume(l);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000758
759 // Generate a transition for 'nullState' to record the assumption
760 // that the state was null.
761 if (nullState)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000762 C.addTransition(nullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000763
764 if (!notNullState)
765 return;
766
767 if (RS->isAllocated()) {
768 // Something we presently own is being assigned somewhere.
769 const MemRegion *AR = location.getAsRegion();
770 if (!AR)
771 return;
772 AR = AR->StripCasts()->getBaseRegion();
773 do {
774 // If it is on the stack, we still own it.
775 if (AR->hasStackNonParametersStorage())
776 break;
777
778 // If the state can't represent this binding, we still own it.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000779 if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
780 UnknownVal())))
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000781 break;
782
783 // We no longer own this pointer.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000784 notNullState =
785 notNullState->set<RegionState>(Sym,
Anna Zaks390909c2011-10-06 00:43:15 +0000786 RefState::getRelinquished(BindS));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000787 }
788 while (false);
789 }
Anna Zaks0bd6b112011-10-26 21:06:34 +0000790 C.addTransition(notNullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000791 }
792 }
793}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000794
Anna Zaks231361a2012-02-08 23:16:52 +0000795#define REGISTER_CHECKER(name) \
796void ento::register##name(CheckerManager &mgr) {\
797 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000798}
Anna Zaks231361a2012-02-08 23:16:52 +0000799
800REGISTER_CHECKER(MallocPessimistic)
801REGISTER_CHECKER(MallocOptimistic)