blob: 4a15afd986e0da4de179d310a25f6d27476ce6c4 [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;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000141
142 /// The bug visitor which allows us to print extra diagnostics along the
143 /// BugReport path. For example, showing the allocation site of the leaked
144 /// region.
145 class MallocBugVisitor : public BugReporterVisitor {
146 protected:
147 // The allocated region symbol tracked by the main analysis.
148 SymbolRef Sym;
149
150 public:
151 MallocBugVisitor(SymbolRef S) : Sym(S) {}
152 virtual ~MallocBugVisitor() {}
153
154 void Profile(llvm::FoldingSetNodeID &ID) const {
155 static int X = 0;
156 ID.AddPointer(&X);
157 ID.AddPointer(Sym);
158 }
159
160 inline bool isAllocated(const RefState *S, const RefState *SPrev) {
161 // Did not track -> allocated. Other state (released) -> allocated.
162 return ((S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
163 }
164
165 inline bool isReleased(const RefState *S, const RefState *SPrev) {
166 // Did not track -> released. Other state (allocated) -> released.
167 return ((S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
168 }
169
170 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
171 const ExplodedNode *PrevN,
172 BugReporterContext &BRC,
173 BugReport &BR);
174 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000175};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000176} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000177
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000178typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
179
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000180namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000181namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000182 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000183 struct ProgramStateTrait<RegionState>
184 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000185 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000186 };
187}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000188}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000189
Anna Zaksb319e022012-02-08 20:13:28 +0000190void MallocChecker::initIdentifierInfo(CheckerContext &C) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000191 ASTContext &Ctx = C.getASTContext();
192 if (!II_malloc)
193 II_malloc = &Ctx.Idents.get("malloc");
194 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000195 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000196 if (!II_realloc)
197 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000198 if (!II_calloc)
199 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000200}
201
202void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
203 const FunctionDecl *FD = C.getCalleeDecl(CE);
204 if (!FD)
205 return;
206 initIdentifierInfo(C);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000207
208 if (FD->getIdentifier() == II_malloc) {
209 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000210 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000211 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000212 if (FD->getIdentifier() == II_realloc) {
213 ReallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000214 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000215 }
216
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000217 if (FD->getIdentifier() == II_calloc) {
218 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000219 return;
220 }
221
222 if (FD->getIdentifier() == II_free) {
223 FreeMem(C, CE);
224 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000225 }
226
Anna Zaks91c2a112012-02-08 23:16:56 +0000227 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000228 // Check all the attributes, if there are any.
229 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000230 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000231 for (specific_attr_iterator<OwnershipAttr>
232 i = FD->specific_attr_begin<OwnershipAttr>(),
233 e = FD->specific_attr_end<OwnershipAttr>();
234 i != e; ++i) {
235 switch ((*i)->getOwnKind()) {
236 case OwnershipAttr::Returns: {
237 MallocMemReturnsAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000238 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000239 }
240 case OwnershipAttr::Takes:
241 case OwnershipAttr::Holds: {
242 FreeMemAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000243 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000244 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000245 }
246 }
247 }
Anna Zaks91c2a112012-02-08 23:16:56 +0000248
249 if (Filter.CMallocPessimistic) {
250 ProgramStateRef State = C.getState();
251 // The pointer might escape through a function call.
252 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
253 E = CE->arg_end(); I != E; ++I) {
254 const Expr *A = *I;
255 if (A->getType().getTypePtr()->isAnyPointerType()) {
256 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
257 if (!Sym)
258 return;
259 checkEscape(Sym, A, C);
260 checkUseAfterFree(Sym, C, A);
261 }
262 }
263 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000264}
265
266void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000267 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000268 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000269 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000270}
271
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000272void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
273 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000274 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000275 return;
276
Sean Huntcf807c42010-08-18 23:23:40 +0000277 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000278 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000279 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000280 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000281 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000282 return;
283 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000284 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000285 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000286 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000287}
288
Anna Zaksb319e022012-02-08 20:13:28 +0000289ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000290 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000291 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000292 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000293 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000294
Anna Zaksb319e022012-02-08 20:13:28 +0000295 // Get the return value.
296 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000297
Jordy Rose32f26562010-07-04 00:00:41 +0000298 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000299 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000300
Jordy Rose32f26562010-07-04 00:00:41 +0000301 // Set the region's extent equal to the Size parameter.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000302 const SymbolicRegion *R = cast<SymbolicRegion>(retVal.getAsRegion());
303 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000304 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000305 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000306 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000307
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000308 state = state->assume(extentMatchesSize, true);
309 assert(state);
310
311 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000312 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000313
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000314 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000315 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000316}
317
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000318void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000319 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000320
321 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000322 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000323}
324
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000325void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000326 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000327 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000328 return;
329
Sean Huntcf807c42010-08-18 23:23:40 +0000330 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
331 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000332 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000333 FreeMemAux(C, CE, C.getState(), *I,
334 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000335 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000336 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000337 }
338}
339
Ted Kremenek8bef8232012-01-26 21:29:00 +0000340ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000341 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000342 ProgramStateRef state,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000343 unsigned Num,
344 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000345 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000346 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000347
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000348 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
349
350 // Check for null dereferences.
351 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000352 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000353
354 // FIXME: Technically using 'Assume' here can result in a path
355 // bifurcation. In such cases we need to return two states, not just one.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000356 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000357 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000358
359 // The explicit NULL case, no operation is performed.
360 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000361 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000362
363 assert(notNullState);
364
Jordy Rose43859f62010-06-07 19:32:37 +0000365 // Unknown values could easily be okay
366 // Undefined values are handled elsewhere
367 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000368 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000369
Jordy Rose43859f62010-06-07 19:32:37 +0000370 const MemRegion *R = ArgVal.getAsRegion();
371
372 // Nonlocs can't be freed, of course.
373 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
374 if (!R) {
375 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000376 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000377 }
378
379 R = R->StripCasts();
380
381 // Blocks might show up as heap data, but should not be free()d
382 if (isa<BlockDataRegion>(R)) {
383 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000384 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000385 }
386
387 const MemSpaceRegion *MS = R->getMemorySpace();
388
389 // Parameters, locals, statics, and globals shouldn't be freed.
390 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
391 // FIXME: at the time this code was written, malloc() regions were
392 // represented by conjured symbols, which are all in UnknownSpaceRegion.
393 // This means that there isn't actually anything from HeapSpaceRegion
394 // that should be freed, even though we allow it here.
395 // Of course, free() can work on memory allocated outside the current
396 // function, so UnknownSpaceRegion is always a possibility.
397 // False negatives are better than false positives.
398
399 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000400 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000401 }
402
403 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
404 // Various cases could lead to non-symbol values here.
405 // For now, ignore them.
406 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000407 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000408
409 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000410 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000411
412 // If the symbol has not been tracked, return. This is possible when free() is
413 // called on a pointer that does not get its pointee directly from malloc().
414 // Full support of this requires inter-procedural analysis.
415 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000416 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000417
418 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000419 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000420 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000421 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000422 BT_DoubleFree.reset(
423 new BuiltinBug("Double free",
424 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000425 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000426 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000427 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000428 C.EmitReport(R);
429 }
Anna Zaksb319e022012-02-08 20:13:28 +0000430 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000431 }
432
433 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000434 if (Hold)
435 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
436 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000437}
438
Ted Kremenek9c378f72011-08-12 23:37:29 +0000439bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000440 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
441 os << "an integer (" << IntVal->getValue() << ")";
442 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
443 os << "a constant address (" << ConstAddr->getValue() << ")";
444 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000445 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000446 else
447 return false;
448
449 return true;
450}
451
Ted Kremenek9c378f72011-08-12 23:37:29 +0000452bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000453 const MemRegion *MR) {
454 switch (MR->getKind()) {
455 case MemRegion::FunctionTextRegionKind: {
456 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
457 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000458 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000459 else
460 os << "the address of a function";
461 return true;
462 }
463 case MemRegion::BlockTextRegionKind:
464 os << "block text";
465 return true;
466 case MemRegion::BlockDataRegionKind:
467 // FIXME: where the block came from?
468 os << "a block";
469 return true;
470 default: {
471 const MemSpaceRegion *MS = MR->getMemorySpace();
472
Anna Zakseb31a762012-01-04 23:54:01 +0000473 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000474 const VarRegion *VR = dyn_cast<VarRegion>(MR);
475 const VarDecl *VD;
476 if (VR)
477 VD = VR->getDecl();
478 else
479 VD = NULL;
480
481 if (VD)
482 os << "the address of the local variable '" << VD->getName() << "'";
483 else
484 os << "the address of a local stack variable";
485 return true;
486 }
Anna Zakseb31a762012-01-04 23:54:01 +0000487
488 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000489 const VarRegion *VR = dyn_cast<VarRegion>(MR);
490 const VarDecl *VD;
491 if (VR)
492 VD = VR->getDecl();
493 else
494 VD = NULL;
495
496 if (VD)
497 os << "the address of the parameter '" << VD->getName() << "'";
498 else
499 os << "the address of a parameter";
500 return true;
501 }
Anna Zakseb31a762012-01-04 23:54:01 +0000502
503 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000504 const VarRegion *VR = dyn_cast<VarRegion>(MR);
505 const VarDecl *VD;
506 if (VR)
507 VD = VR->getDecl();
508 else
509 VD = NULL;
510
511 if (VD) {
512 if (VD->isStaticLocal())
513 os << "the address of the static variable '" << VD->getName() << "'";
514 else
515 os << "the address of the global variable '" << VD->getName() << "'";
516 } else
517 os << "the address of a global variable";
518 return true;
519 }
Anna Zakseb31a762012-01-04 23:54:01 +0000520
521 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000522 }
523 }
524}
525
526void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000527 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000528 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000529 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000530 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000531
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000532 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000533 llvm::raw_svector_ostream os(buf);
534
535 const MemRegion *MR = ArgVal.getAsRegion();
536 if (MR) {
537 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
538 MR = ER->getSuperRegion();
539
540 // Special case for alloca()
541 if (isa<AllocaRegion>(MR))
542 os << "Argument to free() was allocated by alloca(), not malloc()";
543 else {
544 os << "Argument to free() is ";
545 if (SummarizeRegion(os, MR))
546 os << ", which is not memory allocated by malloc()";
547 else
548 os << "not memory allocated by malloc()";
549 }
550 } else {
551 os << "Argument to free() is ";
552 if (SummarizeValue(os, ArgVal))
553 os << ", which is not memory allocated by malloc()";
554 else
555 os << "not memory allocated by malloc()";
556 }
557
Anna Zakse172e8b2011-08-17 23:00:25 +0000558 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000559 R->addRange(range);
560 C.EmitReport(R);
561 }
562}
563
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000564void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000565 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000566 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000567 const LocationContext *LCtx = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000568 DefinedOrUnknownSVal arg0Val
Ted Kremenek5eca4822012-01-06 22:09:28 +0000569 = cast<DefinedOrUnknownSVal>(state->getSVal(arg0Expr, LCtx));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000570
Ted Kremenek846eabd2010-12-01 21:28:31 +0000571 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000572
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000573 DefinedOrUnknownSVal PtrEQ =
574 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000575
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000576 // Get the size argument. If there is no size arg then give up.
577 const Expr *Arg1 = CE->getArg(1);
578 if (!Arg1)
579 return;
580
581 // Get the value of the size argument.
582 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek5eca4822012-01-06 22:09:28 +0000583 cast<DefinedOrUnknownSVal>(state->getSVal(Arg1, LCtx));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000584
585 // Compare the size argument to 0.
586 DefinedOrUnknownSVal SizeZero =
587 svalBuilder.evalEQ(state, Arg1Val,
588 svalBuilder.makeIntValWithPtrWidth(0, false));
589
590 // If the ptr is NULL and the size is not 0, the call is equivalent to
591 // malloc(size).
Ted Kremenek8bef8232012-01-26 21:29:00 +0000592 ProgramStateRef stateEqual = state->assume(PtrEQ, true);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000593 if (stateEqual && state->assume(SizeZero, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000594 // Hack: set the NULL symbolic region to released to suppress false warning.
595 // In the future we should add more states for allocated regions, e.g.,
596 // CheckedNull, CheckedNonNull.
597
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000598 SymbolRef Sym = arg0Val.getAsLocSymbol();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000599 if (Sym)
600 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
601
Ted Kremenek8bef8232012-01-26 21:29:00 +0000602 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000603 UndefinedVal(), stateEqual);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000604 C.addTransition(stateMalloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000605 }
606
Ted Kremenek8bef8232012-01-26 21:29:00 +0000607 if (ProgramStateRef stateNotEqual = state->assume(PtrEQ, false)) {
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000608 // If the size is 0, free the memory.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000609 if (ProgramStateRef stateSizeZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000610 stateNotEqual->assume(SizeZero, true))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000611 if (ProgramStateRef stateFree =
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000612 FreeMemAux(C, CE, stateSizeZero, 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000613
Zhongxing Xud56763f2011-09-01 04:53:59 +0000614 // Bind the return value to NULL because it is now free.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000615 C.addTransition(stateFree->BindExpr(CE, LCtx,
616 svalBuilder.makeNull(), true));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000617 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000618 if (ProgramStateRef stateSizeNotZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000619 stateNotEqual->assume(SizeZero,false))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000620 if (ProgramStateRef stateFree = FreeMemAux(C, CE, stateSizeNotZero,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000621 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000622 // FIXME: We should copy the content of the original buffer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000623 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000624 UnknownVal(), stateFree);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000625 C.addTransition(stateRealloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000626 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000627 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000628}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000629
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000630void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000631 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000632 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000633 const LocationContext *LCtx = C.getLocationContext();
634 SVal count = state->getSVal(CE->getArg(0), LCtx);
635 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000636 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
637 svalBuilder.getContext().getSizeType());
638 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000639
Anna Zaks0bd6b112011-10-26 21:06:34 +0000640 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000641}
642
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000643void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
644 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000645{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000646 if (!SymReaper.hasDeadSymbols())
647 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000648
Ted Kremenek8bef8232012-01-26 21:29:00 +0000649 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000650 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000651 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000652
Ted Kremenek217470e2011-07-28 23:07:51 +0000653 bool generateReport = false;
654
Zhongxing Xu173ff562010-08-15 08:19:57 +0000655 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
656 if (SymReaper.isDead(I->first)) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000657 if (I->second.isAllocated())
658 generateReport = true;
Jordy Rose90760142010-08-18 04:33:47 +0000659
660 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000661 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000662
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000663 }
664 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000665
Anna Zaks0bd6b112011-10-26 21:06:34 +0000666 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000667
668 // FIXME: This does not handle when we have multiple leaks at a single
669 // place.
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000670 // TODO: We don't have symbol info in the diagnostics here!
Ted Kremenek217470e2011-07-28 23:07:51 +0000671 if (N && generateReport) {
672 if (!BT_Leak)
673 BT_Leak.reset(new BuiltinBug("Memory leak",
674 "Allocated memory never released. Potential memory leak."));
675 // FIXME: where it is allocated.
676 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000677 //Report->addVisitor(new MallocBugVisitor(Sym));
Ted Kremenek217470e2011-07-28 23:07:51 +0000678 C.EmitReport(R);
679 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000680}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000681
Anna Zaksaf498a22011-10-25 19:56:48 +0000682void MallocChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000683 ProgramStateRef state = Ctx.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000684 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000685
Jordy Rose09cef092010-08-18 04:26:59 +0000686 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000687 RefState RS = I->second;
688 if (RS.isAllocated()) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000689 ExplodedNode *N = Ctx.addTransition(state);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000690 if (N) {
691 if (!BT_Leak)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000692 BT_Leak.reset(new BuiltinBug("Memory leak",
693 "Allocated memory never released. Potential memory leak."));
Zhongxing Xu243fde92009-11-17 07:54:15 +0000694 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000695 R->addVisitor(new MallocBugVisitor(I->first));
Anna Zaksaf498a22011-10-25 19:56:48 +0000696 Ctx.EmitReport(R);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000697 }
698 }
699 }
700}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000701
Anna Zaks91c2a112012-02-08 23:16:56 +0000702bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
703 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000704 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000705 const RefState *RS = state->get<RegionState>(Sym);
706 if (!RS)
707 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000708
Anna Zaks91c2a112012-02-08 23:16:56 +0000709 if (RS->isAllocated()) {
710 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
711 C.addTransition(state);
712 return true;
713 }
714 return false;
715}
716
717void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
718 const Expr *E = S->getRetValue();
719 if (!E)
720 return;
721 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000722 if (!Sym)
723 return;
724
Anna Zaks91c2a112012-02-08 23:16:56 +0000725 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000726}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000727
Ted Kremenek8bef8232012-01-26 21:29:00 +0000728ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000729 SVal Cond,
730 bool Assumption) const {
Anna Zaks91c2a112012-02-08 23:16:56 +0000731 // If a symbolic region is assumed to NULL, set its state to AllocateFailed.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000732 // FIXME: should also check symbols assumed to non-null.
733
734 RegionStateTy RS = state->get<RegionState>();
735
736 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Zhongxing Xu2bfa3012011-04-02 03:20:45 +0000737 // If the symbol is assumed to NULL, this will return an APSInt*.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000738 if (state->getSymVal(I.getKey()))
739 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
740 }
741
742 return state;
743}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000744
Anna Zaks91c2a112012-02-08 23:16:56 +0000745bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
746 const Stmt *S) const {
747 assert(Sym);
748 const RefState *RS = C.getState()->get<RegionState>(Sym);
749 if (RS && RS->isReleased()) {
750 if (ExplodedNode *N = C.addTransition()) {
751 if (!BT_UseFree)
752 BT_UseFree.reset(new BuiltinBug("Use dynamically allocated memory "
753 "after it is freed."));
754
755 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
756 if (S)
757 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000758 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000759 C.EmitReport(R);
760 return true;
761 }
762 }
763 return false;
764}
765
Zhongxing Xuc8023782010-03-10 04:58:55 +0000766// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000767void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
768 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000769 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000770 if (Sym)
771 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000772}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000773
Anna Zaks390909c2011-10-06 00:43:15 +0000774void MallocChecker::checkBind(SVal location, SVal val,
775 const Stmt *BindS, CheckerContext &C) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000776 // The PreVisitBind implements the same algorithm as already used by the
777 // Objective C ownership checker: if the pointer escaped from this scope by
778 // assignment, let it go. However, assigning to fields of a stack-storage
779 // structure does not transfer ownership.
780
Ted Kremenek8bef8232012-01-26 21:29:00 +0000781 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000782 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
783
784 // Check for null dereferences.
785 if (!isa<Loc>(l))
786 return;
787
788 // Before checking if the state is null, check if 'val' has a RefState.
789 // Only then should we check for null and bifurcate the state.
790 SymbolRef Sym = val.getLocSymbolInBase();
791 if (Sym) {
792 if (const RefState *RS = state->get<RegionState>(Sym)) {
793 // If ptr is NULL, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000794 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000795 llvm::tie(notNullState, nullState) = state->assume(l);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000796
797 // Generate a transition for 'nullState' to record the assumption
798 // that the state was null.
799 if (nullState)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000800 C.addTransition(nullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000801
802 if (!notNullState)
803 return;
804
805 if (RS->isAllocated()) {
806 // Something we presently own is being assigned somewhere.
807 const MemRegion *AR = location.getAsRegion();
808 if (!AR)
809 return;
810 AR = AR->StripCasts()->getBaseRegion();
811 do {
812 // If it is on the stack, we still own it.
813 if (AR->hasStackNonParametersStorage())
814 break;
815
816 // If the state can't represent this binding, we still own it.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000817 if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
818 UnknownVal())))
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000819 break;
820
821 // We no longer own this pointer.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000822 notNullState =
823 notNullState->set<RegionState>(Sym,
Anna Zaks390909c2011-10-06 00:43:15 +0000824 RefState::getRelinquished(BindS));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000825 }
826 while (false);
827 }
Anna Zaks0bd6b112011-10-26 21:06:34 +0000828 C.addTransition(notNullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000829 }
830 }
831}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000832
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000833PathDiagnosticPiece *
834MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
835 const ExplodedNode *PrevN,
836 BugReporterContext &BRC,
837 BugReport &BR) {
838 const RefState *RS = N->getState()->get<RegionState>(Sym);
839 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
840 if (!RS && !RSPrev)
841 return 0;
842
843 // We expect the interesting locations be StmtPoints corresponding to call
844 // expressions. We do not support indirect function calls as of now.
845 const CallExpr *CE = 0;
846 if (isa<StmtPoint>(N->getLocation()))
847 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
848 if (!CE)
849 return 0;
850 const FunctionDecl *funDecl = CE->getDirectCallee();
851 if (!funDecl)
852 return 0;
853 StringRef funName = funDecl->getName();
854
855 // Find out if this is an interesting point and what is the kind.
856 const char *Msg = 0;
857 if (isAllocated(RS, RSPrev))
858 Msg = "Memory is allocated here";
859 else if (isReleased(RS, RSPrev))
860 Msg = "Memory is released here";
861 if (!Msg)
862 return 0;
863
864 // Generate the extra diagnostic.
865 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
866 N->getLocationContext());
867 return new PathDiagnosticEventPiece(Pos, Msg);
868}
869
870
Anna Zaks231361a2012-02-08 23:16:52 +0000871#define REGISTER_CHECKER(name) \
872void ento::register##name(CheckerManager &mgr) {\
873 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000874}
Anna Zaks231361a2012-02-08 23:16:52 +0000875
876REGISTER_CHECKER(MallocPessimistic)
877REGISTER_CHECKER(MallocOptimistic)