blob: b14b40020220189786452584227c9dbaddba0898 [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
Ted Kremenek9c378f72011-08-12 23:37:29 +0000134 static bool SummarizeValue(raw_ostream &os, SVal V);
135 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000136 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000137};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000138} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000139
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000140typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
141
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000142namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000143namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000144 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000145 struct ProgramStateTrait<RegionState>
146 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000147 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000148 };
149}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000150}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000151
Anna Zaksb319e022012-02-08 20:13:28 +0000152void MallocChecker::initIdentifierInfo(CheckerContext &C) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000153 ASTContext &Ctx = C.getASTContext();
154 if (!II_malloc)
155 II_malloc = &Ctx.Idents.get("malloc");
156 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000157 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000158 if (!II_realloc)
159 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000160 if (!II_calloc)
161 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000162}
163
164void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
165 const FunctionDecl *FD = C.getCalleeDecl(CE);
166 if (!FD)
167 return;
168 initIdentifierInfo(C);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000169
170 if (FD->getIdentifier() == II_malloc) {
171 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000172 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000173 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000174 if (FD->getIdentifier() == II_realloc) {
175 ReallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000176 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000177 }
178
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000179 if (FD->getIdentifier() == II_calloc) {
180 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000181 return;
182 }
183
184 if (FD->getIdentifier() == II_free) {
185 FreeMem(C, CE);
186 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000187 }
188
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000189 // Check all the attributes, if there are any.
190 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000191 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000192 for (specific_attr_iterator<OwnershipAttr>
193 i = FD->specific_attr_begin<OwnershipAttr>(),
194 e = FD->specific_attr_end<OwnershipAttr>();
195 i != e; ++i) {
196 switch ((*i)->getOwnKind()) {
197 case OwnershipAttr::Returns: {
198 MallocMemReturnsAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000199 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000200 }
201 case OwnershipAttr::Takes:
202 case OwnershipAttr::Holds: {
203 FreeMemAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000204 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000205 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000206 }
207 }
208 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000209}
210
211void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000212 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000213 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000214 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000215}
216
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000217void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
218 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000219 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000220 return;
221
Sean Huntcf807c42010-08-18 23:23:40 +0000222 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000223 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000224 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000225 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000226 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000227 return;
228 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000229 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000230 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000231 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000232}
233
Anna Zaksb319e022012-02-08 20:13:28 +0000234ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000235 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000236 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000237 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000238 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000239
Anna Zaksb319e022012-02-08 20:13:28 +0000240 // Get the return value.
241 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000242
Jordy Rose32f26562010-07-04 00:00:41 +0000243 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000244 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000245
Jordy Rose32f26562010-07-04 00:00:41 +0000246 // Set the region's extent equal to the Size parameter.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000247 const SymbolicRegion *R = cast<SymbolicRegion>(retVal.getAsRegion());
248 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000249 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000250 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000251 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000252
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000253 state = state->assume(extentMatchesSize, true);
254 assert(state);
255
256 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000257 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000258
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000259 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000260 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000261}
262
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000263void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000264 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000265
266 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000267 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000268}
269
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000270void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000271 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000272 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000273 return;
274
Sean Huntcf807c42010-08-18 23:23:40 +0000275 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
276 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000277 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000278 FreeMemAux(C, CE, C.getState(), *I,
279 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000280 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000281 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000282 }
283}
284
Ted Kremenek8bef8232012-01-26 21:29:00 +0000285ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000286 const CallExpr *CE,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000287 ProgramStateRef state,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000288 unsigned Num,
289 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000290 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000291 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Zhongxing Xu181cc3d2010-02-14 06:49:48 +0000292
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000293 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
294
295 // Check for null dereferences.
296 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000297 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000298
299 // FIXME: Technically using 'Assume' here can result in a path
300 // bifurcation. In such cases we need to return two states, not just one.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000301 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000302 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000303
304 // The explicit NULL case, no operation is performed.
305 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000306 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000307
308 assert(notNullState);
309
Jordy Rose43859f62010-06-07 19:32:37 +0000310 // Unknown values could easily be okay
311 // Undefined values are handled elsewhere
312 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000313 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000314
Jordy Rose43859f62010-06-07 19:32:37 +0000315 const MemRegion *R = ArgVal.getAsRegion();
316
317 // Nonlocs can't be freed, of course.
318 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
319 if (!R) {
320 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000321 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000322 }
323
324 R = R->StripCasts();
325
326 // Blocks might show up as heap data, but should not be free()d
327 if (isa<BlockDataRegion>(R)) {
328 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000329 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000330 }
331
332 const MemSpaceRegion *MS = R->getMemorySpace();
333
Anna Zaksb319e022012-02-08 20:13:28 +0000334 // TODO: Pessimize this. should be behinds a flag!
Jordy Rose43859f62010-06-07 19:32:37 +0000335 // Parameters, locals, statics, and globals shouldn't be freed.
336 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
337 // FIXME: at the time this code was written, malloc() regions were
338 // represented by conjured symbols, which are all in UnknownSpaceRegion.
339 // This means that there isn't actually anything from HeapSpaceRegion
340 // that should be freed, even though we allow it here.
341 // Of course, free() can work on memory allocated outside the current
342 // function, so UnknownSpaceRegion is always a possibility.
343 // False negatives are better than false positives.
344
345 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000346 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000347 }
348
349 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
350 // Various cases could lead to non-symbol values here.
351 // For now, ignore them.
352 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000353 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000354
355 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000356 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000357
358 // If the symbol has not been tracked, return. This is possible when free() is
359 // called on a pointer that does not get its pointee directly from malloc().
360 // Full support of this requires inter-procedural analysis.
361 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000362 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000363
364 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000365 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000366 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000367 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000368 BT_DoubleFree.reset(
369 new BuiltinBug("Double free",
370 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000371 // FIXME: should find where it's freed last time.
372 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000373 BT_DoubleFree->getDescription(), N);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000374 C.EmitReport(R);
375 }
Anna Zaksb319e022012-02-08 20:13:28 +0000376 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000377 }
378
379 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000380 if (Hold)
381 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
382 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000383}
384
Ted Kremenek9c378f72011-08-12 23:37:29 +0000385bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000386 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
387 os << "an integer (" << IntVal->getValue() << ")";
388 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
389 os << "a constant address (" << ConstAddr->getValue() << ")";
390 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000391 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000392 else
393 return false;
394
395 return true;
396}
397
Ted Kremenek9c378f72011-08-12 23:37:29 +0000398bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000399 const MemRegion *MR) {
400 switch (MR->getKind()) {
401 case MemRegion::FunctionTextRegionKind: {
402 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
403 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000404 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000405 else
406 os << "the address of a function";
407 return true;
408 }
409 case MemRegion::BlockTextRegionKind:
410 os << "block text";
411 return true;
412 case MemRegion::BlockDataRegionKind:
413 // FIXME: where the block came from?
414 os << "a block";
415 return true;
416 default: {
417 const MemSpaceRegion *MS = MR->getMemorySpace();
418
Anna Zakseb31a762012-01-04 23:54:01 +0000419 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000420 const VarRegion *VR = dyn_cast<VarRegion>(MR);
421 const VarDecl *VD;
422 if (VR)
423 VD = VR->getDecl();
424 else
425 VD = NULL;
426
427 if (VD)
428 os << "the address of the local variable '" << VD->getName() << "'";
429 else
430 os << "the address of a local stack variable";
431 return true;
432 }
Anna Zakseb31a762012-01-04 23:54:01 +0000433
434 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000435 const VarRegion *VR = dyn_cast<VarRegion>(MR);
436 const VarDecl *VD;
437 if (VR)
438 VD = VR->getDecl();
439 else
440 VD = NULL;
441
442 if (VD)
443 os << "the address of the parameter '" << VD->getName() << "'";
444 else
445 os << "the address of a parameter";
446 return true;
447 }
Anna Zakseb31a762012-01-04 23:54:01 +0000448
449 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000450 const VarRegion *VR = dyn_cast<VarRegion>(MR);
451 const VarDecl *VD;
452 if (VR)
453 VD = VR->getDecl();
454 else
455 VD = NULL;
456
457 if (VD) {
458 if (VD->isStaticLocal())
459 os << "the address of the static variable '" << VD->getName() << "'";
460 else
461 os << "the address of the global variable '" << VD->getName() << "'";
462 } else
463 os << "the address of a global variable";
464 return true;
465 }
Anna Zakseb31a762012-01-04 23:54:01 +0000466
467 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000468 }
469 }
470}
471
472void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000473 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000474 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000475 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000476 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000477
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000478 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000479 llvm::raw_svector_ostream os(buf);
480
481 const MemRegion *MR = ArgVal.getAsRegion();
482 if (MR) {
483 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
484 MR = ER->getSuperRegion();
485
486 // Special case for alloca()
487 if (isa<AllocaRegion>(MR))
488 os << "Argument to free() was allocated by alloca(), not malloc()";
489 else {
490 os << "Argument to free() is ";
491 if (SummarizeRegion(os, MR))
492 os << ", which is not memory allocated by malloc()";
493 else
494 os << "not memory allocated by malloc()";
495 }
496 } else {
497 os << "Argument to free() is ";
498 if (SummarizeValue(os, ArgVal))
499 os << ", which is not memory allocated by malloc()";
500 else
501 os << "not memory allocated by malloc()";
502 }
503
Anna Zakse172e8b2011-08-17 23:00:25 +0000504 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000505 R->addRange(range);
506 C.EmitReport(R);
507 }
508}
509
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000510void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000511 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000512 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000513 const LocationContext *LCtx = C.getLocationContext();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000514 DefinedOrUnknownSVal arg0Val
Ted Kremenek5eca4822012-01-06 22:09:28 +0000515 = cast<DefinedOrUnknownSVal>(state->getSVal(arg0Expr, LCtx));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000516
Ted Kremenek846eabd2010-12-01 21:28:31 +0000517 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000518
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000519 DefinedOrUnknownSVal PtrEQ =
520 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000521
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000522 // Get the size argument. If there is no size arg then give up.
523 const Expr *Arg1 = CE->getArg(1);
524 if (!Arg1)
525 return;
526
527 // Get the value of the size argument.
528 DefinedOrUnknownSVal Arg1Val =
Ted Kremenek5eca4822012-01-06 22:09:28 +0000529 cast<DefinedOrUnknownSVal>(state->getSVal(Arg1, LCtx));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000530
531 // Compare the size argument to 0.
532 DefinedOrUnknownSVal SizeZero =
533 svalBuilder.evalEQ(state, Arg1Val,
534 svalBuilder.makeIntValWithPtrWidth(0, false));
535
536 // If the ptr is NULL and the size is not 0, the call is equivalent to
537 // malloc(size).
Ted Kremenek8bef8232012-01-26 21:29:00 +0000538 ProgramStateRef stateEqual = state->assume(PtrEQ, true);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000539 if (stateEqual && state->assume(SizeZero, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000540 // Hack: set the NULL symbolic region to released to suppress false warning.
541 // In the future we should add more states for allocated regions, e.g.,
542 // CheckedNull, CheckedNonNull.
543
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000544 SymbolRef Sym = arg0Val.getAsLocSymbol();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000545 if (Sym)
546 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
547
Ted Kremenek8bef8232012-01-26 21:29:00 +0000548 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000549 UndefinedVal(), stateEqual);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000550 C.addTransition(stateMalloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000551 }
552
Ted Kremenek8bef8232012-01-26 21:29:00 +0000553 if (ProgramStateRef stateNotEqual = state->assume(PtrEQ, false)) {
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000554 // If the size is 0, free the memory.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000555 if (ProgramStateRef stateSizeZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000556 stateNotEqual->assume(SizeZero, true))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000557 if (ProgramStateRef stateFree =
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000558 FreeMemAux(C, CE, stateSizeZero, 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000559
Zhongxing Xud56763f2011-09-01 04:53:59 +0000560 // Bind the return value to NULL because it is now free.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000561 C.addTransition(stateFree->BindExpr(CE, LCtx,
562 svalBuilder.makeNull(), true));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000563 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000564 if (ProgramStateRef stateSizeNotZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000565 stateNotEqual->assume(SizeZero,false))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000566 if (ProgramStateRef stateFree = FreeMemAux(C, CE, stateSizeNotZero,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000567 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000568 // FIXME: We should copy the content of the original buffer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000569 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000570 UnknownVal(), stateFree);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000571 C.addTransition(stateRealloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000572 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000573 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000574}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000575
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000576void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000577 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000578 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000579 const LocationContext *LCtx = C.getLocationContext();
580 SVal count = state->getSVal(CE->getArg(0), LCtx);
581 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000582 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
583 svalBuilder.getContext().getSizeType());
584 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000585
Anna Zaks0bd6b112011-10-26 21:06:34 +0000586 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000587}
588
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000589void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
590 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000591{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000592 if (!SymReaper.hasDeadSymbols())
593 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000594
Ted Kremenek8bef8232012-01-26 21:29:00 +0000595 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000596 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000597 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000598
Ted Kremenek217470e2011-07-28 23:07:51 +0000599 bool generateReport = false;
600
Zhongxing Xu173ff562010-08-15 08:19:57 +0000601 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
602 if (SymReaper.isDead(I->first)) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000603 if (I->second.isAllocated())
604 generateReport = true;
Jordy Rose90760142010-08-18 04:33:47 +0000605
606 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000607 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000608
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000609 }
610 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000611
Anna Zaks0bd6b112011-10-26 21:06:34 +0000612 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000613
614 // FIXME: This does not handle when we have multiple leaks at a single
615 // place.
616 if (N && generateReport) {
617 if (!BT_Leak)
618 BT_Leak.reset(new BuiltinBug("Memory leak",
619 "Allocated memory never released. Potential memory leak."));
620 // FIXME: where it is allocated.
621 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
622 C.EmitReport(R);
623 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000624}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000625
Anna Zaksaf498a22011-10-25 19:56:48 +0000626void MallocChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000627 ProgramStateRef state = Ctx.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000628 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000629
Jordy Rose09cef092010-08-18 04:26:59 +0000630 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000631 RefState RS = I->second;
632 if (RS.isAllocated()) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000633 ExplodedNode *N = Ctx.addTransition(state);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000634 if (N) {
635 if (!BT_Leak)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000636 BT_Leak.reset(new BuiltinBug("Memory leak",
637 "Allocated memory never released. Potential memory leak."));
Zhongxing Xu243fde92009-11-17 07:54:15 +0000638 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
Anna Zaksaf498a22011-10-25 19:56:48 +0000639 Ctx.EmitReport(R);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000640 }
641 }
642 }
643}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000644
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000645void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000646 const Expr *retExpr = S->getRetValue();
647 if (!retExpr)
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000648 return;
649
Ted Kremenek8bef8232012-01-26 21:29:00 +0000650 ProgramStateRef state = C.getState();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000651
Ted Kremenek5eca4822012-01-06 22:09:28 +0000652 SymbolRef Sym = state->getSVal(retExpr, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000653 if (!Sym)
654 return;
655
656 const RefState *RS = state->get<RegionState>(Sym);
657 if (!RS)
658 return;
659
660 // FIXME: check other cases.
661 if (RS->isAllocated())
662 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
663
Anna Zaks0bd6b112011-10-26 21:06:34 +0000664 C.addTransition(state);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000665}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000666
Ted Kremenek8bef8232012-01-26 21:29:00 +0000667ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000668 SVal Cond,
669 bool Assumption) const {
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000670 // If a symblic region is assumed to NULL, set its state to AllocateFailed.
671 // FIXME: should also check symbols assumed to non-null.
672
673 RegionStateTy RS = state->get<RegionState>();
674
675 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Zhongxing Xu2bfa3012011-04-02 03:20:45 +0000676 // If the symbol is assumed to NULL, this will return an APSInt*.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000677 if (state->getSymVal(I.getKey()))
678 state = state->set<RegionState>(I.getKey(),RefState::getAllocateFailed());
679 }
680
681 return state;
682}
Zhongxing Xuc8023782010-03-10 04:58:55 +0000683
684// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000685void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
686 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000687 SymbolRef Sym = l.getLocSymbolInBase();
688 if (Sym) {
689 const RefState *RS = C.getState()->get<RegionState>(Sym);
Ted Kremenekcea68652010-08-06 21:12:49 +0000690 if (RS && RS->isReleased()) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000691 if (ExplodedNode *N = C.addTransition()) {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000692 if (!BT_UseFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000693 BT_UseFree.reset(new BuiltinBug("Use dynamically allocated memory "
694 "after it is freed."));
Zhongxing Xuc8023782010-03-10 04:58:55 +0000695
696 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),
697 N);
698 C.EmitReport(R);
699 }
Ted Kremenekcea68652010-08-06 21:12:49 +0000700 }
Zhongxing Xuc8023782010-03-10 04:58:55 +0000701 }
702}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000703
Anna Zaks390909c2011-10-06 00:43:15 +0000704void MallocChecker::checkBind(SVal location, SVal val,
705 const Stmt *BindS, CheckerContext &C) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000706 // The PreVisitBind implements the same algorithm as already used by the
707 // Objective C ownership checker: if the pointer escaped from this scope by
708 // assignment, let it go. However, assigning to fields of a stack-storage
709 // structure does not transfer ownership.
710
Ted Kremenek8bef8232012-01-26 21:29:00 +0000711 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000712 DefinedOrUnknownSVal l = cast<DefinedOrUnknownSVal>(location);
713
714 // Check for null dereferences.
715 if (!isa<Loc>(l))
716 return;
717
718 // Before checking if the state is null, check if 'val' has a RefState.
719 // Only then should we check for null and bifurcate the state.
720 SymbolRef Sym = val.getLocSymbolInBase();
721 if (Sym) {
722 if (const RefState *RS = state->get<RegionState>(Sym)) {
723 // If ptr is NULL, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000724 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000725 llvm::tie(notNullState, nullState) = state->assume(l);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000726
727 // Generate a transition for 'nullState' to record the assumption
728 // that the state was null.
729 if (nullState)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000730 C.addTransition(nullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000731
732 if (!notNullState)
733 return;
734
735 if (RS->isAllocated()) {
736 // Something we presently own is being assigned somewhere.
737 const MemRegion *AR = location.getAsRegion();
738 if (!AR)
739 return;
740 AR = AR->StripCasts()->getBaseRegion();
741 do {
742 // If it is on the stack, we still own it.
743 if (AR->hasStackNonParametersStorage())
744 break;
745
746 // If the state can't represent this binding, we still own it.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000747 if (notNullState == (notNullState->bindLoc(cast<Loc>(location),
748 UnknownVal())))
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000749 break;
750
751 // We no longer own this pointer.
Ted Kremenekdde201b2010-08-06 21:12:55 +0000752 notNullState =
753 notNullState->set<RegionState>(Sym,
Anna Zaks390909c2011-10-06 00:43:15 +0000754 RefState::getRelinquished(BindS));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000755 }
756 while (false);
757 }
Anna Zaks0bd6b112011-10-26 21:06:34 +0000758 C.addTransition(notNullState);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000759 }
760 }
761}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000762
Anna Zaks231361a2012-02-08 23:16:52 +0000763#define REGISTER_CHECKER(name) \
764void ento::register##name(CheckerManager &mgr) {\
765 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000766}
Anna Zaks231361a2012-02-08 23:16:52 +0000767
768REGISTER_CHECKER(MallocPessimistic)
769REGISTER_CHECKER(MallocOptimistic)