blob: 8b6964bff7cd14b729db09e40c19a28e53071d4f [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)
Anna Zakse9ef5622012-02-10 01:11:00 +0000258 continue;
Anna Zaks91c2a112012-02-08 23:16:56 +0000259 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.
Anna Zakse9ef5622012-02-10 01:11:00 +0000302 const SymbolicRegion *R =
303 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
304 if (!R || !isa<DefinedOrUnknownSVal>(Size))
305 return 0;
306
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000307 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000308 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000309 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000310 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000311
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000312 state = state->assume(extentMatchesSize, true);
313 assert(state);
314
315 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000316 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000317
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000318 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000319 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000320}
321
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000322void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000323 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000324
325 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000326 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000327}
328
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000329void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000330 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000331 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000332 return;
333
Sean Huntcf807c42010-08-18 23:23:40 +0000334 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
335 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000336 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000337 FreeMemAux(C, CE, C.getState(), *I,
338 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000339 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000340 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000341 }
342}
343
Ted Kremenek8bef8232012-01-26 21:29:00 +0000344ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000345 const CallExpr *CE,
346 ProgramStateRef state,
347 unsigned Num,
348 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000349 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000350 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000351 if (!isa<DefinedOrUnknownSVal>(ArgVal))
352 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000353 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
354
355 // Check for null dereferences.
356 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000357 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000358
359 // FIXME: Technically using 'Assume' here can result in a path
360 // bifurcation. In such cases we need to return two states, not just one.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000361 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000362 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000363
364 // The explicit NULL case, no operation is performed.
365 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000366 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000367
368 assert(notNullState);
369
Jordy Rose43859f62010-06-07 19:32:37 +0000370 // Unknown values could easily be okay
371 // Undefined values are handled elsewhere
372 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000373 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000374
Jordy Rose43859f62010-06-07 19:32:37 +0000375 const MemRegion *R = ArgVal.getAsRegion();
376
377 // Nonlocs can't be freed, of course.
378 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
379 if (!R) {
380 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000381 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000382 }
383
384 R = R->StripCasts();
385
386 // Blocks might show up as heap data, but should not be free()d
387 if (isa<BlockDataRegion>(R)) {
388 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000389 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000390 }
391
392 const MemSpaceRegion *MS = R->getMemorySpace();
393
394 // Parameters, locals, statics, and globals shouldn't be freed.
395 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
396 // FIXME: at the time this code was written, malloc() regions were
397 // represented by conjured symbols, which are all in UnknownSpaceRegion.
398 // This means that there isn't actually anything from HeapSpaceRegion
399 // that should be freed, even though we allow it here.
400 // Of course, free() can work on memory allocated outside the current
401 // function, so UnknownSpaceRegion is always a possibility.
402 // False negatives are better than false positives.
403
404 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000405 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000406 }
407
408 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
409 // Various cases could lead to non-symbol values here.
410 // For now, ignore them.
411 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000412 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000413
414 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000415 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000416
417 // If the symbol has not been tracked, return. This is possible when free() is
418 // called on a pointer that does not get its pointee directly from malloc().
419 // Full support of this requires inter-procedural analysis.
420 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000421 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000422
423 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000424 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000425 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000426 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000427 BT_DoubleFree.reset(
428 new BuiltinBug("Double free",
429 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000430 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000431 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000432 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000433 C.EmitReport(R);
434 }
Anna Zaksb319e022012-02-08 20:13:28 +0000435 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000436 }
437
438 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000439 if (Hold)
440 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
441 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000442}
443
Ted Kremenek9c378f72011-08-12 23:37:29 +0000444bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000445 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
446 os << "an integer (" << IntVal->getValue() << ")";
447 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
448 os << "a constant address (" << ConstAddr->getValue() << ")";
449 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000450 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000451 else
452 return false;
453
454 return true;
455}
456
Ted Kremenek9c378f72011-08-12 23:37:29 +0000457bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000458 const MemRegion *MR) {
459 switch (MR->getKind()) {
460 case MemRegion::FunctionTextRegionKind: {
461 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
462 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000463 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000464 else
465 os << "the address of a function";
466 return true;
467 }
468 case MemRegion::BlockTextRegionKind:
469 os << "block text";
470 return true;
471 case MemRegion::BlockDataRegionKind:
472 // FIXME: where the block came from?
473 os << "a block";
474 return true;
475 default: {
476 const MemSpaceRegion *MS = MR->getMemorySpace();
477
Anna Zakseb31a762012-01-04 23:54:01 +0000478 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000479 const VarRegion *VR = dyn_cast<VarRegion>(MR);
480 const VarDecl *VD;
481 if (VR)
482 VD = VR->getDecl();
483 else
484 VD = NULL;
485
486 if (VD)
487 os << "the address of the local variable '" << VD->getName() << "'";
488 else
489 os << "the address of a local stack variable";
490 return true;
491 }
Anna Zakseb31a762012-01-04 23:54:01 +0000492
493 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000494 const VarRegion *VR = dyn_cast<VarRegion>(MR);
495 const VarDecl *VD;
496 if (VR)
497 VD = VR->getDecl();
498 else
499 VD = NULL;
500
501 if (VD)
502 os << "the address of the parameter '" << VD->getName() << "'";
503 else
504 os << "the address of a parameter";
505 return true;
506 }
Anna Zakseb31a762012-01-04 23:54:01 +0000507
508 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000509 const VarRegion *VR = dyn_cast<VarRegion>(MR);
510 const VarDecl *VD;
511 if (VR)
512 VD = VR->getDecl();
513 else
514 VD = NULL;
515
516 if (VD) {
517 if (VD->isStaticLocal())
518 os << "the address of the static variable '" << VD->getName() << "'";
519 else
520 os << "the address of the global variable '" << VD->getName() << "'";
521 } else
522 os << "the address of a global variable";
523 return true;
524 }
Anna Zakseb31a762012-01-04 23:54:01 +0000525
526 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000527 }
528 }
529}
530
531void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000532 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000533 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000534 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000535 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000536
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000537 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000538 llvm::raw_svector_ostream os(buf);
539
540 const MemRegion *MR = ArgVal.getAsRegion();
541 if (MR) {
542 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
543 MR = ER->getSuperRegion();
544
545 // Special case for alloca()
546 if (isa<AllocaRegion>(MR))
547 os << "Argument to free() was allocated by alloca(), not malloc()";
548 else {
549 os << "Argument to free() is ";
550 if (SummarizeRegion(os, MR))
551 os << ", which is not memory allocated by malloc()";
552 else
553 os << "not memory allocated by malloc()";
554 }
555 } else {
556 os << "Argument to free() is ";
557 if (SummarizeValue(os, ArgVal))
558 os << ", which is not memory allocated by malloc()";
559 else
560 os << "not memory allocated by malloc()";
561 }
562
Anna Zakse172e8b2011-08-17 23:00:25 +0000563 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000564 R->addRange(range);
565 C.EmitReport(R);
566 }
567}
568
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000569void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000570 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000571 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000572 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000573 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
574 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
575 return;
576 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000577
Ted Kremenek846eabd2010-12-01 21:28:31 +0000578 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000579
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000580 DefinedOrUnknownSVal PtrEQ =
581 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000582
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000583 // Get the size argument. If there is no size arg then give up.
584 const Expr *Arg1 = CE->getArg(1);
585 if (!Arg1)
586 return;
587
588 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000589 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
590 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
591 return;
592 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000593
594 // Compare the size argument to 0.
595 DefinedOrUnknownSVal SizeZero =
596 svalBuilder.evalEQ(state, Arg1Val,
597 svalBuilder.makeIntValWithPtrWidth(0, false));
598
599 // If the ptr is NULL and the size is not 0, the call is equivalent to
600 // malloc(size).
Ted Kremenek8bef8232012-01-26 21:29:00 +0000601 ProgramStateRef stateEqual = state->assume(PtrEQ, true);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000602 if (stateEqual && state->assume(SizeZero, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000603 // Hack: set the NULL symbolic region to released to suppress false warning.
604 // In the future we should add more states for allocated regions, e.g.,
605 // CheckedNull, CheckedNonNull.
606
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000607 SymbolRef Sym = arg0Val.getAsLocSymbol();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000608 if (Sym)
609 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
610
Ted Kremenek8bef8232012-01-26 21:29:00 +0000611 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000612 UndefinedVal(), stateEqual);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000613 C.addTransition(stateMalloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000614 }
615
Ted Kremenek8bef8232012-01-26 21:29:00 +0000616 if (ProgramStateRef stateNotEqual = state->assume(PtrEQ, false)) {
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000617 // If the size is 0, free the memory.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000618 if (ProgramStateRef stateSizeZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000619 stateNotEqual->assume(SizeZero, true))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000620 if (ProgramStateRef stateFree =
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000621 FreeMemAux(C, CE, stateSizeZero, 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000622
Zhongxing Xud56763f2011-09-01 04:53:59 +0000623 // Bind the return value to NULL because it is now free.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000624 C.addTransition(stateFree->BindExpr(CE, LCtx,
625 svalBuilder.makeNull(), true));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000626 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000627 if (ProgramStateRef stateSizeNotZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000628 stateNotEqual->assume(SizeZero,false))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000629 if (ProgramStateRef stateFree = FreeMemAux(C, CE, stateSizeNotZero,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000630 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000631 // FIXME: We should copy the content of the original buffer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000632 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000633 UnknownVal(), stateFree);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000634 C.addTransition(stateRealloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000635 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000636 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000637}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000638
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000639void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000640 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000641 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000642 const LocationContext *LCtx = C.getLocationContext();
643 SVal count = state->getSVal(CE->getArg(0), LCtx);
644 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000645 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
646 svalBuilder.getContext().getSizeType());
647 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000648
Anna Zaks0bd6b112011-10-26 21:06:34 +0000649 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000650}
651
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000652void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
653 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000654{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000655 if (!SymReaper.hasDeadSymbols())
656 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000657
Ted Kremenek8bef8232012-01-26 21:29:00 +0000658 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000659 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000660 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000661
Ted Kremenek217470e2011-07-28 23:07:51 +0000662 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000663 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000664 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
665 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000666 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000667 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000668 Errors.push_back(I->first);
669 }
Jordy Rose90760142010-08-18 04:33:47 +0000670 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000671 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000672
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000673 }
674 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000675
Anna Zaks0bd6b112011-10-26 21:06:34 +0000676 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000677
Ted Kremenek217470e2011-07-28 23:07:51 +0000678 if (N && generateReport) {
679 if (!BT_Leak)
680 BT_Leak.reset(new BuiltinBug("Memory leak",
Anna Zaksf8c17b72012-02-09 06:48:19 +0000681 "Allocated memory never released. Potential memory leak."));
682 for (llvm::SmallVector<SymbolRef, 2>::iterator
683 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
684 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
685 R->addVisitor(new MallocBugVisitor(*I));
686 C.EmitReport(R);
687 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000688 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000689}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000690
Anna Zaksaf498a22011-10-25 19:56:48 +0000691void MallocChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000692 ProgramStateRef state = Ctx.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000693 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000694
Jordy Rose09cef092010-08-18 04:26:59 +0000695 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000696 RefState RS = I->second;
697 if (RS.isAllocated()) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000698 ExplodedNode *N = Ctx.addTransition(state);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000699 if (N) {
700 if (!BT_Leak)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000701 BT_Leak.reset(new BuiltinBug("Memory leak",
702 "Allocated memory never released. Potential memory leak."));
Zhongxing Xu243fde92009-11-17 07:54:15 +0000703 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000704 R->addVisitor(new MallocBugVisitor(I->first));
Anna Zaksaf498a22011-10-25 19:56:48 +0000705 Ctx.EmitReport(R);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000706 }
707 }
708 }
709}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000710
Anna Zaks91c2a112012-02-08 23:16:56 +0000711bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
712 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000713 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000714 const RefState *RS = state->get<RegionState>(Sym);
715 if (!RS)
716 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000717
Anna Zaks91c2a112012-02-08 23:16:56 +0000718 if (RS->isAllocated()) {
719 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
720 C.addTransition(state);
721 return true;
722 }
723 return false;
724}
725
726void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
727 const Expr *E = S->getRetValue();
728 if (!E)
729 return;
730 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000731 if (!Sym)
732 return;
733
Anna Zaks91c2a112012-02-08 23:16:56 +0000734 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000735}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000736
Ted Kremenek8bef8232012-01-26 21:29:00 +0000737ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000738 SVal Cond,
739 bool Assumption) const {
Anna Zaks91c2a112012-02-08 23:16:56 +0000740 // If a symbolic region is assumed to NULL, set its state to AllocateFailed.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000741 // FIXME: should also check symbols assumed to non-null.
742
743 RegionStateTy RS = state->get<RegionState>();
744
745 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Zhongxing Xu2bfa3012011-04-02 03:20:45 +0000746 // If the symbol is assumed to NULL, this will return an APSInt*.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000747 if (state->getSymVal(I.getKey()))
748 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
749 }
750
751 return state;
752}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000753
Anna Zaks91c2a112012-02-08 23:16:56 +0000754bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
755 const Stmt *S) const {
756 assert(Sym);
757 const RefState *RS = C.getState()->get<RegionState>(Sym);
758 if (RS && RS->isReleased()) {
759 if (ExplodedNode *N = C.addTransition()) {
760 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000761 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000762 "after it is freed."));
763
764 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
765 if (S)
766 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000767 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000768 C.EmitReport(R);
769 return true;
770 }
771 }
772 return false;
773}
774
Zhongxing Xuc8023782010-03-10 04:58:55 +0000775// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000776void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
777 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000778 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000779 if (Sym)
780 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000781}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000782
Anna Zaks390909c2011-10-06 00:43:15 +0000783void MallocChecker::checkBind(SVal location, SVal val,
784 const Stmt *BindS, CheckerContext &C) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000785 // The PreVisitBind implements the same algorithm as already used by the
786 // Objective C ownership checker: if the pointer escaped from this scope by
787 // assignment, let it go. However, assigning to fields of a stack-storage
788 // structure does not transfer ownership.
789
Ted Kremenek8bef8232012-01-26 21:29:00 +0000790 ProgramStateRef state = C.getState();
Anna Zakse9ef5622012-02-10 01:11:00 +0000791 if (!isa<DefinedOrUnknownSVal>(location))
792 return;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000793 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
794
795 // Check for null dereferences.
796 if (!isa<Loc>(l))
797 return;
798
799 // Before checking if the state is null, check if 'val' has a RefState.
800 // Only then should we check for null and bifurcate the state.
801 SymbolRef Sym = val.getLocSymbolInBase();
802 if (Sym) {
803 if (const RefState *RS = state->get<RegionState>(Sym)) {
804 // If ptr is NULL, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000805 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000806 llvm::tie(notNullState, nullState) = state->assume(l);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000807
808 // Generate a transition for 'nullState' to record the assumption
809 // that the state was null.
810 if (nullState)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000811 C.addTransition(nullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000812
813 if (!notNullState)
814 return;
815
816 if (RS->isAllocated()) {
817 // Something we presently own is being assigned somewhere.
818 const MemRegion *AR = location.getAsRegion();
819 if (!AR)
820 return;
821 AR = AR->StripCasts()->getBaseRegion();
822 do {
823 // If it is on the stack, we still own it.
824 if (AR->hasStackNonParametersStorage())
825 break;
826
827 // If the state can't represent this binding, we still own it.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000828 if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
829 UnknownVal())))
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000830 break;
831
832 // We no longer own this pointer.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000833 notNullState =
834 notNullState->set<RegionState>(Sym,
Anna Zaks390909c2011-10-06 00:43:15 +0000835 RefState::getRelinquished(BindS));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000836 }
837 while (false);
838 }
Anna Zaks0bd6b112011-10-26 21:06:34 +0000839 C.addTransition(notNullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000840 }
841 }
842}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000843
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000844PathDiagnosticPiece *
845MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
846 const ExplodedNode *PrevN,
847 BugReporterContext &BRC,
848 BugReport &BR) {
849 const RefState *RS = N->getState()->get<RegionState>(Sym);
850 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
851 if (!RS && !RSPrev)
852 return 0;
853
854 // We expect the interesting locations be StmtPoints corresponding to call
855 // expressions. We do not support indirect function calls as of now.
856 const CallExpr *CE = 0;
857 if (isa<StmtPoint>(N->getLocation()))
858 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
859 if (!CE)
860 return 0;
861 const FunctionDecl *funDecl = CE->getDirectCallee();
862 if (!funDecl)
863 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000864
865 // Find out if this is an interesting point and what is the kind.
866 const char *Msg = 0;
867 if (isAllocated(RS, RSPrev))
868 Msg = "Memory is allocated here";
869 else if (isReleased(RS, RSPrev))
870 Msg = "Memory is released here";
871 if (!Msg)
872 return 0;
873
874 // Generate the extra diagnostic.
875 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
876 N->getLocationContext());
877 return new PathDiagnosticEventPiece(Pos, Msg);
878}
879
880
Anna Zaks231361a2012-02-08 23:16:52 +0000881#define REGISTER_CHECKER(name) \
882void ento::register##name(CheckerManager &mgr) {\
883 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000884}
Anna Zaks231361a2012-02-08 23:16:52 +0000885
886REGISTER_CHECKER(MallocPessimistic)
887REGISTER_CHECKER(MallocOptimistic)