blob: ea4d7d29eab8b0a9f8f15f150ad02f3ec9fa91d3 [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,
Anna Zaks4fb54872012-02-11 21:02:35 +000075 eval::Assume,
76 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000077{
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000078 mutable OwningPtr<BuiltinBug> BT_DoubleFree;
79 mutable OwningPtr<BuiltinBug> BT_Leak;
80 mutable OwningPtr<BuiltinBug> BT_UseFree;
81 mutable OwningPtr<BuiltinBug> BT_UseRelinquished;
82 mutable OwningPtr<BuiltinBug> BT_BadFree;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000083 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000084
85public:
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000086 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +000087
88 /// In pessimistic mode, the checker assumes that it does not know which
89 /// functions might free the memory.
90 struct ChecksFilter {
91 DefaultBool CMallocPessimistic;
92 DefaultBool CMallocOptimistic;
93 };
94
95 ChecksFilter Filter;
96
Anna Zaksb319e022012-02-08 20:13:28 +000097 void initIdentifierInfo(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000098
Anna Zaksb319e022012-02-08 20:13:28 +000099 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000100 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000101 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000102 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000103 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000104 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000105 void checkLocation(SVal l, bool isLoad, const Stmt *S,
106 CheckerContext &C) const;
107 void checkBind(SVal location, SVal val, const Stmt*S,
108 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000109 ProgramStateRef
110 checkRegionChanges(ProgramStateRef state,
111 const StoreManager::InvalidatedSymbols *invalidated,
112 ArrayRef<const MemRegion *> ExplicitRegions,
113 ArrayRef<const MemRegion *> Regions) const;
114 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
115 return true;
116 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000117
Zhongxing Xu7b760962009-11-13 07:25:27 +0000118private:
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000119 static void MallocMem(CheckerContext &C, const CallExpr *CE);
120 static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
121 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000122 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000123 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000124 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000125 return MallocMemAux(C, CE,
126 state->getSVal(SizeEx, C.getLocationContext()),
127 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000128 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000129 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000130 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000131 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000132
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000133 void FreeMem(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose2a479922010-08-12 08:54:03 +0000134 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000135 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000136 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
137 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000138 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000139
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000140 void ReallocMem(CheckerContext &C, const CallExpr *CE) const;
141 static void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000142
Anna Zaks91c2a112012-02-08 23:16:56 +0000143 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
144 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
145 const Stmt *S = 0) const;
146
Ted Kremenek9c378f72011-08-12 23:37:29 +0000147 static bool SummarizeValue(raw_ostream &os, SVal V);
148 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000149 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000150
Anna Zaksda046772012-02-11 21:02:40 +0000151 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
152
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000153 /// The bug visitor which allows us to print extra diagnostics along the
154 /// BugReport path. For example, showing the allocation site of the leaked
155 /// region.
156 class MallocBugVisitor : public BugReporterVisitor {
157 protected:
158 // The allocated region symbol tracked by the main analysis.
159 SymbolRef Sym;
160
161 public:
162 MallocBugVisitor(SymbolRef S) : Sym(S) {}
163 virtual ~MallocBugVisitor() {}
164
165 void Profile(llvm::FoldingSetNodeID &ID) const {
166 static int X = 0;
167 ID.AddPointer(&X);
168 ID.AddPointer(Sym);
169 }
170
171 inline bool isAllocated(const RefState *S, const RefState *SPrev) {
172 // Did not track -> allocated. Other state (released) -> allocated.
173 return ((S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
174 }
175
176 inline bool isReleased(const RefState *S, const RefState *SPrev) {
177 // Did not track -> released. Other state (allocated) -> released.
178 return ((S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
179 }
180
181 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
182 const ExplodedNode *PrevN,
183 BugReporterContext &BRC,
184 BugReport &BR);
185 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000186};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000187} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000188
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000189typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
190
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000191namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000192namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000193 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000194 struct ProgramStateTrait<RegionState>
195 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000196 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000197 };
198}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000199}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000200
Anna Zaks4fb54872012-02-11 21:02:35 +0000201namespace {
202class StopTrackingCallback : public SymbolVisitor {
203 ProgramStateRef state;
204public:
205 StopTrackingCallback(ProgramStateRef st) : state(st) {}
206 ProgramStateRef getState() const { return state; }
207
208 bool VisitSymbol(SymbolRef sym) {
209 state = state->remove<RegionState>(sym);
210 return true;
211 }
212};
213} // end anonymous namespace
214
Anna Zaksb319e022012-02-08 20:13:28 +0000215void MallocChecker::initIdentifierInfo(CheckerContext &C) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000216 ASTContext &Ctx = C.getASTContext();
217 if (!II_malloc)
218 II_malloc = &Ctx.Idents.get("malloc");
219 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000220 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000221 if (!II_realloc)
222 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000223 if (!II_calloc)
224 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000225}
226
227void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
228 const FunctionDecl *FD = C.getCalleeDecl(CE);
229 if (!FD)
230 return;
231 initIdentifierInfo(C);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000232
233 if (FD->getIdentifier() == II_malloc) {
234 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000235 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000236 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000237 if (FD->getIdentifier() == II_realloc) {
238 ReallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000239 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000240 }
241
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000242 if (FD->getIdentifier() == II_calloc) {
243 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000244 return;
245 }
246
247 if (FD->getIdentifier() == II_free) {
248 FreeMem(C, CE);
249 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000250 }
251
Anna Zaks91c2a112012-02-08 23:16:56 +0000252 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000253 // Check all the attributes, if there are any.
254 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000255 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000256 for (specific_attr_iterator<OwnershipAttr>
257 i = FD->specific_attr_begin<OwnershipAttr>(),
258 e = FD->specific_attr_end<OwnershipAttr>();
259 i != e; ++i) {
260 switch ((*i)->getOwnKind()) {
261 case OwnershipAttr::Returns: {
262 MallocMemReturnsAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000263 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000264 }
265 case OwnershipAttr::Takes:
266 case OwnershipAttr::Holds: {
267 FreeMemAttr(C, CE, *i);
Jordy Rose2a479922010-08-12 08:54:03 +0000268 break;
Sean Huntcf807c42010-08-18 23:23:40 +0000269 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000270 }
271 }
272 }
Anna Zaks91c2a112012-02-08 23:16:56 +0000273
274 if (Filter.CMallocPessimistic) {
275 ProgramStateRef State = C.getState();
276 // The pointer might escape through a function call.
277 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
278 E = CE->arg_end(); I != E; ++I) {
279 const Expr *A = *I;
280 if (A->getType().getTypePtr()->isAnyPointerType()) {
281 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
282 if (!Sym)
Anna Zakse9ef5622012-02-10 01:11:00 +0000283 continue;
Anna Zaks91c2a112012-02-08 23:16:56 +0000284 checkEscape(Sym, A, C);
285 checkUseAfterFree(Sym, C, A);
286 }
287 }
288 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000289}
290
291void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000292 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000293 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000294 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000295}
296
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000297void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
298 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000299 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000300 return;
301
Sean Huntcf807c42010-08-18 23:23:40 +0000302 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000303 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000304 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000305 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000306 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000307 return;
308 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000309 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000310 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000311 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000312}
313
Anna Zaksb319e022012-02-08 20:13:28 +0000314ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000315 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000316 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000317 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000318 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000319
Anna Zaksb319e022012-02-08 20:13:28 +0000320 // Get the return value.
321 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000322
Jordy Rose32f26562010-07-04 00:00:41 +0000323 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000324 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000325
Jordy Rose32f26562010-07-04 00:00:41 +0000326 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000327 const SymbolicRegion *R =
328 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
329 if (!R || !isa<DefinedOrUnknownSVal>(Size))
330 return 0;
331
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000332 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000333 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000334 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000335 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000336
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000337 state = state->assume(extentMatchesSize, true);
338 assert(state);
339
340 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000341 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000342
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000343 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000344 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000345}
346
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000347void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000348 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000349
350 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000351 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000352}
353
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000354void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000355 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000356 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000357 return;
358
Sean Huntcf807c42010-08-18 23:23:40 +0000359 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
360 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000361 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000362 FreeMemAux(C, CE, C.getState(), *I,
363 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000364 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000365 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000366 }
367}
368
Ted Kremenek8bef8232012-01-26 21:29:00 +0000369ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000370 const CallExpr *CE,
371 ProgramStateRef state,
372 unsigned Num,
373 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000374 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000375 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000376 if (!isa<DefinedOrUnknownSVal>(ArgVal))
377 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000378 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
379
380 // Check for null dereferences.
381 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000382 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000383
384 // FIXME: Technically using 'Assume' here can result in a path
385 // bifurcation. In such cases we need to return two states, not just one.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000386 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000387 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000388
389 // The explicit NULL case, no operation is performed.
390 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000391 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000392
393 assert(notNullState);
394
Jordy Rose43859f62010-06-07 19:32:37 +0000395 // Unknown values could easily be okay
396 // Undefined values are handled elsewhere
397 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000398 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000399
Jordy Rose43859f62010-06-07 19:32:37 +0000400 const MemRegion *R = ArgVal.getAsRegion();
401
402 // Nonlocs can't be freed, of course.
403 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
404 if (!R) {
405 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000406 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000407 }
408
409 R = R->StripCasts();
410
411 // Blocks might show up as heap data, but should not be free()d
412 if (isa<BlockDataRegion>(R)) {
413 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000414 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000415 }
416
417 const MemSpaceRegion *MS = R->getMemorySpace();
418
419 // Parameters, locals, statics, and globals shouldn't be freed.
420 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
421 // FIXME: at the time this code was written, malloc() regions were
422 // represented by conjured symbols, which are all in UnknownSpaceRegion.
423 // This means that there isn't actually anything from HeapSpaceRegion
424 // that should be freed, even though we allow it here.
425 // Of course, free() can work on memory allocated outside the current
426 // function, so UnknownSpaceRegion is always a possibility.
427 // False negatives are better than false positives.
428
429 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000430 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000431 }
432
433 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
434 // Various cases could lead to non-symbol values here.
435 // For now, ignore them.
436 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000437 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000438
439 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000440 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000441
442 // If the symbol has not been tracked, return. This is possible when free() is
443 // called on a pointer that does not get its pointee directly from malloc().
444 // Full support of this requires inter-procedural analysis.
445 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000446 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000447
448 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000449 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000450 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000451 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000452 BT_DoubleFree.reset(
453 new BuiltinBug("Double free",
454 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000455 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000456 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000457 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000458 C.EmitReport(R);
459 }
Anna Zaksb319e022012-02-08 20:13:28 +0000460 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000461 }
462
463 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000464 if (Hold)
465 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
466 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000467}
468
Ted Kremenek9c378f72011-08-12 23:37:29 +0000469bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000470 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
471 os << "an integer (" << IntVal->getValue() << ")";
472 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
473 os << "a constant address (" << ConstAddr->getValue() << ")";
474 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000475 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000476 else
477 return false;
478
479 return true;
480}
481
Ted Kremenek9c378f72011-08-12 23:37:29 +0000482bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000483 const MemRegion *MR) {
484 switch (MR->getKind()) {
485 case MemRegion::FunctionTextRegionKind: {
486 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
487 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000488 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000489 else
490 os << "the address of a function";
491 return true;
492 }
493 case MemRegion::BlockTextRegionKind:
494 os << "block text";
495 return true;
496 case MemRegion::BlockDataRegionKind:
497 // FIXME: where the block came from?
498 os << "a block";
499 return true;
500 default: {
501 const MemSpaceRegion *MS = MR->getMemorySpace();
502
Anna Zakseb31a762012-01-04 23:54:01 +0000503 if (isa<StackLocalsSpaceRegion>(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 os << "the address of the local variable '" << VD->getName() << "'";
513 else
514 os << "the address of a local stack variable";
515 return true;
516 }
Anna Zakseb31a762012-01-04 23:54:01 +0000517
518 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000519 const VarRegion *VR = dyn_cast<VarRegion>(MR);
520 const VarDecl *VD;
521 if (VR)
522 VD = VR->getDecl();
523 else
524 VD = NULL;
525
526 if (VD)
527 os << "the address of the parameter '" << VD->getName() << "'";
528 else
529 os << "the address of a parameter";
530 return true;
531 }
Anna Zakseb31a762012-01-04 23:54:01 +0000532
533 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000534 const VarRegion *VR = dyn_cast<VarRegion>(MR);
535 const VarDecl *VD;
536 if (VR)
537 VD = VR->getDecl();
538 else
539 VD = NULL;
540
541 if (VD) {
542 if (VD->isStaticLocal())
543 os << "the address of the static variable '" << VD->getName() << "'";
544 else
545 os << "the address of the global variable '" << VD->getName() << "'";
546 } else
547 os << "the address of a global variable";
548 return true;
549 }
Anna Zakseb31a762012-01-04 23:54:01 +0000550
551 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000552 }
553 }
554}
555
556void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000557 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000558 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000559 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000560 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000561
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000562 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000563 llvm::raw_svector_ostream os(buf);
564
565 const MemRegion *MR = ArgVal.getAsRegion();
566 if (MR) {
567 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
568 MR = ER->getSuperRegion();
569
570 // Special case for alloca()
571 if (isa<AllocaRegion>(MR))
572 os << "Argument to free() was allocated by alloca(), not malloc()";
573 else {
574 os << "Argument to free() is ";
575 if (SummarizeRegion(os, MR))
576 os << ", which is not memory allocated by malloc()";
577 else
578 os << "not memory allocated by malloc()";
579 }
580 } else {
581 os << "Argument to free() is ";
582 if (SummarizeValue(os, ArgVal))
583 os << ", which is not memory allocated by malloc()";
584 else
585 os << "not memory allocated by malloc()";
586 }
587
Anna Zakse172e8b2011-08-17 23:00:25 +0000588 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000589 R->addRange(range);
590 C.EmitReport(R);
591 }
592}
593
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000594void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000595 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000596 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000597 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000598 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
599 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
600 return;
601 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000602
Ted Kremenek846eabd2010-12-01 21:28:31 +0000603 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000604
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000605 DefinedOrUnknownSVal PtrEQ =
606 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000607
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000608 // Get the size argument. If there is no size arg then give up.
609 const Expr *Arg1 = CE->getArg(1);
610 if (!Arg1)
611 return;
612
613 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000614 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
615 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
616 return;
617 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000618
619 // Compare the size argument to 0.
620 DefinedOrUnknownSVal SizeZero =
621 svalBuilder.evalEQ(state, Arg1Val,
622 svalBuilder.makeIntValWithPtrWidth(0, false));
623
624 // If the ptr is NULL and the size is not 0, the call is equivalent to
625 // malloc(size).
Ted Kremenek8bef8232012-01-26 21:29:00 +0000626 ProgramStateRef stateEqual = state->assume(PtrEQ, true);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000627 if (stateEqual && state->assume(SizeZero, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000628 // Hack: set the NULL symbolic region to released to suppress false warning.
629 // In the future we should add more states for allocated regions, e.g.,
630 // CheckedNull, CheckedNonNull.
631
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000632 SymbolRef Sym = arg0Val.getAsLocSymbol();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000633 if (Sym)
634 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
635
Ted Kremenek8bef8232012-01-26 21:29:00 +0000636 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000637 UndefinedVal(), stateEqual);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000638 C.addTransition(stateMalloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000639 }
640
Ted Kremenek8bef8232012-01-26 21:29:00 +0000641 if (ProgramStateRef stateNotEqual = state->assume(PtrEQ, false)) {
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000642 // If the size is 0, free the memory.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000643 if (ProgramStateRef stateSizeZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000644 stateNotEqual->assume(SizeZero, true))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000645 if (ProgramStateRef stateFree =
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000646 FreeMemAux(C, CE, stateSizeZero, 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000647
Zhongxing Xud56763f2011-09-01 04:53:59 +0000648 // Bind the return value to NULL because it is now free.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000649 C.addTransition(stateFree->BindExpr(CE, LCtx,
650 svalBuilder.makeNull(), true));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000651 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000652 if (ProgramStateRef stateSizeNotZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000653 stateNotEqual->assume(SizeZero,false))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000654 if (ProgramStateRef stateFree = FreeMemAux(C, CE, stateSizeNotZero,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000655 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000656 // FIXME: We should copy the content of the original buffer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000657 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000658 UnknownVal(), stateFree);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000659 C.addTransition(stateRealloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000660 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000661 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000662}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000663
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000664void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000665 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000666 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000667 const LocationContext *LCtx = C.getLocationContext();
668 SVal count = state->getSVal(CE->getArg(0), LCtx);
669 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000670 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
671 svalBuilder.getContext().getSizeType());
672 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000673
Anna Zaks0bd6b112011-10-26 21:06:34 +0000674 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000675}
676
Anna Zaksda046772012-02-11 21:02:40 +0000677void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
678 CheckerContext &C) const {
679 assert(N);
680 if (!BT_Leak) {
681 BT_Leak.reset(new BuiltinBug("Memory leak",
682 "Allocated memory never released. Potential memory leak."));
683 // Leaks should not be reported if they are post-dominated by a sink:
684 // (1) Sinks are higher importance bugs.
685 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
686 // with __noreturn functions such as assert() or exit(). We choose not
687 // to report leaks on such paths.
688 BT_Leak->setSuppressOnSink(true);
689 }
690
691 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
692 R->addVisitor(new MallocBugVisitor(Sym));
693 C.EmitReport(R);
694}
695
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000696void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
697 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000698{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000699 if (!SymReaper.hasDeadSymbols())
700 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000701
Ted Kremenek8bef8232012-01-26 21:29:00 +0000702 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000703 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000704 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000705
Ted Kremenek217470e2011-07-28 23:07:51 +0000706 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000707 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000708 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
709 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000710 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000711 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000712 Errors.push_back(I->first);
713 }
Jordy Rose90760142010-08-18 04:33:47 +0000714 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000715 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000716
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000717 }
718 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000719
Anna Zaks0bd6b112011-10-26 21:06:34 +0000720 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000721
Ted Kremenek217470e2011-07-28 23:07:51 +0000722 if (N && generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000723 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000724 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
725 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000726 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000727 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000728}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000729
Anna Zaksda046772012-02-11 21:02:40 +0000730void MallocChecker::checkEndPath(CheckerContext &C) const {
731 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000732 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000733
Jordy Rose09cef092010-08-18 04:26:59 +0000734 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000735 RefState RS = I->second;
736 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000737 ExplodedNode *N = C.addTransition(state);
738 if (N)
739 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000740 }
741 }
742}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000743
Anna Zaks91c2a112012-02-08 23:16:56 +0000744bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
745 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000746 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000747 const RefState *RS = state->get<RegionState>(Sym);
748 if (!RS)
749 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000750
Anna Zaks91c2a112012-02-08 23:16:56 +0000751 if (RS->isAllocated()) {
752 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
753 C.addTransition(state);
754 return true;
755 }
756 return false;
757}
758
759void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
760 const Expr *E = S->getRetValue();
761 if (!E)
762 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000763
764 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000765 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000766 if (!Sym)
767 return;
768
Anna Zaks0860cd02012-02-11 21:44:39 +0000769 // Check if we are returning freed memory.
770 checkUseAfterFree(Sym, C, S);
771
772 // Check if the symbol is escaping.
Anna Zaks91c2a112012-02-08 23:16:56 +0000773 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000774}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000775
Anna Zaks91c2a112012-02-08 23:16:56 +0000776bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
777 const Stmt *S) const {
778 assert(Sym);
779 const RefState *RS = C.getState()->get<RegionState>(Sym);
780 if (RS && RS->isReleased()) {
781 if (ExplodedNode *N = C.addTransition()) {
782 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000783 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000784 "after it is freed."));
785
786 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
787 if (S)
788 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000789 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000790 C.EmitReport(R);
791 return true;
792 }
793 }
794 return false;
795}
796
Zhongxing Xuc8023782010-03-10 04:58:55 +0000797// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000798void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
799 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000800 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000801 if (Sym)
802 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000803}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000804
Anna Zaks4fb54872012-02-11 21:02:35 +0000805//===----------------------------------------------------------------------===//
806// Check various ways a symbol can be invalidated.
807// TODO: This logic (the next 3 functions) is copied/similar to the
808// RetainRelease checker. We might want to factor this out.
809//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000810
Anna Zaks4fb54872012-02-11 21:02:35 +0000811// Stop tracking symbols when a value escapes as a result of checkBind.
812// A value escapes in three possible cases:
813// (1) we are binding to something that is not a memory region.
814// (2) we are binding to a memregion that does not have stack storage
815// (3) we are binding to a memregion with stack storage that the store
816// does not understand.
817void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
818 CheckerContext &C) const {
819 // Are we storing to something that causes the value to "escape"?
820 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000821 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000822
Anna Zaks4fb54872012-02-11 21:02:35 +0000823 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
824 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000825
Anna Zaks4fb54872012-02-11 21:02:35 +0000826 if (!escapes) {
827 // To test (3), generate a new state with the binding added. If it is
828 // the same state, then it escapes (since the store cannot represent
829 // the binding).
830 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000831 }
832 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000833
834 // If our store can represent the binding and we aren't storing to something
835 // that doesn't have local storage then just return and have the simulation
836 // state continue as is.
837 if (!escapes)
838 return;
839
840 // Otherwise, find all symbols referenced by 'val' that we are tracking
841 // and stop tracking them.
842 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
843 C.addTransition(state);
844}
845
846// If a symbolic region is assumed to NULL (or another constant), stop tracking
847// it - assuming that allocation failed on this path.
848ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
849 SVal Cond,
850 bool Assumption) const {
851 RegionStateTy RS = state->get<RegionState>();
852
853 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
854 // If the symbol is assumed to NULL or another constant, this will
855 // return an APSInt*.
856 if (state->getSymVal(I.getKey()))
857 state = state->remove<RegionState>(I.getKey());
858 }
859
860 return state;
861}
862
863// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
864// escapes, when we are tracking p), do not track the symbol as we cannot reason
865// about it anymore.
866ProgramStateRef
867MallocChecker::checkRegionChanges(ProgramStateRef state,
868 const StoreManager::InvalidatedSymbols *invalidated,
869 ArrayRef<const MemRegion *> ExplicitRegions,
870 ArrayRef<const MemRegion *> Regions) const {
871 if (!invalidated)
872 return state;
873
874 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
875 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
876 E = ExplicitRegions.end(); I != E; ++I) {
877 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
878 WhitelistedSymbols.insert(SR->getSymbol());
879 }
880
881 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
882 E = invalidated->end(); I!=E; ++I) {
883 SymbolRef sym = *I;
884 if (WhitelistedSymbols.count(sym))
885 continue;
886 // Don't track the symbol.
887 state = state->remove<RegionState>(sym);
888 }
889 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000890}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000891
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000892PathDiagnosticPiece *
893MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
894 const ExplodedNode *PrevN,
895 BugReporterContext &BRC,
896 BugReport &BR) {
897 const RefState *RS = N->getState()->get<RegionState>(Sym);
898 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
899 if (!RS && !RSPrev)
900 return 0;
901
902 // We expect the interesting locations be StmtPoints corresponding to call
903 // expressions. We do not support indirect function calls as of now.
904 const CallExpr *CE = 0;
905 if (isa<StmtPoint>(N->getLocation()))
906 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
907 if (!CE)
908 return 0;
909 const FunctionDecl *funDecl = CE->getDirectCallee();
910 if (!funDecl)
911 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000912
913 // Find out if this is an interesting point and what is the kind.
914 const char *Msg = 0;
915 if (isAllocated(RS, RSPrev))
916 Msg = "Memory is allocated here";
917 else if (isReleased(RS, RSPrev))
918 Msg = "Memory is released here";
919 if (!Msg)
920 return 0;
921
922 // Generate the extra diagnostic.
923 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
924 N->getLocationContext());
925 return new PathDiagnosticEventPiece(Pos, Msg);
926}
927
928
Anna Zaks231361a2012-02-08 23:16:52 +0000929#define REGISTER_CHECKER(name) \
930void ento::register##name(CheckerManager &mgr) {\
931 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000932}
Anna Zaks231361a2012-02-08 23:16:52 +0000933
934REGISTER_CHECKER(MallocPessimistic)
935REGISTER_CHECKER(MallocOptimistic)