blob: d57e8a9f621adb018fe0a27bddb5730bb6395fc0 [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"
Anna Zaks66c40402012-02-14 21:55:24 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Anna Zaks15d0ae12012-02-11 23:46:36 +000024#include "clang/Basic/SourceManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000025#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000026#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000027#include "llvm/ADT/STLExtras.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000028using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000029using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000030
31namespace {
32
Zhongxing Xu7fb14642009-12-11 00:55:44 +000033class RefState {
Ted Kremenekdde201b2010-08-06 21:12:55 +000034 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
35 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000036 const Stmt *S;
37
Zhongxing Xu7fb14642009-12-11 00:55:44 +000038public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000039 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
40
Zhongxing Xub94b81a2009-12-31 06:13:07 +000041 bool isAllocated() const { return K == AllocateUnchecked; }
Chris Lattnerfae96222010-09-03 04:34:38 +000042 //bool isFailed() const { return K == AllocateFailed; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000043 bool isReleased() const { return K == Released; }
Chris Lattnerfae96222010-09-03 04:34:38 +000044 //bool isEscaped() const { return K == Escaped; }
45 //bool isRelinquished() const { return K == Relinquished; }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000046 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000047
48 bool operator==(const RefState &X) const {
49 return K == X.K && S == X.S;
50 }
51
Zhongxing Xub94b81a2009-12-31 06:13:07 +000052 static RefState getAllocateUnchecked(const Stmt *s) {
53 return RefState(AllocateUnchecked, s);
54 }
55 static RefState getAllocateFailed() {
56 return RefState(AllocateFailed, 0);
57 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000058 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
59 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000060 static RefState getRelinquished(const Stmt *s) {
61 return RefState(Relinquished, s);
62 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000063
64 void Profile(llvm::FoldingSetNodeID &ID) const {
65 ID.AddInteger(K);
66 ID.AddPointer(S);
67 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000068};
69
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 Zaks66c40402012-02-14 21:55:24 +000073 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000074 check::PostStmt<CallExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000075 check::Location,
76 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000077 eval::Assume,
78 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000079{
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000080 mutable OwningPtr<BuiltinBug> BT_DoubleFree;
81 mutable OwningPtr<BuiltinBug> BT_Leak;
82 mutable OwningPtr<BuiltinBug> BT_UseFree;
83 mutable OwningPtr<BuiltinBug> BT_UseRelinquished;
84 mutable OwningPtr<BuiltinBug> BT_BadFree;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000085 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000086
87public:
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000088 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +000089
90 /// In pessimistic mode, the checker assumes that it does not know which
91 /// functions might free the memory.
92 struct ChecksFilter {
93 DefaultBool CMallocPessimistic;
94 DefaultBool CMallocOptimistic;
95 };
96
97 ChecksFilter Filter;
98
Anna Zaks66c40402012-02-14 21:55:24 +000099 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
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,
Anna Zaks66c40402012-02-14 21:55:24 +0000114 ArrayRef<const MemRegion *> Regions,
115 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000116 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
117 return true;
118 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000119
Zhongxing Xu7b760962009-11-13 07:25:27 +0000120private:
Anna Zaks66c40402012-02-14 21:55:24 +0000121 void initIdentifierInfo(ASTContext &C) const;
122
123 /// Check if this is one of the functions which can allocate/reallocate memory
124 /// pointed to by one of its arguments.
125 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
126
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000127 static void MallocMem(CheckerContext &C, const CallExpr *CE);
128 static void MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
129 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000130 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000131 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000132 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000133 return MallocMemAux(C, CE,
134 state->getSVal(SizeEx, C.getLocationContext()),
135 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000136 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000137 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000138 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000139 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000140
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000141 void FreeMem(CheckerContext &C, const CallExpr *CE) const;
Jordy Rose2a479922010-08-12 08:54:03 +0000142 void FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000143 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000144 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
145 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000146 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000147
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000148 void ReallocMem(CheckerContext &C, const CallExpr *CE) const;
149 static void CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000150
Anna Zaks91c2a112012-02-08 23:16:56 +0000151 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
152 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
153 const Stmt *S = 0) const;
154
Anna Zaks66c40402012-02-14 21:55:24 +0000155 /// Check if the function is not known to us. So, for example, we could
156 /// conservatively assume it can free/reallocate it's pointer arguments.
157 bool hasUnknownBehavior(const FunctionDecl *FD, ProgramStateRef State) const;
158
Ted Kremenek9c378f72011-08-12 23:37:29 +0000159 static bool SummarizeValue(raw_ostream &os, SVal V);
160 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000161 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000162
Anna Zaksda046772012-02-11 21:02:40 +0000163 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
164
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000165 /// The bug visitor which allows us to print extra diagnostics along the
166 /// BugReport path. For example, showing the allocation site of the leaked
167 /// region.
168 class MallocBugVisitor : public BugReporterVisitor {
169 protected:
170 // The allocated region symbol tracked by the main analysis.
171 SymbolRef Sym;
172
173 public:
174 MallocBugVisitor(SymbolRef S) : Sym(S) {}
175 virtual ~MallocBugVisitor() {}
176
177 void Profile(llvm::FoldingSetNodeID &ID) const {
178 static int X = 0;
179 ID.AddPointer(&X);
180 ID.AddPointer(Sym);
181 }
182
183 inline bool isAllocated(const RefState *S, const RefState *SPrev) {
184 // Did not track -> allocated. Other state (released) -> allocated.
185 return ((S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
186 }
187
188 inline bool isReleased(const RefState *S, const RefState *SPrev) {
189 // Did not track -> released. Other state (allocated) -> released.
190 return ((S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
191 }
192
193 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
194 const ExplodedNode *PrevN,
195 BugReporterContext &BRC,
196 BugReport &BR);
197 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000198};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000199} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000200
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000201typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000202typedef llvm::ImmutableMap<SymbolRef, SymbolRef> SymRefToSymRefTy;
203class RegionState {};
204class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000205namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000206namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000207 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000208 struct ProgramStateTrait<RegionState>
209 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000210 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000211 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000212
213 template <>
214 struct ProgramStateTrait<ReallocPairs>
215 : public ProgramStatePartialTrait<SymRefToSymRefTy> {
216 static void *GDMIndex() { static int x; return &x; }
217 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000218}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000219}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000220
Anna Zaks4fb54872012-02-11 21:02:35 +0000221namespace {
222class StopTrackingCallback : public SymbolVisitor {
223 ProgramStateRef state;
224public:
225 StopTrackingCallback(ProgramStateRef st) : state(st) {}
226 ProgramStateRef getState() const { return state; }
227
228 bool VisitSymbol(SymbolRef sym) {
229 state = state->remove<RegionState>(sym);
230 return true;
231 }
232};
233} // end anonymous namespace
234
Anna Zaks66c40402012-02-14 21:55:24 +0000235void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000236 if (!II_malloc)
237 II_malloc = &Ctx.Idents.get("malloc");
238 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000239 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000240 if (!II_realloc)
241 II_realloc = &Ctx.Idents.get("realloc");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000242 if (!II_calloc)
243 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000244}
245
Anna Zaks66c40402012-02-14 21:55:24 +0000246bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
247 initIdentifierInfo(C);
248 IdentifierInfo *FunI = FD->getIdentifier();
249 if (!FunI)
250 return false;
251
252 // TODO: Add more here : ex: reallocf!
253 if (FunI == II_malloc || FunI == II_free ||
254 FunI == II_realloc || FunI == II_calloc)
255 return true;
256
257 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
258 FD->specific_attr_begin<OwnershipAttr>() !=
259 FD->specific_attr_end<OwnershipAttr>())
260 return true;
261
262
263 return false;
264}
265
Anna Zaksb319e022012-02-08 20:13:28 +0000266void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
267 const FunctionDecl *FD = C.getCalleeDecl(CE);
268 if (!FD)
269 return;
Anna Zaks66c40402012-02-14 21:55:24 +0000270 initIdentifierInfo(C.getASTContext());
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000271
272 if (FD->getIdentifier() == II_malloc) {
273 MallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000274 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000275 }
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000276 if (FD->getIdentifier() == II_realloc) {
277 ReallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000278 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000279 }
280
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000281 if (FD->getIdentifier() == II_calloc) {
282 CallocMem(C, CE);
Anna Zaksb319e022012-02-08 20:13:28 +0000283 return;
284 }
285
286 if (FD->getIdentifier() == II_free) {
287 FreeMem(C, CE);
288 return;
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000289 }
290
Anna Zaks91c2a112012-02-08 23:16:56 +0000291 if (Filter.CMallocOptimistic)
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000292 // Check all the attributes, if there are any.
293 // There can be multiple of these attributes.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000294 if (FD->hasAttrs()) {
Sean Huntcf807c42010-08-18 23:23:40 +0000295 for (specific_attr_iterator<OwnershipAttr>
296 i = FD->specific_attr_begin<OwnershipAttr>(),
297 e = FD->specific_attr_end<OwnershipAttr>();
298 i != e; ++i) {
299 switch ((*i)->getOwnKind()) {
300 case OwnershipAttr::Returns: {
301 MallocMemReturnsAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000302 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000303 }
304 case OwnershipAttr::Takes:
305 case OwnershipAttr::Holds: {
306 FreeMemAttr(C, CE, *i);
Anna Zaks15d0ae12012-02-11 23:46:36 +0000307 return;
Sean Huntcf807c42010-08-18 23:23:40 +0000308 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000309 }
310 }
311 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000312}
313
314void MallocChecker::MallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000315 ProgramStateRef state = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(),
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000316 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000317 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000318}
319
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000320void MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
321 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000322 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000323 return;
324
Sean Huntcf807c42010-08-18 23:23:40 +0000325 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000326 if (I != E) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000327 ProgramStateRef state =
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000328 MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000329 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000330 return;
331 }
Ted Kremenek8bef8232012-01-26 21:29:00 +0000332 ProgramStateRef state = MallocMemAux(C, CE, UnknownVal(), UndefinedVal(),
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000333 C.getState());
Anna Zaks0bd6b112011-10-26 21:06:34 +0000334 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000335}
336
Anna Zaksb319e022012-02-08 20:13:28 +0000337ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000338 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000339 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000340 ProgramStateRef state) {
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000341 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000342
Anna Zaksb319e022012-02-08 20:13:28 +0000343 // Get the return value.
344 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000345
Jordy Rose32f26562010-07-04 00:00:41 +0000346 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000347 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000348
Jordy Rose32f26562010-07-04 00:00:41 +0000349 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000350 const SymbolicRegion *R =
351 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
352 if (!R || !isa<DefinedOrUnknownSVal>(Size))
353 return 0;
354
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000355 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Jordy Rose32f26562010-07-04 00:00:41 +0000356 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000357 DefinedOrUnknownSVal extentMatchesSize =
Ted Kremenek9c149532010-12-01 21:57:22 +0000358 svalBuilder.evalEQ(state, Extent, DefinedSize);
Jordy Rose32f26562010-07-04 00:00:41 +0000359
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000360 state = state->assume(extentMatchesSize, true);
361 assert(state);
362
363 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000364 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000365
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000366 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000367 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000368}
369
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000370void MallocChecker::FreeMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000371 ProgramStateRef state = FreeMemAux(C, CE, C.getState(), 0, false);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000372
373 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000374 C.addTransition(state);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000375}
376
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000377void MallocChecker::FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000378 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000379 if (Att->getModule() != "malloc")
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000380 return;
381
Sean Huntcf807c42010-08-18 23:23:40 +0000382 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
383 I != E; ++I) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000384 ProgramStateRef state =
Ted Kremeneke3659a72012-01-04 23:48:37 +0000385 FreeMemAux(C, CE, C.getState(), *I,
386 Att->getOwnKind() == OwnershipAttr::Holds);
Sean Huntcf807c42010-08-18 23:23:40 +0000387 if (state)
Anna Zaks0bd6b112011-10-26 21:06:34 +0000388 C.addTransition(state);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000389 }
390}
391
Ted Kremenek8bef8232012-01-26 21:29:00 +0000392ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000393 const CallExpr *CE,
394 ProgramStateRef state,
395 unsigned Num,
396 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000397 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000398 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000399 if (!isa<DefinedOrUnknownSVal>(ArgVal))
400 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000401 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
402
403 // Check for null dereferences.
404 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000405 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000406
Anna Zaksb276bd92012-02-14 00:26:13 +0000407 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000408 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000409 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000410 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000411 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000412
Jordy Rose43859f62010-06-07 19:32:37 +0000413 // Unknown values could easily be okay
414 // Undefined values are handled elsewhere
415 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000416 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000417
Jordy Rose43859f62010-06-07 19:32:37 +0000418 const MemRegion *R = ArgVal.getAsRegion();
419
420 // Nonlocs can't be freed, of course.
421 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
422 if (!R) {
423 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000424 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000425 }
426
427 R = R->StripCasts();
428
429 // Blocks might show up as heap data, but should not be free()d
430 if (isa<BlockDataRegion>(R)) {
431 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000432 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000433 }
434
435 const MemSpaceRegion *MS = R->getMemorySpace();
436
437 // Parameters, locals, statics, and globals shouldn't be freed.
438 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
439 // FIXME: at the time this code was written, malloc() regions were
440 // represented by conjured symbols, which are all in UnknownSpaceRegion.
441 // This means that there isn't actually anything from HeapSpaceRegion
442 // that should be freed, even though we allow it here.
443 // Of course, free() can work on memory allocated outside the current
444 // function, so UnknownSpaceRegion is always a possibility.
445 // False negatives are better than false positives.
446
447 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000448 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000449 }
450
451 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
452 // Various cases could lead to non-symbol values here.
453 // For now, ignore them.
454 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000455 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000456
457 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000458 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000459
460 // If the symbol has not been tracked, return. This is possible when free() is
461 // called on a pointer that does not get its pointee directly from malloc().
462 // Full support of this requires inter-procedural analysis.
463 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000464 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000465
466 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000467 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000468 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000469 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000470 BT_DoubleFree.reset(
471 new BuiltinBug("Double free",
472 "Try to free a memory block that has been released"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000473 BugReport *R = new BugReport(*BT_DoubleFree,
Benjamin Kramerd02e2322009-11-14 12:08:24 +0000474 BT_DoubleFree->getDescription(), N);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000475 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000476 C.EmitReport(R);
477 }
Anna Zaksb319e022012-02-08 20:13:28 +0000478 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000479 }
480
481 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000482 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000483 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
484 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000485}
486
Ted Kremenek9c378f72011-08-12 23:37:29 +0000487bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000488 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
489 os << "an integer (" << IntVal->getValue() << ")";
490 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
491 os << "a constant address (" << ConstAddr->getValue() << ")";
492 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000493 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000494 else
495 return false;
496
497 return true;
498}
499
Ted Kremenek9c378f72011-08-12 23:37:29 +0000500bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000501 const MemRegion *MR) {
502 switch (MR->getKind()) {
503 case MemRegion::FunctionTextRegionKind: {
504 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
505 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000506 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000507 else
508 os << "the address of a function";
509 return true;
510 }
511 case MemRegion::BlockTextRegionKind:
512 os << "block text";
513 return true;
514 case MemRegion::BlockDataRegionKind:
515 // FIXME: where the block came from?
516 os << "a block";
517 return true;
518 default: {
519 const MemSpaceRegion *MS = MR->getMemorySpace();
520
Anna Zakseb31a762012-01-04 23:54:01 +0000521 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000522 const VarRegion *VR = dyn_cast<VarRegion>(MR);
523 const VarDecl *VD;
524 if (VR)
525 VD = VR->getDecl();
526 else
527 VD = NULL;
528
529 if (VD)
530 os << "the address of the local variable '" << VD->getName() << "'";
531 else
532 os << "the address of a local stack variable";
533 return true;
534 }
Anna Zakseb31a762012-01-04 23:54:01 +0000535
536 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000537 const VarRegion *VR = dyn_cast<VarRegion>(MR);
538 const VarDecl *VD;
539 if (VR)
540 VD = VR->getDecl();
541 else
542 VD = NULL;
543
544 if (VD)
545 os << "the address of the parameter '" << VD->getName() << "'";
546 else
547 os << "the address of a parameter";
548 return true;
549 }
Anna Zakseb31a762012-01-04 23:54:01 +0000550
551 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000552 const VarRegion *VR = dyn_cast<VarRegion>(MR);
553 const VarDecl *VD;
554 if (VR)
555 VD = VR->getDecl();
556 else
557 VD = NULL;
558
559 if (VD) {
560 if (VD->isStaticLocal())
561 os << "the address of the static variable '" << VD->getName() << "'";
562 else
563 os << "the address of the global variable '" << VD->getName() << "'";
564 } else
565 os << "the address of a global variable";
566 return true;
567 }
Anna Zakseb31a762012-01-04 23:54:01 +0000568
569 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000570 }
571 }
572}
573
574void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000575 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000576 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000577 if (!BT_BadFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000578 BT_BadFree.reset(new BuiltinBug("Bad free"));
Jordy Rose43859f62010-06-07 19:32:37 +0000579
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000580 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000581 llvm::raw_svector_ostream os(buf);
582
583 const MemRegion *MR = ArgVal.getAsRegion();
584 if (MR) {
585 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
586 MR = ER->getSuperRegion();
587
588 // Special case for alloca()
589 if (isa<AllocaRegion>(MR))
590 os << "Argument to free() was allocated by alloca(), not malloc()";
591 else {
592 os << "Argument to free() is ";
593 if (SummarizeRegion(os, MR))
594 os << ", which is not memory allocated by malloc()";
595 else
596 os << "not memory allocated by malloc()";
597 }
598 } else {
599 os << "Argument to free() is ";
600 if (SummarizeValue(os, ArgVal))
601 os << ", which is not memory allocated by malloc()";
602 else
603 os << "not memory allocated by malloc()";
604 }
605
Anna Zakse172e8b2011-08-17 23:00:25 +0000606 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Jordy Rose43859f62010-06-07 19:32:37 +0000607 R->addRange(range);
608 C.EmitReport(R);
609 }
610}
611
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000612void MallocChecker::ReallocMem(CheckerContext &C, const CallExpr *CE) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000613 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000614 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000615 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000616 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
617 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
618 return;
619 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000620
Ted Kremenek846eabd2010-12-01 21:28:31 +0000621 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000622
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000623 DefinedOrUnknownSVal PtrEQ =
624 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000625
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000626 // Get the size argument. If there is no size arg then give up.
627 const Expr *Arg1 = CE->getArg(1);
628 if (!Arg1)
629 return;
630
631 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000632 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
633 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
634 return;
635 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000636
637 // Compare the size argument to 0.
638 DefinedOrUnknownSVal SizeZero =
639 svalBuilder.evalEQ(state, Arg1Val,
640 svalBuilder.makeIntValWithPtrWidth(0, false));
641
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000642 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
643 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
644 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
645 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
646 // We only assume exceptional states if they are definitely true; if the
647 // state is under-constrained, assume regular realloc behavior.
648 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
649 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
650
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000651 // If the ptr is NULL and the size is not 0, the call is equivalent to
652 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000653 if ( PrtIsNull && !SizeIsZero) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000654 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000655 UndefinedVal(), StatePtrIsNull);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000656 C.addTransition(stateMalloc);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000657 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000658 }
659
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000660 if (PrtIsNull && SizeIsZero)
661 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000662
Anna Zaks30838b92012-02-13 20:57:07 +0000663 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000664 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000665 SymbolRef FromPtr = arg0Val.getAsSymbol();
666 SVal RetVal = state->getSVal(CE, LCtx);
667 SymbolRef ToPtr = RetVal.getAsSymbol();
668 if (!FromPtr || !ToPtr)
669 return;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000670
671 // If the size is 0, free the memory.
672 if (SizeIsZero)
673 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000674 // The semantics of the return value are:
675 // If size was equal to 0, either NULL or a pointer suitable to be passed
676 // to free() is returned.
Anna Zaks30838b92012-02-13 20:57:07 +0000677 stateFree = stateFree->set<ReallocPairs>(ToPtr, FromPtr);
Anna Zaksb276bd92012-02-14 00:26:13 +0000678 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks30838b92012-02-13 20:57:07 +0000679 C.addTransition(stateFree);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000680 return;
681 }
682
683 // Default behavior.
684 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
685 // FIXME: We should copy the content of the original buffer.
686 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
687 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000688 if (!stateRealloc)
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000689 return;
690 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr, FromPtr);
Anna Zaksb276bd92012-02-14 00:26:13 +0000691 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000692 C.addTransition(stateRealloc);
693 return;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000694 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000695}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000696
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000697void MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000698 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000699 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000700 const LocationContext *LCtx = C.getLocationContext();
701 SVal count = state->getSVal(CE->getArg(0), LCtx);
702 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000703 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
704 svalBuilder.getContext().getSizeType());
705 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000706
Anna Zaks0bd6b112011-10-26 21:06:34 +0000707 C.addTransition(MallocMemAux(C, CE, TotalSize, zeroVal, state));
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000708}
709
Anna Zaksda046772012-02-11 21:02:40 +0000710void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
711 CheckerContext &C) const {
712 assert(N);
713 if (!BT_Leak) {
714 BT_Leak.reset(new BuiltinBug("Memory leak",
715 "Allocated memory never released. Potential memory leak."));
716 // Leaks should not be reported if they are post-dominated by a sink:
717 // (1) Sinks are higher importance bugs.
718 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
719 // with __noreturn functions such as assert() or exit(). We choose not
720 // to report leaks on such paths.
721 BT_Leak->setSuppressOnSink(true);
722 }
723
724 BugReport *R = new BugReport(*BT_Leak, BT_Leak->getDescription(), N);
725 R->addVisitor(new MallocBugVisitor(Sym));
726 C.EmitReport(R);
727}
728
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000729void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
730 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000731{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000732 if (!SymReaper.hasDeadSymbols())
733 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000734
Ted Kremenek8bef8232012-01-26 21:29:00 +0000735 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000736 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000737 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000738
Ted Kremenek217470e2011-07-28 23:07:51 +0000739 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000740 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000741 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
742 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000743 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000744 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000745 Errors.push_back(I->first);
746 }
Jordy Rose90760142010-08-18 04:33:47 +0000747 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000748 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000749
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000750 }
751 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000752
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000753 // Cleanup the Realloc Pairs Map.
754 SymRefToSymRefTy RP = state->get<ReallocPairs>();
755 for (SymRefToSymRefTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
756 if (SymReaper.isDead(I->first) || SymReaper.isDead(I->second)) {
757 state = state->remove<ReallocPairs>(I->first);
758 }
759 }
760
Anna Zaks0bd6b112011-10-26 21:06:34 +0000761 ExplodedNode *N = C.addTransition(state->set<RegionState>(RS));
Ted Kremenek217470e2011-07-28 23:07:51 +0000762
Ted Kremenek217470e2011-07-28 23:07:51 +0000763 if (N && generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000764 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000765 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
766 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000767 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000768 }
Zhongxing Xu7b760962009-11-13 07:25:27 +0000769}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000770
Anna Zaksda046772012-02-11 21:02:40 +0000771void MallocChecker::checkEndPath(CheckerContext &C) const {
772 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000773 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000774
Jordy Rose09cef092010-08-18 04:26:59 +0000775 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000776 RefState RS = I->second;
777 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000778 ExplodedNode *N = C.addTransition(state);
779 if (N)
780 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000781 }
782 }
783}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000784
Anna Zaks91c2a112012-02-08 23:16:56 +0000785bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
786 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000787 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000788 const RefState *RS = state->get<RegionState>(Sym);
789 if (!RS)
790 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000791
Anna Zaks91c2a112012-02-08 23:16:56 +0000792 if (RS->isAllocated()) {
793 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
794 C.addTransition(state);
795 return true;
796 }
797 return false;
798}
799
Anna Zaks66c40402012-02-14 21:55:24 +0000800void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
801 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
802 return;
803
804 // Check use after free, when a freed pointer is passed to a call.
805 ProgramStateRef State = C.getState();
806 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
807 E = CE->arg_end(); I != E; ++I) {
808 const Expr *A = *I;
809 if (A->getType().getTypePtr()->isAnyPointerType()) {
810 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
811 if (!Sym)
812 continue;
813 if (checkUseAfterFree(Sym, C, A))
814 return;
815 }
816 }
817}
818
Anna Zaks91c2a112012-02-08 23:16:56 +0000819void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
820 const Expr *E = S->getRetValue();
821 if (!E)
822 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000823
824 // Check if we are returning a symbol.
Anna Zaks91c2a112012-02-08 23:16:56 +0000825 SymbolRef Sym = C.getState()->getSVal(E, C.getLocationContext()).getAsSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000826 if (!Sym)
827 return;
828
Anna Zaks0860cd02012-02-11 21:44:39 +0000829 // Check if we are returning freed memory.
Anna Zaks15d0ae12012-02-11 23:46:36 +0000830 if (checkUseAfterFree(Sym, C, S))
831 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000832
833 // Check if the symbol is escaping.
Anna Zaks91c2a112012-02-08 23:16:56 +0000834 checkEscape(Sym, S, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000835}
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000836
Anna Zaks91c2a112012-02-08 23:16:56 +0000837bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
838 const Stmt *S) const {
839 assert(Sym);
840 const RefState *RS = C.getState()->get<RegionState>(Sym);
841 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +0000842 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +0000843 if (!BT_UseFree)
Anna Zakse9ef5622012-02-10 01:11:00 +0000844 BT_UseFree.reset(new BuiltinBug("Use of dynamically allocated memory "
Anna Zaks91c2a112012-02-08 23:16:56 +0000845 "after it is freed."));
846
847 BugReport *R = new BugReport(*BT_UseFree, BT_UseFree->getDescription(),N);
848 if (S)
849 R->addRange(S->getSourceRange());
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000850 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +0000851 C.EmitReport(R);
852 return true;
853 }
854 }
855 return false;
856}
857
Zhongxing Xuc8023782010-03-10 04:58:55 +0000858// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +0000859void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
860 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +0000861 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +0000862 if (Sym)
863 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +0000864}
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000865
Anna Zaks4fb54872012-02-11 21:02:35 +0000866//===----------------------------------------------------------------------===//
867// Check various ways a symbol can be invalidated.
868// TODO: This logic (the next 3 functions) is copied/similar to the
869// RetainRelease checker. We might want to factor this out.
870//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000871
Anna Zaks4fb54872012-02-11 21:02:35 +0000872// Stop tracking symbols when a value escapes as a result of checkBind.
873// A value escapes in three possible cases:
874// (1) we are binding to something that is not a memory region.
875// (2) we are binding to a memregion that does not have stack storage
876// (3) we are binding to a memregion with stack storage that the store
877// does not understand.
878void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
879 CheckerContext &C) const {
880 // Are we storing to something that causes the value to "escape"?
881 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000882 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000883
Anna Zaks4fb54872012-02-11 21:02:35 +0000884 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
885 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000886
Anna Zaks4fb54872012-02-11 21:02:35 +0000887 if (!escapes) {
888 // To test (3), generate a new state with the binding added. If it is
889 // the same state, then it escapes (since the store cannot represent
890 // the binding).
891 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000892 }
893 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000894
895 // If our store can represent the binding and we aren't storing to something
896 // that doesn't have local storage then just return and have the simulation
897 // state continue as is.
898 if (!escapes)
899 return;
900
901 // Otherwise, find all symbols referenced by 'val' that we are tracking
902 // and stop tracking them.
903 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
904 C.addTransition(state);
905}
906
907// If a symbolic region is assumed to NULL (or another constant), stop tracking
908// it - assuming that allocation failed on this path.
909ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
910 SVal Cond,
911 bool Assumption) const {
912 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +0000913 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
914 // If the symbol is assumed to NULL or another constant, this will
915 // return an APSInt*.
916 if (state->getSymVal(I.getKey()))
917 state = state->remove<RegionState>(I.getKey());
918 }
919
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000920 // Realloc returns 0 when reallocation fails, which means that we should
921 // restore the state of the pointer being reallocated.
922 SymRefToSymRefTy RP = state->get<ReallocPairs>();
923 for (SymRefToSymRefTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
924 // If the symbol is assumed to NULL or another constant, this will
925 // return an APSInt*.
926 if (state->getSymVal(I.getKey())) {
927 const RefState *RS = state->get<RegionState>(I.getData());
928 if (RS) {
929 if (RS->isReleased())
930 state = state->set<RegionState>(I.getData(),
931 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksb276bd92012-02-14 00:26:13 +0000932 else if (RS->isAllocated())
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000933 state = state->set<RegionState>(I.getData(),
934 RefState::getReleased(RS->getStmt()));
935 }
936 state = state->remove<ReallocPairs>(I.getKey());
937 }
938 }
939
Anna Zaks4fb54872012-02-11 21:02:35 +0000940 return state;
941}
942
Anna Zaks66c40402012-02-14 21:55:24 +0000943// Check if the function is not known to us. So, for example, we could
944// conservatively assume it can free/reallocate it's pointer arguments.
945// (We assume that the pointers cannot escape through calls to system
946// functions not handled by this checker.)
947bool MallocChecker::hasUnknownBehavior(const FunctionDecl *FD,
948 ProgramStateRef State) const {
949 ASTContext &ASTC = State->getStateManager().getContext();
950
951 // If it's one of the allocation functions we can reason about, we model it's
952 // behavior explicitly.
953 if (isMemFunction(FD, ASTC)) {
954 return false;
955 }
956
957 // If it's a system call, we know it does not free the memory.
958 SourceManager &SM = ASTC.getSourceManager();
959 if (SM.isInSystemHeader(FD->getLocation())) {
960 return false;
961 }
962
963 // Otherwise, assume that the function can free memory.
964 return true;
965}
966
Anna Zaks4fb54872012-02-11 21:02:35 +0000967// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
968// escapes, when we are tracking p), do not track the symbol as we cannot reason
969// about it anymore.
970ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +0000971MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +0000972 const StoreManager::InvalidatedSymbols *invalidated,
973 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000974 ArrayRef<const MemRegion *> Regions,
975 const CallOrObjCMessage *Call) const {
Anna Zaks4fb54872012-02-11 21:02:35 +0000976 if (!invalidated)
Anna Zaks66c40402012-02-14 21:55:24 +0000977 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +0000978 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +0000979
980 const FunctionDecl *FD = (Call ? dyn_cast<FunctionDecl>(Call->getDecl()) : 0);
981
982 // If it's a call which might free or reallocate memory, we assume that all
983 // regions (explicit and implicit) escaped. Otherwise, whitelist explicit
984 // pointers; we still can track them.
985 if (!(FD && hasUnknownBehavior(FD, State))) {
986 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
987 E = ExplicitRegions.end(); I != E; ++I) {
988 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
989 WhitelistedSymbols.insert(R->getSymbol());
990 }
Anna Zaks4fb54872012-02-11 21:02:35 +0000991 }
992
993 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
994 E = invalidated->end(); I!=E; ++I) {
995 SymbolRef sym = *I;
996 if (WhitelistedSymbols.count(sym))
997 continue;
Anna Zaks66c40402012-02-14 21:55:24 +0000998 // The symbol escaped.
999 if (const RefState *RS = State->get<RegionState>(sym))
1000 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001001 }
Anna Zaks66c40402012-02-14 21:55:24 +00001002 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001003}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001004
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001005PathDiagnosticPiece *
1006MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1007 const ExplodedNode *PrevN,
1008 BugReporterContext &BRC,
1009 BugReport &BR) {
1010 const RefState *RS = N->getState()->get<RegionState>(Sym);
1011 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym);
1012 if (!RS && !RSPrev)
1013 return 0;
1014
1015 // We expect the interesting locations be StmtPoints corresponding to call
1016 // expressions. We do not support indirect function calls as of now.
1017 const CallExpr *CE = 0;
1018 if (isa<StmtPoint>(N->getLocation()))
1019 CE = dyn_cast<CallExpr>(cast<StmtPoint>(N->getLocation()).getStmt());
1020 if (!CE)
1021 return 0;
1022 const FunctionDecl *funDecl = CE->getDirectCallee();
1023 if (!funDecl)
1024 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001025
1026 // Find out if this is an interesting point and what is the kind.
1027 const char *Msg = 0;
1028 if (isAllocated(RS, RSPrev))
1029 Msg = "Memory is allocated here";
1030 else if (isReleased(RS, RSPrev))
1031 Msg = "Memory is released here";
1032 if (!Msg)
1033 return 0;
1034
1035 // Generate the extra diagnostic.
1036 PathDiagnosticLocation Pos(CE, BRC.getSourceManager(),
1037 N->getLocationContext());
1038 return new PathDiagnosticEventPiece(Pos, Msg);
1039}
1040
1041
Anna Zaks231361a2012-02-08 23:16:52 +00001042#define REGISTER_CHECKER(name) \
1043void ento::register##name(CheckerManager &mgr) {\
1044 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001045}
Anna Zaks231361a2012-02-08 23:16:52 +00001046
1047REGISTER_CHECKER(MallocPessimistic)
1048REGISTER_CHECKER(MallocOptimistic)