blob: f486a7e8c9a2f82032ee516d2c476081d653eaaf [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"
Anna Zaks15d0ae12012-02-11 23:46:36 +000023#include "clang/Basic/SourceManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000024#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000025#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000026#include "llvm/ADT/STLExtras.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000027using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000028using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000029
30namespace {
31
Zhongxing Xu7fb14642009-12-11 00:55:44 +000032class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000033 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
34 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000035 const Stmt *S;
36
Zhongxing Xu7fb14642009-12-11 00:55:44 +000037public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000038 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
39
Zhongxing Xub94b81a2009-12-31 06:13:07 +000040 bool isAllocated() const { return K == AllocateUnchecked; }
Chris Lattnerfae96222010-09-03 04:34:38 +000041 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000042 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000043 //bool isEscaped() const { return K == Escaped; }
44 //bool isRelinquished() const { return K == Relinquished; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000045
46 bool operator==(const RefState &X) const {
47 return K == X.K && S == X.S;
48 }
49
Zhongxing Xub94b81a2009-12-31 06:13:07 +000050 static RefState getAllocateUnchecked(const Stmt *s) {
51 return RefState(AllocateUnchecked, s);
52 }
53 static RefState getAllocateFailed() {
54 return RefState(AllocateFailed, 0);
55 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000056 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
57 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000058 static RefState getRelinquished(const Stmt *s) {
59 return RefState(Relinquished, s);
60 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000061
62 void Profile(llvm::FoldingSetNodeID &ID) const {
63 ID.AddInteger(K);
64 ID.AddPointer(S);
65 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000066};
67
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000068class RegionState {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +000069
Anna Zaksb319e022012-02-08 20:13:28 +000070class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000071 check::EndPath,
72 check::PreStmt<ReturnStmt>,
Anna Zaksb319e022012-02-08 20:13:28 +000073 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000074 check::Location,
75 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000076 eval::Assume,
77 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000078{
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000079 mutable OwningPtr<BuiltinBug> BT_DoubleFree;
80 mutable OwningPtr<BuiltinBug> BT_Leak;
81 mutable OwningPtr<BuiltinBug> BT_UseFree;
82 mutable OwningPtr<BuiltinBug> BT_UseRelinquished;
83 mutable OwningPtr<BuiltinBug> BT_BadFree;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000084 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000085
86public:
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000087 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +000088
89 /// In pessimistic mode, the checker assumes that it does not know which
90 /// functions might free the memory.
91 struct ChecksFilter {
92 DefaultBool CMallocPessimistic;
93 DefaultBool CMallocOptimistic;
94 };
95
96 ChecksFilter Filter;
97
Anna Zaksb319e022012-02-08 20:13:28 +000098 void initIdentifierInfo(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000099
Anna Zaksb319e022012-02-08 20:13:28 +0000100 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000101 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000102 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000103 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000104 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000105 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000106 void checkLocation(SVal l, bool isLoad, const Stmt *S,
107 CheckerContext &C) const;
108 void checkBind(SVal location, SVal val, const Stmt*S,
109 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000110 ProgramStateRef
111 checkRegionChanges(ProgramStateRef state,
112 const StoreManager::InvalidatedSymbols *invalidated,
113 ArrayRef<const MemRegion *> ExplicitRegions,
114 ArrayRef<const MemRegion *> Regions) const;
115 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
116 return true;
117 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000118
Zhongxing Xu7b760962009-11-13 07:25:27 +0000119private:
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000120 static void MallocMem(CheckerContext &C, const CallExpr *CE);
121 static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
122 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000123 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000124 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000125 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000126 return MallocMemAux(C, CE,
127 state->getSVal(SizeEx, C.getLocationContext()),
128 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000129 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000130 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000131 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000132 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000133
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000134 void FreeMem(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose2a479922010-08-12 08:54:03 +0000135 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000136 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000137 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
138 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000139 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000140
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000141 void ReallocMem(CheckerContext &C, const CallExpr *CE) const;
142 static void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000143
Anna Zaks91c2a112012-02-08 23:16:56 +0000144 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
145 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
146 const Stmt *S = 0) const;
147
Ted Kremenek9c378f72011-08-12 23:37:29 +0000148 static bool SummarizeValue(raw_ostream &os, SVal V);
149 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000150 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000151
Anna Zaksda046772012-02-11 21:02:40 +0000152 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
153
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000154 /// The bug visitor which allows us to print extra diagnostics along the
155 /// BugReport path. For example, showing the allocation site of the leaked
156 /// region.
157 class MallocBugVisitor : public BugReporterVisitor {
158 protected:
159 // The allocated region symbol tracked by the main analysis.
160 SymbolRef Sym;
161
162 public:
163 MallocBugVisitor(SymbolRef S) : Sym(S) {}
164 virtual ~MallocBugVisitor() {}
165
166 void Profile(llvm::FoldingSetNodeID &ID) const {
167 static int X = 0;
168 ID.AddPointer(&X);
169 ID.AddPointer(Sym);
170 }
171
172 inline bool isAllocated(const RefState *S, const RefState *SPrev) {
173 // Did not track -> allocated. Other state (released) -> allocated.
174 return ((S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
175 }
176
177 inline bool isReleased(const RefState *S, const RefState *SPrev) {
178 // Did not track -> released. Other state (allocated) -> released.
179 return ((S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
180 }
181
182 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
183 const ExplodedNode *PrevN,
184 BugReporterContext &BRC,
185 BugReport &BR);
186 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000187};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000188} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000189
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000190typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
191
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000192namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000193namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000194 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000195 struct ProgramStateTrait<RegionState>
196 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000197 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000198 };
199}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000200}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000201
Anna Zaks4fb54872012-02-11 21:02:35 +0000202namespace {
203class StopTrackingCallback : public SymbolVisitor {
204 ProgramStateRef state;
205public:
206 StopTrackingCallback(ProgramStateRef st) : state(st) {}
207 ProgramStateRef getState() const { return state; }
208
209 bool VisitSymbol(SymbolRef sym) {
210 state = state->remove<RegionState>(sym);
211 return true;
212 }
213};
214} // end anonymous namespace
215
Anna Zaksb319e022012-02-08 20:13:28 +0000216void MallocChecker::initIdentifierInfo(CheckerContext &C) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000217 ASTContext &Ctx = C.getASTContext();
218 if (!II_malloc)
219 II_malloc = &Ctx.Idents.get("malloc");
220 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000221 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000222 if (!II_realloc)
223 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000224 if (!II_calloc)
225 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000226}
227
228void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
229 const FunctionDecl *FD = C.getCalleeDecl(CE);
230 if (!FD)
231 return;
232 initIdentifierInfo(C);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000233
234 if (FD->getIdentifier() == II_malloc) {
235 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000236 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000237 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000238 if (FD->getIdentifier() == II_realloc) {
239 ReallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000240 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000241 }
242
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000243 if (FD->getIdentifier() == II_calloc) {
244 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000245 return;
246 }
247
248 if (FD->getIdentifier() == II_free) {
249 FreeMem(C, CE);
250 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000251 }
252
Anna Zaks91c2a112012-02-08 23:16:56 +0000253 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000254 // Check all the attributes, if there are any.
255 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000256 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000257 for (specific_attr_iterator<OwnershipAttr>
258 i = FD->specific_attr_begin<OwnershipAttr>(),
259 e = FD->specific_attr_end<OwnershipAttr>();
260 i != e; ++i) {
261 switch ((*i)->getOwnKind()) {
262 case OwnershipAttr::Returns: {
263 MallocMemReturnsAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000264 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000265 }
266 case OwnershipAttr::Takes:
267 case OwnershipAttr::Holds: {
268 FreeMemAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000269 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000270 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000271 }
272 }
273 }
Anna Zaks91c2a112012-02-08 23:16:56 +0000274
Anna Zaks15d0ae12012-02-11 23:46:36 +0000275 // Check use after free, when a freed pointer is passed to a call.
276 ProgramStateRef State = C.getState();
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)
283 continue;
284 if (checkUseAfterFree(Sym, C, A))
285 return;
286 }
287 }
288
289 // The pointer might escape through a function call.
290 // TODO: This should be rewritten to take into account inlining.
Anna Zaks91c2a112012-02-08 23:16:56 +0000291 if (Filter.CMallocPessimistic) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000292 SourceLocation FLoc = FD->getLocation();
293 // We assume that the pointers cannot escape through calls to system
294 // functions.
295 if (C.getSourceManager().isInSystemHeader(FLoc))
296 return;
297
Anna Zaks91c2a112012-02-08 23:16:56 +0000298 ProgramStateRef State = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000299 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
300 E = CE->arg_end(); I != E; ++I) {
301 const Expr *A = *I;
302 if (A->getType().getTypePtr()->isAnyPointerType()) {
303 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
304 if (!Sym)
Anna Zakse9ef5622012-02-10 01:11:00 +0000305 continue;
Anna Zaks91c2a112012-02-08 23:16:56 +0000306 checkEscape(Sym, A, C);
Anna Zaks91c2a112012-02-08 23:16:56 +0000307 }
308 }
309 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000310}
311
312void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000313 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000314 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000315 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000316}
317
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000318void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
319 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000320 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000321 return;
322
Sean Huntcf807c42010-08-18 23:23:40 +0000323 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000324 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000325 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000326 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000327 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000328 return;
329 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000330 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000331 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000332 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000333}
334
Anna Zaksb319e022012-02-08 20:13:28 +0000335ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000336 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000337 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000338 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000339 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000340
Anna Zaksb319e022012-02-08 20:13:28 +0000341 // Get the return value.
342 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000343
Jordy Rose32f26562010-07-04 00:00:41 +0000344 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000345 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000346
Jordy Rose32f26562010-07-04 00:00:41 +0000347 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000348 const SymbolicRegion *R =
349 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
350 if (!R || !isa<DefinedOrUnknownSVal>(Size))
351 return 0;
352
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000353 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000354 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000355 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000356 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000357
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000358 state = state->assume(extentMatchesSize, true);
359 assert(state);
360
361 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000362 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000363
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000364 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000365 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000366}
367
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000368void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000369 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000370
371 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000372 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000373}
374
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000375void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000376 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000377 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000378 return;
379
Sean Huntcf807c42010-08-18 23:23:40 +0000380 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
381 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000382 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000383 FreeMemAux(C, CE, C.getState(), *I,
384 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000385 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000386 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000387 }
388}
389
Ted Kremenek8bef8232012-01-26 21:29:00 +0000390ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000391 const CallExpr *CE,
392 ProgramStateRef state,
393 unsigned Num,
394 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000395 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000396 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000397 if (!isa<DefinedOrUnknownSVal>(ArgVal))
398 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000399 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
400
401 // Check for null dereferences.
402 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000403 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000404
405 // FIXME: Technically using 'Assume' here can result in a path
406 // bifurcation. In such cases we need to return two states, not just one.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000407 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000408 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000409
410 // The explicit NULL case, no operation is performed.
411 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000412 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000413
414 assert(notNullState);
415
Jordy Rose43859f62010-06-07 19:32:37 +0000416 // Unknown values could easily be okay
417 // Undefined values are handled elsewhere
418 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000419 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000420
Jordy Rose43859f62010-06-07 19:32:37 +0000421 const MemRegion *R = ArgVal.getAsRegion();
422
423 // Nonlocs can't be freed, of course.
424 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
425 if (!R) {
426 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000427 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000428 }
429
430 R = R->StripCasts();
431
432 // Blocks might show up as heap data, but should not be free()d
433 if (isa<BlockDataRegion>(R)) {
434 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000435 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000436 }
437
438 const MemSpaceRegion *MS = R->getMemorySpace();
439
440 // Parameters, locals, statics, and globals shouldn't be freed.
441 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
442 // FIXME: at the time this code was written, malloc() regions were
443 // represented by conjured symbols, which are all in UnknownSpaceRegion.
444 // This means that there isn't actually anything from HeapSpaceRegion
445 // that should be freed, even though we allow it here.
446 // Of course, free() can work on memory allocated outside the current
447 // function, so UnknownSpaceRegion is always a possibility.
448 // False negatives are better than false positives.
449
450 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000451 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000452 }
453
454 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
455 // Various cases could lead to non-symbol values here.
456 // For now, ignore them.
457 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000458 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000459
460 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000461 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000462
463 // If the symbol has not been tracked, return. This is possible when free() is
464 // called on a pointer that does not get its pointee directly from malloc().
465 // Full support of this requires inter-procedural analysis.
466 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000467 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000468
469 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000470 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000471 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000472 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000473 BT_DoubleFree.reset(
474 new BuiltinBug("Double free",
475 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000476 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000477 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000478 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000479 C.EmitReport(R);
480 }
Anna Zaksb319e022012-02-08 20:13:28 +0000481 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000482 }
483
484 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000485 if (Hold)
486 return notNullState->set<RegionState>(Sym, RefState::getRelinquished(CE));
487 return notNullState->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000488}
489
Ted Kremenek9c378f72011-08-12 23:37:29 +0000490bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000491 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
492 os << "an integer (" << IntVal->getValue() << ")";
493 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
494 os << "a constant address (" << ConstAddr->getValue() << ")";
495 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000496 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000497 else
498 return false;
499
500 return true;
501}
502
Ted Kremenek9c378f72011-08-12 23:37:29 +0000503bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000504 const MemRegion *MR) {
505 switch (MR->getKind()) {
506 case MemRegion::FunctionTextRegionKind: {
507 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
508 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000509 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000510 else
511 os << "the address of a function";
512 return true;
513 }
514 case MemRegion::BlockTextRegionKind:
515 os << "block text";
516 return true;
517 case MemRegion::BlockDataRegionKind:
518 // FIXME: where the block came from?
519 os << "a block";
520 return true;
521 default: {
522 const MemSpaceRegion *MS = MR->getMemorySpace();
523
Anna Zakseb31a762012-01-04 23:54:01 +0000524 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000525 const VarRegion *VR = dyn_cast<VarRegion>(MR);
526 const VarDecl *VD;
527 if (VR)
528 VD = VR->getDecl();
529 else
530 VD = NULL;
531
532 if (VD)
533 os << "the address of the local variable '" << VD->getName() << "'";
534 else
535 os << "the address of a local stack variable";
536 return true;
537 }
Anna Zakseb31a762012-01-04 23:54:01 +0000538
539 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000540 const VarRegion *VR = dyn_cast<VarRegion>(MR);
541 const VarDecl *VD;
542 if (VR)
543 VD = VR->getDecl();
544 else
545 VD = NULL;
546
547 if (VD)
548 os << "the address of the parameter '" << VD->getName() << "'";
549 else
550 os << "the address of a parameter";
551 return true;
552 }
Anna Zakseb31a762012-01-04 23:54:01 +0000553
554 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000555 const VarRegion *VR = dyn_cast<VarRegion>(MR);
556 const VarDecl *VD;
557 if (VR)
558 VD = VR->getDecl();
559 else
560 VD = NULL;
561
562 if (VD) {
563 if (VD->isStaticLocal())
564 os << "the address of the static variable '" << VD->getName() << "'";
565 else
566 os << "the address of the global variable '" << VD->getName() << "'";
567 } else
568 os << "the address of a global variable";
569 return true;
570 }
Anna Zakseb31a762012-01-04 23:54:01 +0000571
572 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000573 }
574 }
575}
576
577void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000578 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000579 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000580 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000581 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000582
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000583 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000584 llvm::raw_svector_ostream os(buf);
585
586 const MemRegion *MR = ArgVal.getAsRegion();
587 if (MR) {
588 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
589 MR = ER->getSuperRegion();
590
591 // Special case for alloca()
592 if (isa<AllocaRegion>(MR))
593 os << "Argument to free() was allocated by alloca(), not malloc()";
594 else {
595 os << "Argument to free() is ";
596 if (SummarizeRegion(os, MR))
597 os << ", which is not memory allocated by malloc()";
598 else
599 os << "not memory allocated by malloc()";
600 }
601 } else {
602 os << "Argument to free() is ";
603 if (SummarizeValue(os, ArgVal))
604 os << ", which is not memory allocated by malloc()";
605 else
606 os << "not memory allocated by malloc()";
607 }
608
Anna Zakse172e8b2011-08-17 23:00:25 +0000609 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000610 R->addRange(range);
611 C.EmitReport(R);
612 }
613}
614
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000615void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000616 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000617 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000618 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000619 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
620 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
621 return;
622 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000623
Ted Kremenek846eabd2010-12-01 21:28:31 +0000624 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000625
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000626 DefinedOrUnknownSVal PtrEQ =
627 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000628
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000629 // Get the size argument. If there is no size arg then give up.
630 const Expr *Arg1 = CE->getArg(1);
631 if (!Arg1)
632 return;
633
634 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000635 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
636 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
637 return;
638 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000639
640 // Compare the size argument to 0.
641 DefinedOrUnknownSVal SizeZero =
642 svalBuilder.evalEQ(state, Arg1Val,
643 svalBuilder.makeIntValWithPtrWidth(0, false));
644
645 // If the ptr is NULL and the size is not 0, the call is equivalent to
646 // malloc(size).
Ted Kremenek8bef8232012-01-26 21:29:00 +0000647 ProgramStateRef stateEqual = state->assume(PtrEQ, true);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000648 if (stateEqual && state->assume(SizeZero, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000649 // Hack: set the NULL symbolic region to released to suppress false warning.
650 // In the future we should add more states for allocated regions, e.g.,
651 // CheckedNull, CheckedNonNull.
652
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000653 SymbolRef Sym = arg0Val.getAsLocSymbol();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000654 if (Sym)
655 stateEqual = stateEqual->set<RegionState>(Sym, RefState::getReleased(CE));
656
Ted Kremenek8bef8232012-01-26 21:29:00 +0000657 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000658 UndefinedVal(), stateEqual);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000659 C.addTransition(stateMalloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000660 }
661
Ted Kremenek8bef8232012-01-26 21:29:00 +0000662 if (ProgramStateRef stateNotEqual = state->assume(PtrEQ, false)) {
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000663 // If the size is 0, free the memory.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000664 if (ProgramStateRef stateSizeZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000665 stateNotEqual->assume(SizeZero, true))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000666 if (ProgramStateRef stateFree =
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000667 FreeMemAux(C, CE, stateSizeZero, 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000668
Zhongxing Xud56763f2011-09-01 04:53:59 +0000669 // Bind the return value to NULL because it is now free.
Ted Kremenek5eca4822012-01-06 22:09:28 +0000670 C.addTransition(stateFree->BindExpr(CE, LCtx,
671 svalBuilder.makeNull(), true));
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000672 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000673 if (ProgramStateRef stateSizeNotZero =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000674 stateNotEqual->assume(SizeZero,false))
Ted Kremenek8bef8232012-01-26 21:29:00 +0000675 if (ProgramStateRef stateFree = FreeMemAux(C, CE, stateSizeNotZero,
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000676 0, false)) {
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000677 // FIXME: We should copy the content of the original buffer.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000678 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000679 UnknownVal(), stateFree);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000680 C.addTransition(stateRealloc);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000681 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000682 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000683}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000684
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000685void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000686 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000687 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000688 const LocationContext *LCtx = C.getLocationContext();
689 SVal count = state->getSVal(CE->getArg(0), LCtx);
690 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000691 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
692 svalBuilder.getContext().getSizeType());
693 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000694
Anna Zaks0bd6b112011-10-26 21:06:34 +0000695 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000696}
697
Anna Zaksda046772012-02-11 21:02:40 +0000698void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
699 CheckerContext &C) const {
700 assert(N);
701 if (!BT_Leak) {
702 BT_Leak.reset(new BuiltinBug("Memory leak",
703 "Allocated memory never released. Potential memory leak."));
704 // Leaks should not be reported if they are post-dominated by a sink:
705 // (1) Sinks are higher importance bugs.
706 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
707 // with __noreturn functions such as assert() or exit(). We choose not
708 // to report leaks on such paths.
709 BT_Leak->setSuppressOnSink(true);
710 }
711
712 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
713 R->addVisitor(new MallocBugVisitor(Sym));
714 C.EmitReport(R);
715}
716
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000717void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
718 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000719{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000720 if (!SymReaper.hasDeadSymbols())
721 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000722
Ted Kremenek8bef8232012-01-26 21:29:00 +0000723 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000724 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000725 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000726
Ted Kremenek217470e2011-07-28 23:07:51 +0000727 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000728 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000729 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
730 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000731 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000732 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000733 Errors.push_back(I->first);
734 }
Jordy Rose90760142010-08-18 04:33:47 +0000735 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000736 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000737
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000738 }
739 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000740
Anna Zaks0bd6b112011-10-26 21:06:34 +0000741 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000742
Ted Kremenek217470e2011-07-28 23:07:51 +0000743 if (N && generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000744 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000745 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
746 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000747 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000748 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000749}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000750
Anna Zaksda046772012-02-11 21:02:40 +0000751void MallocChecker::checkEndPath(CheckerContext &C) const {
752 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000753 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000754
Jordy Rose09cef092010-08-18 04:26:59 +0000755 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000756 RefState RS = I->second;
757 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000758 ExplodedNode *N = C.addTransition(state);
759 if (N)
760 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000761 }
762 }
763}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000764
Anna Zaks91c2a112012-02-08 23:16:56 +0000765bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
766 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000767 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000768 const RefState *RS = state->get<RegionState>(Sym);
769 if (!RS)
770 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000771
Anna Zaks91c2a112012-02-08 23:16:56 +0000772 if (RS->isAllocated()) {
773 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
774 C.addTransition(state);
775 return true;
776 }
777 return false;
778}
779
780void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
781 const Expr *E = S->getRetValue();
782 if (!E)
783 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000784
785 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000786 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000787 if (!Sym)
788 return;
789
Anna Zaks0860cd02012-02-11 21:44:39 +0000790 // Check if we are returning freed memory.
Anna Zaks15d0ae12012-02-11 23:46:36 +0000791 if (checkUseAfterFree(Sym, C, S))
792 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000793
794 // Check if the symbol is escaping.
Anna Zaks91c2a112012-02-08 23:16:56 +0000795 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000796}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000797
Anna Zaks91c2a112012-02-08 23:16:56 +0000798bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
799 const Stmt *S) const {
800 assert(Sym);
801 const RefState *RS = C.getState()->get<RegionState>(Sym);
802 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000803 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000804 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000805 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000806 "after it is freed."));
807
808 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
809 if (S)
810 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000811 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000812 C.EmitReport(R);
813 return true;
814 }
815 }
816 return false;
817}
818
Zhongxing Xuc8023782010-03-10 04:58:55 +0000819// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000820void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
821 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000822 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000823 if (Sym)
824 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000825}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000826
Anna Zaks4fb54872012-02-11 21:02:35 +0000827//===----------------------------------------------------------------------===//
828// Check various ways a symbol can be invalidated.
829// TODO: This logic (the next 3 functions) is copied/similar to the
830// RetainRelease checker. We might want to factor this out.
831//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000832
Anna Zaks4fb54872012-02-11 21:02:35 +0000833// Stop tracking symbols when a value escapes as a result of checkBind.
834// A value escapes in three possible cases:
835// (1) we are binding to something that is not a memory region.
836// (2) we are binding to a memregion that does not have stack storage
837// (3) we are binding to a memregion with stack storage that the store
838// does not understand.
839void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
840 CheckerContext &C) const {
841 // Are we storing to something that causes the value to "escape"?
842 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000843 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000844
Anna Zaks4fb54872012-02-11 21:02:35 +0000845 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
846 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000847
Anna Zaks4fb54872012-02-11 21:02:35 +0000848 if (!escapes) {
849 // To test (3), generate a new state with the binding added. If it is
850 // the same state, then it escapes (since the store cannot represent
851 // the binding).
852 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000853 }
854 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000855
856 // If our store can represent the binding and we aren't storing to something
857 // that doesn't have local storage then just return and have the simulation
858 // state continue as is.
859 if (!escapes)
860 return;
861
862 // Otherwise, find all symbols referenced by 'val' that we are tracking
863 // and stop tracking them.
864 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
865 C.addTransition(state);
866}
867
868// If a symbolic region is assumed to NULL (or another constant), stop tracking
869// it - assuming that allocation failed on this path.
870ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
871 SVal Cond,
872 bool Assumption) const {
873 RegionStateTy RS = state->get<RegionState>();
874
875 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
876 // If the symbol is assumed to NULL or another constant, this will
877 // return an APSInt*.
878 if (state->getSymVal(I.getKey()))
879 state = state->remove<RegionState>(I.getKey());
880 }
881
882 return state;
883}
884
885// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
886// escapes, when we are tracking p), do not track the symbol as we cannot reason
887// about it anymore.
888ProgramStateRef
889MallocChecker::checkRegionChanges(ProgramStateRef state,
890 const StoreManager::InvalidatedSymbols *invalidated,
891 ArrayRef<const MemRegion *> ExplicitRegions,
892 ArrayRef<const MemRegion *> Regions) const {
893 if (!invalidated)
894 return state;
895
896 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
897 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
898 E = ExplicitRegions.end(); I != E; ++I) {
899 if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
900 WhitelistedSymbols.insert(SR->getSymbol());
901 }
902
903 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
904 E = invalidated->end(); I!=E; ++I) {
905 SymbolRef sym = *I;
906 if (WhitelistedSymbols.count(sym))
907 continue;
908 // Don't track the symbol.
909 state = state->remove<RegionState>(sym);
910 }
911 return state;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000912}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000913
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000914PathDiagnosticPiece *
915MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
916 const ExplodedNode *PrevN,
917 BugReporterContext &BRC,
918 BugReport &BR) {
919 const RefState *RS = N->getState()->get<RegionState>(Sym);
920 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
921 if (!RS && !RSPrev)
922 return 0;
923
924 // We expect the interesting locations be StmtPoints corresponding to call
925 // expressions. We do not support indirect function calls as of now.
926 const CallExpr *CE = 0;
927 if (isa<StmtPoint>(N->getLocation()))
928 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
929 if (!CE)
930 return 0;
931 const FunctionDecl *funDecl = CE->getDirectCallee();
932 if (!funDecl)
933 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000934
935 // Find out if this is an interesting point and what is the kind.
936 const char *Msg = 0;
937 if (isAllocated(RS, RSPrev))
938 Msg = "Memory is allocated here";
939 else if (isReleased(RS, RSPrev))
940 Msg = "Memory is released here";
941 if (!Msg)
942 return 0;
943
944 // Generate the extra diagnostic.
945 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
946 N->getLocationContext());
947 return new PathDiagnosticEventPiece(Pos, Msg);
948}
949
950
Anna Zaks231361a2012-02-08 23:16:52 +0000951#define REGISTER_CHECKER(name) \
952void ento::register##name(CheckerManager &mgr) {\
953 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000954}
Anna Zaks231361a2012-02-08 23:16:52 +0000955
956REGISTER_CHECKER(MallocPessimistic)
957REGISTER_CHECKER(MallocOptimistic)