blob: f0d1924df596c92ce327790eab1b0297568655b9 [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"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
18#include "clang/Basic/SourceManager.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070019#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000021#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000022#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000025#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
26#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000028#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000029#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000030#include "llvm/ADT/SmallString.h"
Jordan Rose615a0922012-09-22 01:24:42 +000031#include "llvm/ADT/StringExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000032#include <climits>
33
Zhongxing Xu589c0f22009-11-12 08:38:56 +000034using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000035using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000036
37namespace {
38
Anton Yartsev849c7bf2013-03-28 17:05:19 +000039// Used to check correspondence between allocators and deallocators.
40enum AllocationFamily {
41 AF_None,
42 AF_Malloc,
43 AF_CXXNew,
44 AF_CXXNewArray
45};
46
Zhongxing Xu7fb14642009-12-11 00:55:44 +000047class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000048 enum Kind { // Reference to allocated memory.
49 Allocated,
50 // Reference to released/freed memory.
51 Released,
Stephen Hines651f13c2014-04-23 16:59:28 -070052 // The responsibility for freeing resources has transferred from
Anna Zaks050cdd72012-06-20 20:57:46 +000053 // this reference. A relinquished symbol should not be freed.
Anna Zaks04130232013-04-09 00:30:28 +000054 Relinquished,
55 // We are no longer guaranteed to have observed all manipulations
56 // of this pointer/memory. For example, it could have been
57 // passed as a parameter to an opaque function.
58 Escaped
59 };
Anton Yartsev849c7bf2013-03-28 17:05:19 +000060
Zhongxing Xu243fde92009-11-17 07:54:15 +000061 const Stmt *S;
Anton Yartsev849c7bf2013-03-28 17:05:19 +000062 unsigned K : 2; // Kind enum, but stored as a bitfield.
63 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
64 // family.
Zhongxing Xu243fde92009-11-17 07:54:15 +000065
Anton Yartsev849c7bf2013-03-28 17:05:19 +000066 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks04130232013-04-09 00:30:28 +000067 : S(s), K(k), Family(family) {
68 assert(family != AF_None);
69 }
Zhongxing Xu7fb14642009-12-11 00:55:44 +000070public:
Anna Zaks050cdd72012-06-20 20:57:46 +000071 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000072 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000073 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks04130232013-04-09 00:30:28 +000074 bool isEscaped() const { return K == Escaped; }
75 AllocationFamily getAllocationFamily() const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +000076 return (AllocationFamily)Family;
77 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000078 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000079
80 bool operator==(const RefState &X) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +000081 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu243fde92009-11-17 07:54:15 +000082 }
83
Anton Yartsev849c7bf2013-03-28 17:05:19 +000084 static RefState getAllocated(unsigned family, const Stmt *s) {
85 return RefState(Allocated, s, family);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000086 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +000087 static RefState getReleased(unsigned family, const Stmt *s) {
88 return RefState(Released, s, family);
89 }
90 static RefState getRelinquished(unsigned family, const Stmt *s) {
91 return RefState(Relinquished, s, family);
Ted Kremenekdde201b2010-08-06 21:12:55 +000092 }
Anna Zaks04130232013-04-09 00:30:28 +000093 static RefState getEscaped(const RefState *RS) {
94 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
95 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000096
97 void Profile(llvm::FoldingSetNodeID &ID) const {
98 ID.AddInteger(K);
99 ID.AddPointer(S);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000100 ID.AddInteger(Family);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000101 }
Ted Kremenekc37fad62013-01-03 01:30:12 +0000102
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000103 void dump(raw_ostream &OS) const {
Stephen Hines651f13c2014-04-23 16:59:28 -0700104 switch (static_cast<Kind>(K)) {
105#define CASE(ID) case ID: OS << #ID; break;
106 CASE(Allocated)
107 CASE(Released)
108 CASE(Relinquished)
109 CASE(Escaped)
110 }
Ted Kremenekc37fad62013-01-03 01:30:12 +0000111 }
112
Stephen Hines651f13c2014-04-23 16:59:28 -0700113 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000114};
115
Anna Zaks9dc298b2012-09-12 22:57:34 +0000116enum ReallocPairKind {
117 RPToBeFreedAfterFailure,
118 // The symbol has been freed when reallocation failed.
119 RPIsFreeOnFailure,
120 // The symbol does not need to be freed after reallocation fails.
121 RPDoNotTrackAfterFailure
122};
123
Anna Zaks55dd9562012-08-24 02:28:20 +0000124/// \class ReallocPair
125/// \brief Stores information about the symbol being reallocated by a call to
126/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +0000127struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +0000128 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000129 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +0000130 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +0000131
Anna Zaks9dc298b2012-09-12 22:57:34 +0000132 ReallocPair(SymbolRef S, ReallocPairKind K) :
133 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +0000134 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +0000135 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +0000136 ID.AddPointer(ReallocatedSym);
137 }
138 bool operator==(const ReallocPair &X) const {
139 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +0000140 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +0000141 }
142};
143
Anna Zaks97bfb552013-01-08 00:25:29 +0000144typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000145
Anna Zaksb319e022012-02-08 20:13:28 +0000146class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000147 check::PointerEscape,
Anna Zaks41988f32013-03-28 23:15:29 +0000148 check::ConstPointerEscape,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000149 check::PreStmt<ReturnStmt>,
Anton Yartsev55e57a52013-04-10 22:21:41 +0000150 check::PreCall,
Anna Zaksb319e022012-02-08 20:13:28 +0000151 check::PostStmt<CallExpr>,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000152 check::PostStmt<CXXNewExpr>,
153 check::PreStmt<CXXDeleteExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000154 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000155 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000156 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000157 eval::Assume>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000158{
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000159public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000160 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Stephen Hines651f13c2014-04-23 16:59:28 -0700161 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0),
162 II_kmalloc(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000163
164 /// In pessimistic mode, the checker assumes that it does not know which
165 /// functions might free the memory.
Stephen Hines651f13c2014-04-23 16:59:28 -0700166 enum CheckKind {
167 CK_MallocPessimistic,
168 CK_MallocOptimistic,
169 CK_NewDeleteChecker,
170 CK_NewDeleteLeaksChecker,
171 CK_MismatchedDeallocatorChecker,
172 CK_NumCheckKinds
Anna Zaks231361a2012-02-08 23:16:52 +0000173 };
174
Stephen Hines651f13c2014-04-23 16:59:28 -0700175 DefaultBool ChecksEnabled[CK_NumCheckKinds];
176 CheckName CheckNames[CK_NumCheckKinds];
Anna Zaks231361a2012-02-08 23:16:52 +0000177
Anton Yartsev55e57a52013-04-10 22:21:41 +0000178 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000179 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000180 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
181 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000182 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000183 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000184 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000185 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000186 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000187 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000188 void checkLocation(SVal l, bool isLoad, const Stmt *S,
189 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000190
191 ProgramStateRef checkPointerEscape(ProgramStateRef State,
192 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000193 const CallEvent *Call,
194 PointerEscapeKind Kind) const;
Anna Zaks41988f32013-03-28 23:15:29 +0000195 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
196 const InvalidatedSymbols &Escaped,
197 const CallEvent *Call,
198 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000199
Anna Zaks93c5a242012-05-02 00:05:20 +0000200 void printState(raw_ostream &Out, ProgramStateRef State,
Stephen Hines651f13c2014-04-23 16:59:28 -0700201 const char *NL, const char *Sep) const override;
Anna Zaks93c5a242012-05-02 00:05:20 +0000202
Zhongxing Xu7b760962009-11-13 07:25:27 +0000203private:
Stephen Hines651f13c2014-04-23 16:59:28 -0700204 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
205 mutable std::unique_ptr<BugType> BT_DoubleDelete;
206 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
207 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
208 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
209 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
210 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
211 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
212 *II_valloc, *II_reallocf, *II_strndup, *II_strdup,
213 *II_kmalloc;
214 mutable Optional<uint64_t> KernelZeroFlagVal;
215
Anna Zaks66c40402012-02-14 21:55:24 +0000216 void initIdentifierInfo(ASTContext &C) const;
217
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000218 /// \brief Determine family of a deallocation expression.
Anton Yartsev648cb712013-04-04 23:46:29 +0000219 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000220
221 /// \brief Print names of allocators and deallocators.
222 ///
223 /// \returns true on success.
224 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
225 const Expr *E) const;
226
227 /// \brief Print expected name of an allocator based on the deallocator's
228 /// family derived from the DeallocExpr.
229 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
230 const Expr *DeallocExpr) const;
231 /// \brief Print expected name of a deallocator based on the allocator's
232 /// family.
233 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
234
Jordan Rose9fe09f32013-03-09 00:59:10 +0000235 ///@{
Anna Zaks66c40402012-02-14 21:55:24 +0000236 /// Check if this is one of the functions which can allocate/reallocate memory
237 /// pointed to by one of its arguments.
238 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000239 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
240 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000241 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose9fe09f32013-03-09 00:59:10 +0000242 ///@}
Stephen Hines651f13c2014-04-23 16:59:28 -0700243 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
244 const CallExpr *CE,
245 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000246 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000247 const Expr *SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000248 ProgramStateRef State,
249 AllocationFamily Family = AF_Malloc) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000250 return MallocMemAux(C, CE,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000251 State->getSVal(SizeEx, C.getLocationContext()),
252 Init, State, Family);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000253 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000254
Ted Kremenek8bef8232012-01-26 21:29:00 +0000255 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000256 SVal SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000257 ProgramStateRef State,
258 AllocationFamily Family = AF_Malloc);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000259
Stephen Hines651f13c2014-04-23 16:59:28 -0700260 // Check if this malloc() for special flags. At present that means M_ZERO or
261 // __GFP_ZERO (in which case, treat it like calloc).
262 llvm::Optional<ProgramStateRef>
263 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
264 const ProgramStateRef &State) const;
265
Anna Zaks87cb5be2012-02-22 19:24:52 +0000266 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000267 static ProgramStateRef
268 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
269 AllocationFamily Family = AF_Malloc);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000270
271 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
272 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000273 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000274 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000275 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000276 bool &ReleasedAllocated,
277 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000278 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
279 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000280 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000281 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000282 bool &ReleasedAllocated,
283 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000284
Anna Zaks87cb5be2012-02-22 19:24:52 +0000285 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
286 bool FreesMemOnFailure) const;
287 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000288
Anna Zaks14345182012-05-18 01:16:10 +0000289 ///\brief Check if the memory associated with this symbol was released.
290 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
291
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000292 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaks91c2a112012-02-08 23:16:56 +0000293
Stephen Hines651f13c2014-04-23 16:59:28 -0700294 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
295
Anna Zakse7a5c822013-05-31 23:47:32 +0000296 /// Check if the function is known free memory, or if it is
Jordan Rose9fe09f32013-03-09 00:59:10 +0000297 /// "interesting" and should be modeled explicitly.
298 ///
Anna Zaks33708592013-06-08 00:29:29 +0000299 /// \param [out] EscapingSymbol A function might not free memory in general,
300 /// but could be known to free a particular symbol. In this case, false is
Anna Zakse7a5c822013-05-31 23:47:32 +0000301 /// returned and the single escaping symbol is returned through the out
302 /// parameter.
303 ///
Jordan Rose9fe09f32013-03-09 00:59:10 +0000304 /// We assume that pointers do not escape through calls to system functions
305 /// not handled by this checker.
Anna Zaks33708592013-06-08 00:29:29 +0000306 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zakse7a5c822013-05-31 23:47:32 +0000307 ProgramStateRef State,
308 SymbolRef &EscapingSymbol) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000309
Anna Zaks41988f32013-03-28 23:15:29 +0000310 // Implementation of the checkPointerEscape callabcks.
311 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
312 const InvalidatedSymbols &Escaped,
313 const CallEvent *Call,
314 PointerEscapeKind Kind,
315 bool(*CheckRefState)(const RefState*)) const;
316
Anton Yartsev9ae7a922013-04-11 00:05:20 +0000317 ///@{
318 /// Tells if a given family/call/symbol is tracked by the current checker.
Stephen Hines651f13c2014-04-23 16:59:28 -0700319 /// Sets CheckKind to the kind of the checker responsible for this
320 /// family/call/symbol.
321 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family) const;
322 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
323 const Stmt *AllocDeallocStmt) const;
324 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const;
Anton Yartsev9ae7a922013-04-11 00:05:20 +0000325 ///@}
Ted Kremenek9c378f72011-08-12 23:37:29 +0000326 static bool SummarizeValue(raw_ostream &os, SVal V);
327 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000328 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
329 const Expr *DeallocExpr) const;
Anton Yartsev648cb712013-04-04 23:46:29 +0000330 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartseva3ae9372013-04-05 11:25:10 +0000331 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsev30845182013-09-16 17:51:25 +0000332 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000333 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
334 const Expr *DeallocExpr,
335 const Expr *AllocExpr = 0) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000336 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
337 SymbolRef Sym) const;
338 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000339 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000340
Stephen Hines651f13c2014-04-23 16:59:28 -0700341 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
342
Anna Zaksca8e36e2012-02-23 21:38:21 +0000343 /// Find the location of the allocation for Sym on the path leading to the
344 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000345 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
346 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000347
Anna Zaksda046772012-02-11 21:02:40 +0000348 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
349
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000350 /// The bug visitor which allows us to print extra diagnostics along the
351 /// BugReport path. For example, showing the allocation site of the leaked
352 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000353 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000354 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000355 enum NotificationMode {
356 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000357 ReallocationFailed
358 };
359
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000360 // The allocated region symbol tracked by the main analysis.
361 SymbolRef Sym;
362
Anna Zaks88feba02012-05-10 01:37:40 +0000363 // The mode we are in, i.e. what kind of diagnostics will be emitted.
364 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000365
Anna Zaks88feba02012-05-10 01:37:40 +0000366 // A symbol from when the primary region should have been reallocated.
367 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000368
Anna Zaks88feba02012-05-10 01:37:40 +0000369 bool IsLeak;
370
371 public:
372 MallocBugVisitor(SymbolRef S, bool isLeak = false)
373 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000374
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000375 virtual ~MallocBugVisitor() {}
376
Stephen Hines651f13c2014-04-23 16:59:28 -0700377 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000378 static int X = 0;
379 ID.AddPointer(&X);
380 ID.AddPointer(Sym);
381 }
382
Anna Zaksfe571602012-02-16 22:26:07 +0000383 inline bool isAllocated(const RefState *S, const RefState *SPrev,
384 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000385 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000386 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000387 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000388 }
389
Anna Zaksfe571602012-02-16 22:26:07 +0000390 inline bool isReleased(const RefState *S, const RefState *SPrev,
391 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000392 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000393 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000394 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
395 }
396
Anna Zaks5b7aa342012-06-22 02:04:31 +0000397 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
398 const Stmt *Stmt) {
399 // Did not track -> relinquished. Other state (allocated) -> relinquished.
400 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
401 isa<ObjCPropertyRefExpr>(Stmt)) &&
402 (S && S->isRelinquished()) &&
403 (!SPrev || !SPrev->isRelinquished()));
404 }
405
Anna Zaksfe571602012-02-16 22:26:07 +0000406 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
407 const Stmt *Stmt) {
408 // If the expression is not a call, and the state change is
409 // released -> allocated, it must be the realloc return value
410 // check. If we have to handle more cases here, it might be cleaner just
411 // to track this extra bit in the state itself.
412 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
413 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000414 }
415
416 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
417 const ExplodedNode *PrevN,
418 BugReporterContext &BRC,
Stephen Hines651f13c2014-04-23 16:59:28 -0700419 BugReport &BR) override;
Anna Zaks88feba02012-05-10 01:37:40 +0000420
421 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
422 const ExplodedNode *EndPathNode,
Stephen Hines651f13c2014-04-23 16:59:28 -0700423 BugReport &BR) override {
Anna Zaks88feba02012-05-10 01:37:40 +0000424 if (!IsLeak)
425 return 0;
426
427 PathDiagnosticLocation L =
428 PathDiagnosticLocation::createEndOfPath(EndPathNode,
429 BRC.getSourceManager());
430 // Do not add the statement itself as a range in case of leak.
431 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
432 }
433
Anna Zaks56a938f2012-03-16 23:24:20 +0000434 private:
435 class StackHintGeneratorForReallocationFailed
436 : public StackHintGeneratorForSymbol {
437 public:
438 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
439 : StackHintGeneratorForSymbol(S, M) {}
440
Stephen Hines651f13c2014-04-23 16:59:28 -0700441 std::string getMessageForArg(const Expr *ArgE,
442 unsigned ArgIndex) override {
Jordan Rose615a0922012-09-22 01:24:42 +0000443 // Printed parameters start at 1, not 0.
444 ++ArgIndex;
445
Anna Zaks56a938f2012-03-16 23:24:20 +0000446 SmallString<200> buf;
447 llvm::raw_svector_ostream os(buf);
448
Jordan Rose615a0922012-09-22 01:24:42 +0000449 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
450 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000451
452 return os.str();
453 }
454
Stephen Hines651f13c2014-04-23 16:59:28 -0700455 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksfbd58742012-03-16 23:44:28 +0000456 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000457 }
458 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000459 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000460};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000461} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000462
Jordan Rose166d5022012-11-02 01:54:06 +0000463REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
464REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000465
Anna Zaks4141e4d2012-11-13 03:18:01 +0000466// A map from the freed symbol to the symbol representing the return value of
467// the free function.
468REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
469
Anna Zaks4fb54872012-02-11 21:02:35 +0000470namespace {
471class StopTrackingCallback : public SymbolVisitor {
472 ProgramStateRef state;
473public:
474 StopTrackingCallback(ProgramStateRef st) : state(st) {}
475 ProgramStateRef getState() const { return state; }
476
Stephen Hines651f13c2014-04-23 16:59:28 -0700477 bool VisitSymbol(SymbolRef sym) override {
Anna Zaks4fb54872012-02-11 21:02:35 +0000478 state = state->remove<RegionState>(sym);
479 return true;
480 }
481};
482} // end anonymous namespace
483
Anna Zaks66c40402012-02-14 21:55:24 +0000484void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000485 if (II_malloc)
486 return;
487 II_malloc = &Ctx.Idents.get("malloc");
488 II_free = &Ctx.Idents.get("free");
489 II_realloc = &Ctx.Idents.get("realloc");
490 II_reallocf = &Ctx.Idents.get("reallocf");
491 II_calloc = &Ctx.Idents.get("calloc");
492 II_valloc = &Ctx.Idents.get("valloc");
493 II_strdup = &Ctx.Idents.get("strdup");
494 II_strndup = &Ctx.Idents.get("strndup");
Stephen Hines651f13c2014-04-23 16:59:28 -0700495 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksb319e022012-02-08 20:13:28 +0000496}
497
Anna Zaks66c40402012-02-14 21:55:24 +0000498bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000499 if (isFreeFunction(FD, C))
500 return true;
501
502 if (isAllocationFunction(FD, C))
503 return true;
504
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000505 if (isStandardNewDelete(FD, C))
506 return true;
507
Anna Zaks14345182012-05-18 01:16:10 +0000508 return false;
509}
510
511bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
512 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000513 if (!FD)
514 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000515
Jordan Rose5ef6e942012-07-10 23:13:01 +0000516 if (FD->getKind() == Decl::Function) {
517 IdentifierInfo *FunI = FD->getIdentifier();
518 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000519
Jordan Rose5ef6e942012-07-10 23:13:01 +0000520 if (FunI == II_malloc || FunI == II_realloc ||
521 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700522 FunI == II_strdup || FunI == II_strndup || FunI == II_kmalloc)
Jordan Rose5ef6e942012-07-10 23:13:01 +0000523 return true;
524 }
Anna Zaks66c40402012-02-14 21:55:24 +0000525
Stephen Hines651f13c2014-04-23 16:59:28 -0700526 if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs())
527 for (const auto *I : FD->specific_attrs<OwnershipAttr>())
528 if (I->getOwnKind() == OwnershipAttr::Returns)
Anna Zaks14345182012-05-18 01:16:10 +0000529 return true;
530 return false;
531}
532
533bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
534 if (!FD)
535 return false;
536
Jordan Rose5ef6e942012-07-10 23:13:01 +0000537 if (FD->getKind() == Decl::Function) {
538 IdentifierInfo *FunI = FD->getIdentifier();
539 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000540
Jordan Rose5ef6e942012-07-10 23:13:01 +0000541 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
542 return true;
543 }
Anna Zaks66c40402012-02-14 21:55:24 +0000544
Stephen Hines651f13c2014-04-23 16:59:28 -0700545 if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs())
546 for (const auto *I : FD->specific_attrs<OwnershipAttr>())
547 if (I->getOwnKind() == OwnershipAttr::Takes ||
548 I->getOwnKind() == OwnershipAttr::Holds)
Anna Zaks14345182012-05-18 01:16:10 +0000549 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000550 return false;
551}
552
Anton Yartsev69746282013-03-28 16:10:38 +0000553// Tells if the callee is one of the following:
554// 1) A global non-placement new/delete operator function.
555// 2) A global placement operator function with the single placement argument
556// of type std::nothrow_t.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000557bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
558 ASTContext &C) const {
559 if (!FD)
560 return false;
561
562 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
563 if (Kind != OO_New && Kind != OO_Array_New &&
564 Kind != OO_Delete && Kind != OO_Array_Delete)
565 return false;
566
Anton Yartsev69746282013-03-28 16:10:38 +0000567 // Skip all operator new/delete methods.
568 if (isa<CXXMethodDecl>(FD))
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000569 return false;
570
571 // Return true if tested operator is a standard placement nothrow operator.
572 if (FD->getNumParams() == 2) {
573 QualType T = FD->getParamDecl(1)->getType();
574 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
575 return II->getName().equals("nothrow_t");
576 }
577
578 // Skip placement operators.
579 if (FD->getNumParams() != 1 || FD->isVariadic())
580 return false;
581
582 // One of the standard new/new[]/delete/delete[] non-placement operators.
583 return true;
584}
585
Stephen Hines651f13c2014-04-23 16:59:28 -0700586llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
587 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
588 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
589 //
590 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
591 //
592 // One of the possible flags is M_ZERO, which means 'give me back an
593 // allocation which is already zeroed', like calloc.
594
595 // 2-argument kmalloc(), as used in the Linux kernel:
596 //
597 // void *kmalloc(size_t size, gfp_t flags);
598 //
599 // Has the similar flag value __GFP_ZERO.
600
601 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
602 // code could be shared.
603
604 ASTContext &Ctx = C.getASTContext();
605 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
606
607 if (!KernelZeroFlagVal.hasValue()) {
608 if (OS == llvm::Triple::FreeBSD)
609 KernelZeroFlagVal = 0x0100;
610 else if (OS == llvm::Triple::NetBSD)
611 KernelZeroFlagVal = 0x0002;
612 else if (OS == llvm::Triple::OpenBSD)
613 KernelZeroFlagVal = 0x0008;
614 else if (OS == llvm::Triple::Linux)
615 // __GFP_ZERO
616 KernelZeroFlagVal = 0x8000;
617 else
618 // FIXME: We need a more general way of getting the M_ZERO value.
619 // See also: O_CREAT in UnixAPIChecker.cpp.
620
621 // Fall back to normal malloc behavior on platforms where we don't
622 // know M_ZERO.
623 return None;
624 }
625
626 // We treat the last argument as the flags argument, and callers fall-back to
627 // normal malloc on a None return. This works for the FreeBSD kernel malloc
628 // as well as Linux kmalloc.
629 if (CE->getNumArgs() < 2)
630 return None;
631
632 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
633 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
634 if (!V.getAs<NonLoc>()) {
635 // The case where 'V' can be a location can only be due to a bad header,
636 // so in this case bail out.
637 return None;
638 }
639
640 NonLoc Flags = V.castAs<NonLoc>();
641 NonLoc ZeroFlag = C.getSValBuilder()
642 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
643 .castAs<NonLoc>();
644 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
645 Flags, ZeroFlag,
646 FlagsEx->getType());
647 if (MaskedFlagsUC.isUnknownOrUndef())
648 return None;
649 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
650
651 // Check if maskedFlags is non-zero.
652 ProgramStateRef TrueState, FalseState;
653 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
654
655 // If M_ZERO is set, treat this like calloc (initialized).
656 if (TrueState && !FalseState) {
657 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
658 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
659 }
660
661 return None;
662}
663
Anna Zaksb319e022012-02-08 20:13:28 +0000664void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000665 if (C.wasInlined)
666 return;
Stephen Hines651f13c2014-04-23 16:59:28 -0700667
Anna Zaksb319e022012-02-08 20:13:28 +0000668 const FunctionDecl *FD = C.getCalleeDecl(CE);
669 if (!FD)
670 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000671
Anna Zaks87cb5be2012-02-22 19:24:52 +0000672 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000673 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000674
675 if (FD->getKind() == Decl::Function) {
676 initIdentifierInfo(C.getASTContext());
677 IdentifierInfo *FunI = FD->getIdentifier();
678
Stephen Hines651f13c2014-04-23 16:59:28 -0700679 if (FunI == II_malloc) {
680 if (CE->getNumArgs() < 1)
681 return;
682 if (CE->getNumArgs() < 3) {
683 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
684 } else if (CE->getNumArgs() == 3) {
685 llvm::Optional<ProgramStateRef> MaybeState =
686 performKernelMalloc(CE, C, State);
687 if (MaybeState.hasValue())
688 State = MaybeState.getValue();
689 else
690 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
691 }
692 } else if (FunI == II_kmalloc) {
693 llvm::Optional<ProgramStateRef> MaybeState =
694 performKernelMalloc(CE, C, State);
695 if (MaybeState.hasValue())
696 State = MaybeState.getValue();
697 else
698 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
699 } else if (FunI == II_valloc) {
Anton Yartsev648cb712013-04-04 23:46:29 +0000700 if (CE->getNumArgs() < 1)
701 return;
702 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
703 } else if (FunI == II_realloc) {
704 State = ReallocMem(C, CE, false);
705 } else if (FunI == II_reallocf) {
706 State = ReallocMem(C, CE, true);
707 } else if (FunI == II_calloc) {
708 State = CallocMem(C, CE);
709 } else if (FunI == II_free) {
710 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
711 } else if (FunI == II_strdup) {
712 State = MallocUpdateRefState(C, CE, State);
713 } else if (FunI == II_strndup) {
714 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000715 }
Anton Yartsev648cb712013-04-04 23:46:29 +0000716 else if (isStandardNewDelete(FD, C.getASTContext())) {
717 // Process direct calls to operator new/new[]/delete/delete[] functions
718 // as distinct from new/new[]/delete/delete[] expressions that are
719 // processed by the checkPostStmt callbacks for CXXNewExpr and
720 // CXXDeleteExpr.
721 OverloadedOperatorKind K = FD->getOverloadedOperator();
722 if (K == OO_New)
723 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
724 AF_CXXNew);
725 else if (K == OO_Array_New)
726 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
727 AF_CXXNewArray);
728 else if (K == OO_Delete || K == OO_Array_Delete)
729 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
730 else
731 llvm_unreachable("not a new/delete operator");
Jordan Rose5ef6e942012-07-10 23:13:01 +0000732 }
733 }
734
Stephen Hines651f13c2014-04-23 16:59:28 -0700735 if (ChecksEnabled[CK_MallocOptimistic] ||
736 ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000737 // Check all the attributes, if there are any.
738 // There can be multiple of these attributes.
739 if (FD->hasAttrs())
Stephen Hines651f13c2014-04-23 16:59:28 -0700740 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
741 switch (I->getOwnKind()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000742 case OwnershipAttr::Returns:
Stephen Hines651f13c2014-04-23 16:59:28 -0700743 State = MallocMemReturnsAttr(C, CE, I);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000744 break;
745 case OwnershipAttr::Takes:
746 case OwnershipAttr::Holds:
Stephen Hines651f13c2014-04-23 16:59:28 -0700747 State = FreeMemAttr(C, CE, I);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000748 break;
749 }
750 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000751 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000752 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000753}
754
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000755void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
756 CheckerContext &C) const {
757
758 if (NE->getNumPlacementArgs())
759 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
760 E = NE->placement_arg_end(); I != E; ++I)
761 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
762 checkUseAfterFree(Sym, C, *I);
763
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000764 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
765 return;
766
767 ProgramStateRef State = C.getState();
768 // The return value from operator new is bound to a specified initialization
769 // value (if any) and we don't want to loose this value. So we call
770 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
771 // existing binding.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000772 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
773 : AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000774 C.addTransition(State);
775}
776
777void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
778 CheckerContext &C) const {
779
Stephen Hines651f13c2014-04-23 16:59:28 -0700780 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000781 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
782 checkUseAfterFree(Sym, C, DE->getArgument());
783
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000784 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
785 return;
786
787 ProgramStateRef State = C.getState();
788 bool ReleasedAllocated;
789 State = FreeMemAux(C, DE->getArgument(), DE, State,
790 /*Hold*/false, ReleasedAllocated);
791
792 C.addTransition(State);
793}
794
Jordan Rose9fe09f32013-03-09 00:59:10 +0000795static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
796 // If the first selector piece is one of the names below, assume that the
797 // object takes ownership of the memory, promising to eventually deallocate it
798 // with free().
799 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
800 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
801 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
802 if (FirstSlot == "dataWithBytesNoCopy" ||
803 FirstSlot == "initWithBytesNoCopy" ||
804 FirstSlot == "initWithCharactersNoCopy")
805 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000806
807 return false;
808}
809
Jordan Rose9fe09f32013-03-09 00:59:10 +0000810static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
811 Selector S = Call.getSelector();
812
813 // FIXME: We should not rely on fully-constrained symbols being folded.
814 for (unsigned i = 1; i < S.getNumArgs(); ++i)
815 if (S.getNameForSlot(i).equals("freeWhenDone"))
816 return !Call.getArgSVal(i).isZeroConstant();
817
818 return None;
819}
820
Anna Zaks4141e4d2012-11-13 03:18:01 +0000821void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
822 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000823 if (C.wasInlined)
824 return;
825
Jordan Rose9fe09f32013-03-09 00:59:10 +0000826 if (!isKnownDeallocObjCMethodName(Call))
827 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000828
Jordan Rose9fe09f32013-03-09 00:59:10 +0000829 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
830 if (!*FreeWhenDone)
831 return;
832
833 bool ReleasedAllocatedMemory;
834 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
835 Call.getOriginExpr(), C.getState(),
836 /*Hold=*/true, ReleasedAllocatedMemory,
837 /*RetNullOnFailure=*/true);
838
839 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000840}
841
Stephen Hines651f13c2014-04-23 16:59:28 -0700842ProgramStateRef
843MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
844 const OwnershipAttr *Att) const {
845 if (Att->getModule() != II_malloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000846 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000847
Sean Huntcf807c42010-08-18 23:23:40 +0000848 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000849 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000850 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000851 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000852 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000853}
854
Anna Zaksb319e022012-02-08 20:13:28 +0000855ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000856 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000857 SVal Size, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000858 ProgramStateRef State,
859 AllocationFamily Family) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000860
861 // Bind the return value to the symbolic value from the heap region.
862 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
863 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000864 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000865 SValBuilder &svalBuilder = C.getSValBuilder();
866 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000867 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
868 .castAs<DefinedSVal>();
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000869 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000870
Anna Zaksb16ce452012-02-15 00:11:22 +0000871 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000872 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000873 return 0;
874
Jordy Rose32f26562010-07-04 00:00:41 +0000875 // Fill the region with the initialization value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000876 State = State->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000877
Jordy Rose32f26562010-07-04 00:00:41 +0000878 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000879 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000880 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000881 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000882 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000883 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000884 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000885 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000886 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000887 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000888 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000889
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000890 State = State->assume(extentMatchesSize, true);
891 assert(State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000892 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000893
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000894 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000895}
896
897ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000898 const Expr *E,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000899 ProgramStateRef State,
900 AllocationFamily Family) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000901 // Get the return value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000902 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000903
904 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000905 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000906 return 0;
907
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000908 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000909 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000910
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000911 // Set the symbol's state to Allocated.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000912 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000913}
914
Anna Zaks87cb5be2012-02-22 19:24:52 +0000915ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
916 const CallExpr *CE,
Stephen Hines651f13c2014-04-23 16:59:28 -0700917 const OwnershipAttr *Att) const {
918 if (Att->getModule() != II_malloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000919 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000920
Anna Zaksb3d72752012-03-01 22:06:06 +0000921 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000922 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000923
Sean Huntcf807c42010-08-18 23:23:40 +0000924 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
925 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000926 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000927 Att->getOwnKind() == OwnershipAttr::Holds,
928 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000929 if (StateI)
930 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000931 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000932 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000933}
934
Ted Kremenek8bef8232012-01-26 21:29:00 +0000935ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000936 const CallExpr *CE,
937 ProgramStateRef state,
938 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000939 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000940 bool &ReleasedAllocated,
941 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000942 if (CE->getNumArgs() < (Num + 1))
943 return 0;
944
Anna Zaks4141e4d2012-11-13 03:18:01 +0000945 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
946 ReleasedAllocated, ReturnsNullOnFailure);
947}
948
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000949/// Checks if the previous call to free on the given symbol failed - if free
950/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000951static bool didPreviousFreeFail(ProgramStateRef State,
952 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000953 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000954 if (Ret) {
955 assert(*Ret && "We should not store the null return symbol");
956 ConstraintManager &CMgr = State->getConstraintManager();
957 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000958 RetStatusSymbol = *Ret;
959 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000960 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000961 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000962}
963
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000964AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartsev648cb712013-04-04 23:46:29 +0000965 const Stmt *S) const {
966 if (!S)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000967 return AF_None;
968
Anton Yartsev648cb712013-04-04 23:46:29 +0000969 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000970 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartsev648cb712013-04-04 23:46:29 +0000971
972 if (!FD)
973 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
974
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000975 ASTContext &Ctx = C.getASTContext();
976
Anton Yartsev648cb712013-04-04 23:46:29 +0000977 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000978 return AF_Malloc;
979
980 if (isStandardNewDelete(FD, Ctx)) {
981 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartsev648cb712013-04-04 23:46:29 +0000982 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000983 return AF_CXXNew;
Anton Yartsev648cb712013-04-04 23:46:29 +0000984 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000985 return AF_CXXNewArray;
986 }
987
988 return AF_None;
989 }
990
Anton Yartsev648cb712013-04-04 23:46:29 +0000991 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
992 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
993
994 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000995 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
996
Anton Yartsev648cb712013-04-04 23:46:29 +0000997 if (isa<ObjCMessageExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000998 return AF_Malloc;
999
1000 return AF_None;
1001}
1002
1003bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1004 const Expr *E) const {
1005 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1006 // FIXME: This doesn't handle indirect calls.
1007 const FunctionDecl *FD = CE->getDirectCallee();
1008 if (!FD)
1009 return false;
1010
1011 os << *FD;
1012 if (!FD->isOverloadedOperator())
1013 os << "()";
1014 return true;
1015 }
1016
1017 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1018 if (Msg->isInstanceMessage())
1019 os << "-";
1020 else
1021 os << "+";
Stephen Hines651f13c2014-04-23 16:59:28 -07001022 Msg->getSelector().print(os);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001023 return true;
1024 }
1025
1026 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1027 os << "'"
1028 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1029 << "'";
1030 return true;
1031 }
1032
1033 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1034 os << "'"
1035 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1036 << "'";
1037 return true;
1038 }
1039
1040 return false;
1041}
1042
1043void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1044 const Expr *E) const {
1045 AllocationFamily Family = getAllocationFamily(C, E);
1046
1047 switch(Family) {
1048 case AF_Malloc: os << "malloc()"; return;
1049 case AF_CXXNew: os << "'new'"; return;
1050 case AF_CXXNewArray: os << "'new[]'"; return;
1051 case AF_None: llvm_unreachable("not a deallocation expression");
1052 }
1053}
1054
1055void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1056 AllocationFamily Family) const {
1057 switch(Family) {
1058 case AF_Malloc: os << "free()"; return;
1059 case AF_CXXNew: os << "'delete'"; return;
1060 case AF_CXXNewArray: os << "'delete[]'"; return;
1061 case AF_None: llvm_unreachable("suspicious AF_None argument");
1062 }
1063}
1064
Anna Zaks5b7aa342012-06-22 02:04:31 +00001065ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1066 const Expr *ArgExpr,
1067 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +00001068 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +00001069 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +00001070 bool &ReleasedAllocated,
1071 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +00001072
Anna Zaks4141e4d2012-11-13 03:18:01 +00001073 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +00001074 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +00001075 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001076 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001077
1078 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +00001079 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +00001080 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001081
Anna Zaksb276bd92012-02-14 00:26:13 +00001082 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001083 ProgramStateRef notNullState, nullState;
Stephen Hines651f13c2014-04-23 16:59:28 -07001084 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001085 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +00001086 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001087
Jordy Rose43859f62010-06-07 19:32:37 +00001088 // Unknown values could easily be okay
1089 // Undefined values are handled elsewhere
1090 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +00001091 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001092
Jordy Rose43859f62010-06-07 19:32:37 +00001093 const MemRegion *R = ArgVal.getAsRegion();
1094
1095 // Nonlocs can't be freed, of course.
1096 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1097 if (!R) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001098 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +00001099 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001100 }
1101
1102 R = R->StripCasts();
1103
1104 // Blocks might show up as heap data, but should not be free()d
1105 if (isa<BlockDataRegion>(R)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001106 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +00001107 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001108 }
1109
1110 const MemSpaceRegion *MS = R->getMemorySpace();
1111
Anton Yartsevbb369952013-03-13 14:39:10 +00001112 // Parameters, locals, statics, globals, and memory returned by alloca()
1113 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +00001114 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1115 // FIXME: at the time this code was written, malloc() regions were
1116 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1117 // This means that there isn't actually anything from HeapSpaceRegion
1118 // that should be freed, even though we allow it here.
1119 // Of course, free() can work on memory allocated outside the current
1120 // function, so UnknownSpaceRegion is always a possibility.
1121 // False negatives are better than false positives.
1122
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001123 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +00001124 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001125 }
Anna Zaks118aa752013-02-07 23:05:47 +00001126
1127 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +00001128 // Various cases could lead to non-symbol values here.
1129 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +00001130 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +00001131 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001132
Anna Zaks118aa752013-02-07 23:05:47 +00001133 SymbolRef SymBase = SrBase->getSymbol();
1134 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001135 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +00001136
Anton Yartsev648cb712013-04-04 23:46:29 +00001137 if (RsBase) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001138
Anna Zaks04130232013-04-09 00:30:28 +00001139 // Check for double free first.
1140 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartsev648cb712013-04-04 23:46:29 +00001141 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1142 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1143 SymBase, PreviousRetStatusSymbol);
1144 return 0;
Anton Yartsev648cb712013-04-04 23:46:29 +00001145
Anna Zaks04130232013-04-09 00:30:28 +00001146 // If the pointer is allocated or escaped, but we are now trying to free it,
1147 // check that the call to free is proper.
1148 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1149
1150 // Check if an expected deallocation function matches the real one.
1151 bool DeallocMatchesAlloc =
1152 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1153 if (!DeallocMatchesAlloc) {
1154 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsev30845182013-09-16 17:51:25 +00001155 ParentExpr, RsBase, SymBase, Hold);
Anna Zaks04130232013-04-09 00:30:28 +00001156 return 0;
1157 }
1158
1159 // Check if the memory location being freed is the actual location
1160 // allocated, or an offset.
1161 RegionOffset Offset = R->getAsOffset();
1162 if (Offset.isValid() &&
1163 !Offset.hasSymbolicOffset() &&
1164 Offset.getOffset() != 0) {
1165 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1166 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1167 AllocExpr);
1168 return 0;
1169 }
Anton Yartsev648cb712013-04-04 23:46:29 +00001170 }
Anna Zaks118aa752013-02-07 23:05:47 +00001171 }
1172
Jordan Rose68502e52013-08-15 17:22:06 +00001173 ReleasedAllocated = (RsBase != 0) && RsBase->isAllocated();
Anna Zaks55dd9562012-08-24 02:28:20 +00001174
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001175 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +00001176 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001177
Anna Zaks4141e4d2012-11-13 03:18:01 +00001178 // Keep track of the return value. If it is NULL, we will know that free
1179 // failed.
1180 if (ReturnsNullOnFailure) {
1181 SVal RetVal = C.getSVal(ParentExpr);
1182 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1183 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +00001184 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1185 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +00001186 }
1187 }
1188
Anton Yartseva3989b82013-04-05 19:08:04 +00001189 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1190 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001191 // Normal free.
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001192 if (Hold)
Anna Zaks118aa752013-02-07 23:05:47 +00001193 return State->set<RegionState>(SymBase,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001194 RefState::getRelinquished(Family,
1195 ParentExpr));
1196
1197 return State->set<RegionState>(SymBase,
1198 RefState::getReleased(Family, ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001199}
1200
Stephen Hines651f13c2014-04-23 16:59:28 -07001201Optional<MallocChecker::CheckKind>
1202MallocChecker::getCheckIfTracked(AllocationFamily Family) const {
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001203 switch (Family) {
1204 case AF_Malloc: {
Stephen Hines651f13c2014-04-23 16:59:28 -07001205 if (ChecksEnabled[CK_MallocOptimistic]) {
1206 return CK_MallocOptimistic;
1207 } else if (ChecksEnabled[CK_MallocPessimistic]) {
1208 return CK_MallocPessimistic;
1209 }
1210 return Optional<MallocChecker::CheckKind>();
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001211 }
1212 case AF_CXXNew:
1213 case AF_CXXNewArray: {
Stephen Hines651f13c2014-04-23 16:59:28 -07001214 if (ChecksEnabled[CK_NewDeleteChecker]) {
1215 return CK_NewDeleteChecker;
1216 }
1217 return Optional<MallocChecker::CheckKind>();
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001218 }
1219 case AF_None: {
Anton Yartseva3989b82013-04-05 19:08:04 +00001220 llvm_unreachable("no family");
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001221 }
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001222 }
Anton Yartsevc8454312013-04-05 02:12:04 +00001223 llvm_unreachable("unhandled family");
Anton Yartsev648cb712013-04-04 23:46:29 +00001224}
1225
Stephen Hines651f13c2014-04-23 16:59:28 -07001226Optional<MallocChecker::CheckKind>
1227MallocChecker::getCheckIfTracked(CheckerContext &C,
1228 const Stmt *AllocDeallocStmt) const {
1229 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt));
Anton Yartsev648cb712013-04-04 23:46:29 +00001230}
1231
Stephen Hines651f13c2014-04-23 16:59:28 -07001232Optional<MallocChecker::CheckKind>
1233MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const {
Anton Yartsev648cb712013-04-04 23:46:29 +00001234
Anton Yartseva3989b82013-04-05 19:08:04 +00001235 const RefState *RS = C.getState()->get<RegionState>(Sym);
1236 assert(RS);
Stephen Hines651f13c2014-04-23 16:59:28 -07001237 return getCheckIfTracked(RS->getAllocationFamily());
Anton Yartsev648cb712013-04-04 23:46:29 +00001238}
1239
Ted Kremenek9c378f72011-08-12 23:37:29 +00001240bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001241 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001242 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001243 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001244 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001245 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +00001246 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +00001247 else
1248 return false;
1249
1250 return true;
1251}
1252
Ted Kremenek9c378f72011-08-12 23:37:29 +00001253bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +00001254 const MemRegion *MR) {
1255 switch (MR->getKind()) {
1256 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +00001257 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +00001258 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001259 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +00001260 else
1261 os << "the address of a function";
1262 return true;
1263 }
1264 case MemRegion::BlockTextRegionKind:
1265 os << "block text";
1266 return true;
1267 case MemRegion::BlockDataRegionKind:
1268 // FIXME: where the block came from?
1269 os << "a block";
1270 return true;
1271 default: {
1272 const MemSpaceRegion *MS = MR->getMemorySpace();
1273
Anna Zakseb31a762012-01-04 23:54:01 +00001274 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001275 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1276 const VarDecl *VD;
1277 if (VR)
1278 VD = VR->getDecl();
1279 else
1280 VD = NULL;
1281
1282 if (VD)
1283 os << "the address of the local variable '" << VD->getName() << "'";
1284 else
1285 os << "the address of a local stack variable";
1286 return true;
1287 }
Anna Zakseb31a762012-01-04 23:54:01 +00001288
1289 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001290 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1291 const VarDecl *VD;
1292 if (VR)
1293 VD = VR->getDecl();
1294 else
1295 VD = NULL;
1296
1297 if (VD)
1298 os << "the address of the parameter '" << VD->getName() << "'";
1299 else
1300 os << "the address of a parameter";
1301 return true;
1302 }
Anna Zakseb31a762012-01-04 23:54:01 +00001303
1304 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001305 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1306 const VarDecl *VD;
1307 if (VR)
1308 VD = VR->getDecl();
1309 else
1310 VD = NULL;
1311
1312 if (VD) {
1313 if (VD->isStaticLocal())
1314 os << "the address of the static variable '" << VD->getName() << "'";
1315 else
1316 os << "the address of the global variable '" << VD->getName() << "'";
1317 } else
1318 os << "the address of a global variable";
1319 return true;
1320 }
Anna Zakseb31a762012-01-04 23:54:01 +00001321
1322 return false;
Jordy Rose43859f62010-06-07 19:32:37 +00001323 }
1324 }
1325}
1326
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001327void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1328 SourceRange Range,
1329 const Expr *DeallocExpr) const {
1330
Stephen Hines651f13c2014-04-23 16:59:28 -07001331 if (!ChecksEnabled[CK_MallocOptimistic] &&
1332 !ChecksEnabled[CK_MallocPessimistic] &&
1333 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001334 return;
1335
Stephen Hines651f13c2014-04-23 16:59:28 -07001336 Optional<MallocChecker::CheckKind> CheckKind =
1337 getCheckIfTracked(C, DeallocExpr);
1338 if (!CheckKind.hasValue())
Anton Yartsev648cb712013-04-04 23:46:29 +00001339 return;
1340
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001341 if (ExplodedNode *N = C.generateSink()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001342 if (!BT_BadFree[*CheckKind])
1343 BT_BadFree[*CheckKind].reset(
1344 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1345
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001346 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +00001347 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001348
Jordy Rose43859f62010-06-07 19:32:37 +00001349 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001350 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1351 MR = ER->getSuperRegion();
1352
1353 if (MR && isa<AllocaRegion>(MR))
1354 os << "Memory allocated by alloca() should not be deallocated";
1355 else {
1356 os << "Argument to ";
1357 if (!printAllocDeallocName(os, C, DeallocExpr))
1358 os << "deallocator";
1359
1360 os << " is ";
1361 bool Summarized = MR ? SummarizeRegion(os, MR)
1362 : SummarizeValue(os, ArgVal);
1363 if (Summarized)
1364 os << ", which is not memory allocated by ";
Jordy Rose43859f62010-06-07 19:32:37 +00001365 else
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001366 os << "not memory allocated by ";
1367
1368 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose43859f62010-06-07 19:32:37 +00001369 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001370
Stephen Hines651f13c2014-04-23 16:59:28 -07001371 BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001372 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001373 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001374 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001375 }
1376}
1377
Anton Yartsev648cb712013-04-04 23:46:29 +00001378void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1379 SourceRange Range,
1380 const Expr *DeallocExpr,
Anton Yartseva3ae9372013-04-05 11:25:10 +00001381 const RefState *RS,
Anton Yartsev30845182013-09-16 17:51:25 +00001382 SymbolRef Sym,
1383 bool OwnershipTransferred) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001384
Stephen Hines651f13c2014-04-23 16:59:28 -07001385 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001386 return;
1387
1388 if (ExplodedNode *N = C.generateSink()) {
Anton Yartsev648cb712013-04-04 23:46:29 +00001389 if (!BT_MismatchedDealloc)
Stephen Hines651f13c2014-04-23 16:59:28 -07001390 BT_MismatchedDealloc.reset(
1391 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1392 "Bad deallocator", "Memory Error"));
1393
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001394 SmallString<100> buf;
1395 llvm::raw_svector_ostream os(buf);
1396
1397 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1398 SmallString<20> AllocBuf;
1399 llvm::raw_svector_ostream AllocOs(AllocBuf);
1400 SmallString<20> DeallocBuf;
1401 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1402
Anton Yartsev30845182013-09-16 17:51:25 +00001403 if (OwnershipTransferred) {
1404 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1405 os << DeallocOs.str() << " cannot";
1406 else
1407 os << "Cannot";
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001408
Anton Yartsev30845182013-09-16 17:51:25 +00001409 os << " take ownership of memory";
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001410
Anton Yartsev30845182013-09-16 17:51:25 +00001411 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1412 os << " allocated by " << AllocOs.str();
1413 } else {
1414 os << "Memory";
1415 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1416 os << " allocated by " << AllocOs.str();
1417
1418 os << " should be deallocated by ";
1419 printExpectedDeallocName(os, RS->getAllocationFamily());
1420
1421 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1422 os << ", not " << DeallocOs.str();
1423 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001424
Anton Yartsev648cb712013-04-04 23:46:29 +00001425 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001426 R->markInteresting(Sym);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001427 R->addRange(Range);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001428 R->addVisitor(new MallocBugVisitor(Sym));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001429 C.emitReport(R);
1430 }
1431}
1432
Anna Zaks118aa752013-02-07 23:05:47 +00001433void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001434 SourceRange Range, const Expr *DeallocExpr,
1435 const Expr *AllocExpr) const {
1436
Stephen Hines651f13c2014-04-23 16:59:28 -07001437 if (!ChecksEnabled[CK_MallocOptimistic] &&
1438 !ChecksEnabled[CK_MallocPessimistic] &&
1439 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001440 return;
1441
Stephen Hines651f13c2014-04-23 16:59:28 -07001442 Optional<MallocChecker::CheckKind> CheckKind =
1443 getCheckIfTracked(C, AllocExpr);
1444 if (!CheckKind.hasValue())
Anton Yartsev648cb712013-04-04 23:46:29 +00001445 return;
1446
Anna Zaks118aa752013-02-07 23:05:47 +00001447 ExplodedNode *N = C.generateSink();
1448 if (N == NULL)
1449 return;
1450
Stephen Hines651f13c2014-04-23 16:59:28 -07001451 if (!BT_OffsetFree[*CheckKind])
1452 BT_OffsetFree[*CheckKind].reset(
1453 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaks118aa752013-02-07 23:05:47 +00001454
1455 SmallString<100> buf;
1456 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001457 SmallString<20> AllocNameBuf;
1458 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaks118aa752013-02-07 23:05:47 +00001459
1460 const MemRegion *MR = ArgVal.getAsRegion();
1461 assert(MR && "Only MemRegion based symbols can have offset free errors");
1462
1463 RegionOffset Offset = MR->getAsOffset();
1464 assert((Offset.isValid() &&
1465 !Offset.hasSymbolicOffset() &&
1466 Offset.getOffset() != 0) &&
1467 "Only symbols with a valid offset can have offset free errors");
1468
1469 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1470
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001471 os << "Argument to ";
1472 if (!printAllocDeallocName(os, C, DeallocExpr))
1473 os << "deallocator";
1474 os << " is offset by "
Anna Zaks118aa752013-02-07 23:05:47 +00001475 << offsetBytes
1476 << " "
1477 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001478 << " from the start of ";
1479 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1480 os << "memory allocated by " << AllocNameOs.str();
1481 else
1482 os << "allocated memory";
Anna Zaks118aa752013-02-07 23:05:47 +00001483
Stephen Hines651f13c2014-04-23 16:59:28 -07001484 BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaks118aa752013-02-07 23:05:47 +00001485 R->markInteresting(MR->getBaseRegion());
1486 R->addRange(Range);
1487 C.emitReport(R);
1488}
1489
Anton Yartsevbb369952013-03-13 14:39:10 +00001490void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1491 SymbolRef Sym) const {
1492
Stephen Hines651f13c2014-04-23 16:59:28 -07001493 if (!ChecksEnabled[CK_MallocOptimistic] &&
1494 !ChecksEnabled[CK_MallocPessimistic] &&
1495 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001496 return;
1497
Stephen Hines651f13c2014-04-23 16:59:28 -07001498 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1499 if (!CheckKind.hasValue())
Anton Yartsev648cb712013-04-04 23:46:29 +00001500 return;
1501
Anton Yartsevbb369952013-03-13 14:39:10 +00001502 if (ExplodedNode *N = C.generateSink()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001503 if (!BT_UseFree[*CheckKind])
1504 BT_UseFree[*CheckKind].reset(new BugType(
1505 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsevbb369952013-03-13 14:39:10 +00001506
Stephen Hines651f13c2014-04-23 16:59:28 -07001507 BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
Anton Yartsevbb369952013-03-13 14:39:10 +00001508 "Use of memory after it is freed", N);
1509
1510 R->markInteresting(Sym);
1511 R->addRange(Range);
1512 R->addVisitor(new MallocBugVisitor(Sym));
1513 C.emitReport(R);
1514 }
1515}
1516
1517void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1518 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001519 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001520
Stephen Hines651f13c2014-04-23 16:59:28 -07001521 if (!ChecksEnabled[CK_MallocOptimistic] &&
1522 !ChecksEnabled[CK_MallocPessimistic] &&
1523 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001524 return;
1525
Stephen Hines651f13c2014-04-23 16:59:28 -07001526 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1527 if (!CheckKind.hasValue())
Anton Yartsev648cb712013-04-04 23:46:29 +00001528 return;
1529
Anton Yartsevbb369952013-03-13 14:39:10 +00001530 if (ExplodedNode *N = C.generateSink()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001531 if (!BT_DoubleFree[*CheckKind])
1532 BT_DoubleFree[*CheckKind].reset(
1533 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsevbb369952013-03-13 14:39:10 +00001534
Stephen Hines651f13c2014-04-23 16:59:28 -07001535 BugReport *R =
1536 new BugReport(*BT_DoubleFree[*CheckKind],
1537 (Released ? "Attempt to free released memory"
1538 : "Attempt to free non-owned memory"),
1539 N);
Anton Yartsevbb369952013-03-13 14:39:10 +00001540 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001541 R->markInteresting(Sym);
1542 if (PrevSym)
1543 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001544 R->addVisitor(new MallocBugVisitor(Sym));
1545 C.emitReport(R);
1546 }
1547}
1548
Stephen Hines651f13c2014-04-23 16:59:28 -07001549void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1550
1551 if (!ChecksEnabled[CK_NewDeleteChecker])
1552 return;
1553
1554 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1555 if (!CheckKind.hasValue())
1556 return;
1557 assert(*CheckKind == CK_NewDeleteChecker && "invalid check kind");
1558
1559 if (ExplodedNode *N = C.generateSink()) {
1560 if (!BT_DoubleDelete)
1561 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1562 "Double delete", "Memory Error"));
1563
1564 BugReport *R = new BugReport(*BT_DoubleDelete,
1565 "Attempt to delete released memory", N);
1566
1567 R->markInteresting(Sym);
1568 R->addVisitor(new MallocBugVisitor(Sym));
1569 C.emitReport(R);
1570 }
1571}
1572
Anna Zaks87cb5be2012-02-22 19:24:52 +00001573ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1574 const CallExpr *CE,
1575 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001576 if (CE->getNumArgs() < 2)
1577 return 0;
1578
Ted Kremenek8bef8232012-01-26 21:29:00 +00001579 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001580 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001581 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001582 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001583 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001584 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001585 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001586
Ted Kremenek846eabd2010-12-01 21:28:31 +00001587 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001588
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001589 DefinedOrUnknownSVal PtrEQ =
1590 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001591
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001592 // Get the size argument. If there is no size arg then give up.
1593 const Expr *Arg1 = CE->getArg(1);
1594 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001595 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001596
1597 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001598 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001599 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001600 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001601 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001602
1603 // Compare the size argument to 0.
1604 DefinedOrUnknownSVal SizeZero =
1605 svalBuilder.evalEQ(state, Arg1Val,
1606 svalBuilder.makeIntValWithPtrWidth(0, false));
1607
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001608 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Stephen Hines651f13c2014-04-23 16:59:28 -07001609 std::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001610 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Stephen Hines651f13c2014-04-23 16:59:28 -07001611 std::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001612 // We only assume exceptional states if they are definitely true; if the
1613 // state is under-constrained, assume regular realloc behavior.
1614 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1615 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1616
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001617 // If the ptr is NULL and the size is not 0, the call is equivalent to
1618 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001619 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001620 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001621 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001622 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001623 }
1624
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001625 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001626 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001627
Anna Zaks30838b92012-02-13 20:57:07 +00001628 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001629 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001630 SymbolRef FromPtr = arg0Val.getAsSymbol();
1631 SVal RetVal = state->getSVal(CE, LCtx);
1632 SymbolRef ToPtr = RetVal.getAsSymbol();
1633 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001634 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001635
Anna Zaks55dd9562012-08-24 02:28:20 +00001636 bool ReleasedAllocated = false;
1637
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001638 // If the size is 0, free the memory.
1639 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001640 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1641 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001642 // The semantics of the return value are:
1643 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001644 // to free() is returned. We just free the input pointer and do not add
1645 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001646 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001647 }
1648
1649 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001650 if (ProgramStateRef stateFree =
1651 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1652
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001653 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1654 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001655 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001656 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001657
Anna Zaks9dc298b2012-09-12 22:57:34 +00001658 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1659 if (FreesOnFail)
1660 Kind = RPIsFreeOnFailure;
1661 else if (!ReleasedAllocated)
1662 Kind = RPDoNotTrackAfterFailure;
1663
Anna Zaks55dd9562012-08-24 02:28:20 +00001664 // Record the info about the reallocated symbol so that we could properly
1665 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001666 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001667 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001668 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001669 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001670 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001671 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001672 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001673}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001674
Anna Zaks87cb5be2012-02-22 19:24:52 +00001675ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001676 if (CE->getNumArgs() < 2)
1677 return 0;
1678
Ted Kremenek8bef8232012-01-26 21:29:00 +00001679 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001680 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001681 const LocationContext *LCtx = C.getLocationContext();
1682 SVal count = state->getSVal(CE->getArg(0), LCtx);
1683 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001684 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1685 svalBuilder.getContext().getSizeType());
1686 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001687
Anna Zaks87cb5be2012-02-22 19:24:52 +00001688 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001689}
1690
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001691LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001692MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1693 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001694 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001695 // Walk the ExplodedGraph backwards and find the first node that referred to
1696 // the tracked symbol.
1697 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001698 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001699
1700 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001701 ProgramStateRef State = N->getState();
1702 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001703 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001704
1705 // Find the most recent expression bound to the symbol in the current
1706 // context.
Anna Zaks27d99dd2013-04-10 21:42:02 +00001707 if (!ReferenceRegion) {
1708 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1709 SVal Val = State->getSVal(MR);
1710 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks8cf91f72013-04-10 22:56:33 +00001711 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00001712 // Do not show local variables belonging to a function other than
1713 // where the error is reported.
1714 if (!VR ||
1715 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1716 ReferenceRegion = MR;
1717 }
1718 }
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001719 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001720
Anna Zaks7752d292012-02-27 23:40:55 +00001721 // Allocation node, is the last node in the current context in which the
1722 // symbol was tracked.
1723 if (N->getLocationContext() == LeakContext)
1724 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001725 N = N->pred_empty() ? NULL : *(N->pred_begin());
1726 }
1727
Anna Zaks97bfb552013-01-08 00:25:29 +00001728 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001729}
1730
Anna Zaksda046772012-02-11 21:02:40 +00001731void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1732 CheckerContext &C) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001733
Stephen Hines651f13c2014-04-23 16:59:28 -07001734 if (!ChecksEnabled[CK_MallocOptimistic] &&
1735 !ChecksEnabled[CK_MallocPessimistic] &&
1736 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001737 return;
1738
Jordan Rosee85deb32013-04-05 17:55:00 +00001739 const RefState *RS = C.getState()->get<RegionState>(Sym);
1740 assert(RS && "cannot leak an untracked symbol");
1741 AllocationFamily Family = RS->getAllocationFamily();
Stephen Hines651f13c2014-04-23 16:59:28 -07001742 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
1743 if (!CheckKind.hasValue())
Anton Yartsev418780f2013-04-05 02:25:02 +00001744 return;
1745
Jordan Rosee85deb32013-04-05 17:55:00 +00001746 // Special case for new and new[]; these are controlled by a separate checker
1747 // flag so that they can be selectively disabled.
1748 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
Stephen Hines651f13c2014-04-23 16:59:28 -07001749 if (!ChecksEnabled[CK_NewDeleteLeaksChecker])
Jordan Rosee85deb32013-04-05 17:55:00 +00001750 return;
1751
Anna Zaksda046772012-02-11 21:02:40 +00001752 assert(N);
Stephen Hines651f13c2014-04-23 16:59:28 -07001753 if (!BT_Leak[*CheckKind]) {
1754 BT_Leak[*CheckKind].reset(
1755 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001756 // Leaks should not be reported if they are post-dominated by a sink:
1757 // (1) Sinks are higher importance bugs.
1758 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1759 // with __noreturn functions such as assert() or exit(). We choose not
1760 // to report leaks on such paths.
Stephen Hines651f13c2014-04-23 16:59:28 -07001761 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksda046772012-02-11 21:02:40 +00001762 }
1763
Anna Zaksca8e36e2012-02-23 21:38:21 +00001764 // Most bug reports are cached at the location where they occurred.
1765 // With leaks, we want to unique them by the location where they were
1766 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001767 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001768 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001769 const MemRegion *Region = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07001770 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Anna Zaks97bfb552013-01-08 00:25:29 +00001771
1772 ProgramPoint P = AllocNode->getLocation();
1773 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001774 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001775 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001776 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001777 AllocationStmt = SP->getStmt();
Anton Yartsev418780f2013-04-05 02:25:02 +00001778 if (AllocationStmt)
Anna Zaks97bfb552013-01-08 00:25:29 +00001779 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1780 C.getSourceManager(),
1781 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001782
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001783 SmallString<200> buf;
1784 llvm::raw_svector_ostream os(buf);
Jordan Rose919e8a12012-08-08 18:23:36 +00001785 if (Region && Region->canPrintPretty()) {
Anna Zaks9e2f5972013-04-12 18:40:21 +00001786 os << "Potential leak of memory pointed to by ";
Jordan Rose919e8a12012-08-08 18:23:36 +00001787 Region->printPretty(os);
Anna Zaks68eb4c22013-04-06 00:41:36 +00001788 } else {
1789 os << "Potential memory leak";
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001790 }
1791
Stephen Hines651f13c2014-04-23 16:59:28 -07001792 BugReport *R =
1793 new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1794 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001795 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001796 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001797 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001798}
1799
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001800void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1801 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001802{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001803 if (!SymReaper.hasDeadSymbols())
1804 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001805
Ted Kremenek8bef8232012-01-26 21:29:00 +00001806 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001807 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001808 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001809
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001810 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001811 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1812 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001813 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001814 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001815 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001816 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001817
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001818 }
1819 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001820
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001821 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001822 ReallocPairsTy RP = state->get<ReallocPairs>();
1823 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001824 if (SymReaper.isDead(I->first) ||
1825 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001826 state = state->remove<ReallocPairs>(I->first);
1827 }
1828 }
1829
Anna Zaks4141e4d2012-11-13 03:18:01 +00001830 // Cleanup the FreeReturnValue Map.
1831 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1832 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1833 if (SymReaper.isDead(I->first) ||
1834 SymReaper.isDead(I->second)) {
1835 state = state->remove<FreeReturnValue>(I->first);
1836 }
1837 }
1838
Anna Zaksca8e36e2012-02-23 21:38:21 +00001839 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001840 ExplodedNode *N = C.getPredecessor();
1841 if (!Errors.empty()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001842 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Anna Zaks54458702012-10-29 22:51:54 +00001843 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper09d19ef2013-07-04 03:08:24 +00001844 for (SmallVectorImpl<SymbolRef>::iterator
1845 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001846 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001847 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001848 }
Anna Zaks54458702012-10-29 22:51:54 +00001849
Anna Zaksca8e36e2012-02-23 21:38:21 +00001850 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001851}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001852
Anton Yartsev55e57a52013-04-10 22:21:41 +00001853void MallocChecker::checkPreCall(const CallEvent &Call,
1854 CheckerContext &C) const {
1855
Stephen Hines651f13c2014-04-23 16:59:28 -07001856 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
1857 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
1858 if (!Sym || checkDoubleDelete(Sym, C))
1859 return;
1860 }
1861
Anna Zaks14345182012-05-18 01:16:10 +00001862 // We will check for double free in the post visit.
Anton Yartsev55e57a52013-04-10 22:21:41 +00001863 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
1864 const FunctionDecl *FD = FC->getDecl();
1865 if (!FD)
1866 return;
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001867
Stephen Hines651f13c2014-04-23 16:59:28 -07001868 if ((ChecksEnabled[CK_MallocOptimistic] ||
1869 ChecksEnabled[CK_MallocPessimistic]) &&
Anton Yartsev55e57a52013-04-10 22:21:41 +00001870 isFreeFunction(FD, C.getASTContext()))
1871 return;
Anna Zaks66c40402012-02-14 21:55:24 +00001872
Stephen Hines651f13c2014-04-23 16:59:28 -07001873 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anton Yartsev55e57a52013-04-10 22:21:41 +00001874 isStandardNewDelete(FD, C.getASTContext()))
1875 return;
1876 }
1877
1878 // Check if the callee of a method is deleted.
1879 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
1880 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
1881 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
1882 return;
1883 }
1884
1885 // Check arguments for being used after free.
1886 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
1887 SVal ArgSVal = Call.getArgSVal(I);
1888 if (ArgSVal.getAs<Loc>()) {
1889 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001890 if (!Sym)
1891 continue;
Anton Yartsev55e57a52013-04-10 22:21:41 +00001892 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks66c40402012-02-14 21:55:24 +00001893 return;
1894 }
1895 }
1896}
1897
Anna Zaks91c2a112012-02-08 23:16:56 +00001898void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1899 const Expr *E = S->getRetValue();
1900 if (!E)
1901 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001902
1903 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001904 ProgramStateRef State = C.getState();
1905 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001906 SymbolRef Sym = RetVal.getAsSymbol();
1907 if (!Sym)
1908 // If we are returning a field of the allocated struct or an array element,
1909 // the callee could still free the memory.
1910 // TODO: This logic should be a part of generic symbol escape callback.
1911 if (const MemRegion *MR = RetVal.getAsRegion())
1912 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1913 if (const SymbolicRegion *BMR =
1914 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1915 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001916
Anna Zaks0860cd02012-02-11 21:44:39 +00001917 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001918 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001919 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001920}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001921
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001922// TODO: Blocks should be either inlined or should call invalidate regions
1923// upon invocation. After that's in place, special casing here will not be
1924// needed.
1925void MallocChecker::checkPostStmt(const BlockExpr *BE,
1926 CheckerContext &C) const {
1927
1928 // Scan the BlockDecRefExprs for any object the retain count checker
1929 // may be tracking.
1930 if (!BE->getBlockDecl()->hasCaptures())
1931 return;
1932
1933 ProgramStateRef state = C.getState();
1934 const BlockDataRegion *R =
1935 cast<BlockDataRegion>(state->getSVal(BE,
1936 C.getLocationContext()).getAsRegion());
1937
1938 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1939 E = R->referenced_vars_end();
1940
1941 if (I == E)
1942 return;
1943
1944 SmallVector<const MemRegion*, 10> Regions;
1945 const LocationContext *LC = C.getLocationContext();
1946 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1947
1948 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001949 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001950 if (VR->getSuperRegion() == R) {
1951 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1952 }
1953 Regions.push_back(VR);
1954 }
1955
1956 state =
1957 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1958 Regions.data() + Regions.size()).getState();
1959 C.addTransition(state);
1960}
1961
Anna Zaks14345182012-05-18 01:16:10 +00001962bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001963 assert(Sym);
1964 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001965 return (RS && RS->isReleased());
1966}
1967
1968bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1969 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001970
Stephen Hines651f13c2014-04-23 16:59:28 -07001971 if (isReleased(Sym, C)) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001972 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1973 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001974 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001975
Anna Zaks91c2a112012-02-08 23:16:56 +00001976 return false;
1977}
1978
Stephen Hines651f13c2014-04-23 16:59:28 -07001979bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
1980
1981 if (isReleased(Sym, C)) {
1982 ReportDoubleDelete(C, Sym);
1983 return true;
1984 }
1985 return false;
1986}
1987
Zhongxing Xuc8023782010-03-10 04:58:55 +00001988// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001989void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1990 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001991 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001992 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001993 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001994}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001995
Anna Zaks4fb54872012-02-11 21:02:35 +00001996// If a symbolic region is assumed to NULL (or another constant), stop tracking
1997// it - assuming that allocation failed on this path.
1998ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1999 SVal Cond,
2000 bool Assumption) const {
2001 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00002002 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00002003 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00002004 ConstraintManager &CMgr = state->getConstraintManager();
2005 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2006 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00002007 state = state->remove<RegionState>(I.getKey());
2008 }
2009
Anna Zaksc8bb3be2012-02-13 18:05:39 +00002010 // Realloc returns 0 when reallocation fails, which means that we should
2011 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00002012 ReallocPairsTy RP = state->get<ReallocPairs>();
2013 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00002014 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00002015 ConstraintManager &CMgr = state->getConstraintManager();
2016 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00002017 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00002018 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00002019
Anna Zaks9dc298b2012-09-12 22:57:34 +00002020 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2021 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2022 if (RS->isReleased()) {
2023 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00002024 state = state->set<RegionState>(ReallocSym,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002025 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks9dc298b2012-09-12 22:57:34 +00002026 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2027 state = state->remove<RegionState>(ReallocSym);
2028 else
2029 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00002030 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00002031 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00002032 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00002033 }
2034
Anna Zaks4fb54872012-02-11 21:02:35 +00002035 return state;
2036}
2037
Anna Zaks33708592013-06-08 00:29:29 +00002038bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zakse7a5c822013-05-31 23:47:32 +00002039 const CallEvent *Call,
2040 ProgramStateRef State,
2041 SymbolRef &EscapingSymbol) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00002042 assert(Call);
Anna Zaks33708592013-06-08 00:29:29 +00002043 EscapingSymbol = 0;
2044
Stephen Hines651f13c2014-04-23 16:59:28 -07002045 // For now, assume that any C++ or block call can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00002046 // TODO: If we want to be more optimistic here, we'll need to make sure that
2047 // regions escape to C++ containers. They seem to do that even now, but for
2048 // mysterious reasons.
Stephen Hines651f13c2014-04-23 16:59:28 -07002049 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zakse7a5c822013-05-31 23:47:32 +00002050 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00002051
Jordan Rose740d4902012-07-02 19:27:35 +00002052 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002053 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00002054 // If it's not a framework call, or if it takes a callback, assume it
2055 // can free memory.
2056 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zakse7a5c822013-05-31 23:47:32 +00002057 return true;
Anna Zaks07d39a42012-02-28 01:54:22 +00002058
Jordan Rose9fe09f32013-03-09 00:59:10 +00002059 // If it's a method we know about, handle it explicitly post-call.
2060 // This should happen before the "freeWhenDone" check below.
2061 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zakse7a5c822013-05-31 23:47:32 +00002062 return false;
Anna Zaks52a04812012-06-20 23:35:57 +00002063
Jordan Rose9fe09f32013-03-09 00:59:10 +00002064 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2065 // about, we can't be sure that the object will use free() to deallocate the
2066 // memory, so we can't model it explicitly. The best we can do is use it to
2067 // decide whether the pointer escapes.
2068 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zakse7a5c822013-05-31 23:47:32 +00002069 return *FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00002070
Jordan Rose9fe09f32013-03-09 00:59:10 +00002071 // If the first selector piece ends with "NoCopy", and there is no
2072 // "freeWhenDone" parameter set to zero, we know ownership is being
2073 // transferred. Again, though, we can't be sure that the object will use
2074 // free() to deallocate the memory, so we can't model it explicitly.
2075 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00002076 if (FirstSlot.endswith("NoCopy"))
Anna Zakse7a5c822013-05-31 23:47:32 +00002077 return true;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00002078
Anna Zaks5f757682012-06-19 05:10:32 +00002079 // If the first selector starts with addPointer, insertPointer,
2080 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2081 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00002082 // that the pointers get freed by following the container itself.
2083 if (FirstSlot.startswith("addPointer") ||
2084 FirstSlot.startswith("insertPointer") ||
Stephen Hines651f13c2014-04-23 16:59:28 -07002085 FirstSlot.startswith("replacePointer") ||
2086 FirstSlot.equals("valueWithPointer")) {
Anna Zakse7a5c822013-05-31 23:47:32 +00002087 return true;
Anna Zaks5f757682012-06-19 05:10:32 +00002088 }
2089
Anna Zakse7a5c822013-05-31 23:47:32 +00002090 // We should escape receiver on call to 'init'. This is especially relevant
2091 // to the receiver, as the corresponding symbol is usually not referenced
2092 // after the call.
2093 if (Msg->getMethodFamily() == OMF_init) {
2094 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2095 return true;
2096 }
Anna Zaksee1af232013-05-31 22:39:13 +00002097
Jordan Rose740d4902012-07-02 19:27:35 +00002098 // Otherwise, assume that the method does not free memory.
2099 // Most framework methods do not free memory.
Anna Zakse7a5c822013-05-31 23:47:32 +00002100 return false;
Anna Zaks66c40402012-02-14 21:55:24 +00002101 }
2102
Jordan Rose740d4902012-07-02 19:27:35 +00002103 // At this point the only thing left to handle is straight function calls.
Stephen Hines651f13c2014-04-23 16:59:28 -07002104 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose740d4902012-07-02 19:27:35 +00002105 if (!FD)
Anna Zakse7a5c822013-05-31 23:47:32 +00002106 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00002107
Jordan Rose740d4902012-07-02 19:27:35 +00002108 ASTContext &ASTC = State->getStateManager().getContext();
2109
2110 // If it's one of the allocation functions we can reason about, we model
2111 // its behavior explicitly.
2112 if (isMemFunction(FD, ASTC))
Anna Zakse7a5c822013-05-31 23:47:32 +00002113 return false;
Jordan Rose740d4902012-07-02 19:27:35 +00002114
2115 // If it's not a system call, assume it frees memory.
2116 if (!Call->isInSystemHeader())
Anna Zakse7a5c822013-05-31 23:47:32 +00002117 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002118
2119 // White list the system functions whose arguments escape.
2120 const IdentifierInfo *II = FD->getIdentifier();
2121 if (!II)
Anna Zakse7a5c822013-05-31 23:47:32 +00002122 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002123 StringRef FName = II->getName();
2124
Jordan Rose740d4902012-07-02 19:27:35 +00002125 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00002126 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00002127 if (FName.endswith("NoCopy")) {
2128 // Look for the deallocator argument. We know that the memory ownership
2129 // is not transferred only if the deallocator argument is
2130 // 'kCFAllocatorNull'.
2131 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2132 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2133 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2134 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2135 if (DeallocatorName == "kCFAllocatorNull")
Anna Zakse7a5c822013-05-31 23:47:32 +00002136 return false;
Jordan Rose740d4902012-07-02 19:27:35 +00002137 }
2138 }
Anna Zakse7a5c822013-05-31 23:47:32 +00002139 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002140 }
2141
Jordan Rose740d4902012-07-02 19:27:35 +00002142 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00002143 // 'closefn' is specified (and if that function does free memory),
2144 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00002145 // Currently, we do not inspect the 'closefn' function (PR12101).
2146 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00002147 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zakse7a5c822013-05-31 23:47:32 +00002148 return false;
Jordan Rose740d4902012-07-02 19:27:35 +00002149
2150 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2151 // these leaks might be intentional when setting the buffer for stdio.
2152 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2153 if (FName == "setbuf" || FName =="setbuffer" ||
2154 FName == "setlinebuf" || FName == "setvbuf") {
2155 if (Call->getNumArgs() >= 1) {
2156 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2157 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2158 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2159 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zakse7a5c822013-05-31 23:47:32 +00002160 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002161 }
2162 }
2163
2164 // A bunch of other functions which either take ownership of a pointer or
2165 // wrap the result up in a struct or object, meaning it can be freed later.
2166 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2167 // but the Malloc checker cannot differentiate between them. The right way
2168 // of doing this would be to implement a pointer escapes callback.
2169 if (FName == "CGBitmapContextCreate" ||
2170 FName == "CGBitmapContextCreateWithData" ||
2171 FName == "CVPixelBufferCreateWithBytes" ||
2172 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2173 FName == "OSAtomicEnqueue") {
Anna Zakse7a5c822013-05-31 23:47:32 +00002174 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002175 }
2176
Jordan Rose85d7e012012-07-02 19:27:51 +00002177 // Handle cases where we know a buffer's /address/ can escape.
2178 // Note that the above checks handle some special cases where we know that
2179 // even though the address escapes, it's still our responsibility to free the
2180 // buffer.
2181 if (Call->argumentsMayEscape())
Anna Zakse7a5c822013-05-31 23:47:32 +00002182 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002183
2184 // Otherwise, assume that the function does not free memory.
2185 // Most system calls do not free the memory.
Anna Zakse7a5c822013-05-31 23:47:32 +00002186 return false;
Anna Zaks66c40402012-02-14 21:55:24 +00002187}
2188
Anna Zaks41988f32013-03-28 23:15:29 +00002189static bool retTrue(const RefState *RS) {
2190 return true;
2191}
2192
2193static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2194 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2195 RS->getAllocationFamily() == AF_CXXNew);
2196}
2197
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002198ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2199 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00002200 const CallEvent *Call,
2201 PointerEscapeKind Kind) const {
Anna Zaks41988f32013-03-28 23:15:29 +00002202 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2203}
2204
2205ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2206 const InvalidatedSymbols &Escaped,
2207 const CallEvent *Call,
2208 PointerEscapeKind Kind) const {
2209 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2210 &checkIfNewOrNewArrayFamily);
2211}
2212
2213ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2214 const InvalidatedSymbols &Escaped,
2215 const CallEvent *Call,
2216 PointerEscapeKind Kind,
2217 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00002218 // If we know that the call does not free memory, or we want to process the
2219 // call later, keep tracking the top level arguments.
Anna Zakse7a5c822013-05-31 23:47:32 +00002220 SymbolRef EscapingSymbol = 0;
Jordan Rose374ae322013-05-10 17:07:16 +00002221 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks33708592013-06-08 00:29:29 +00002222 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2223 EscapingSymbol) &&
Anna Zakse7a5c822013-05-31 23:47:32 +00002224 !EscapingSymbol) {
Anna Zaks66c40402012-02-14 21:55:24 +00002225 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00002226 }
Anna Zaks66c40402012-02-14 21:55:24 +00002227
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002228 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks41988f32013-03-28 23:15:29 +00002229 E = Escaped.end();
2230 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00002231 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002232
Anna Zakse7a5c822013-05-31 23:47:32 +00002233 if (EscapingSymbol && EscapingSymbol != sym)
2234 continue;
2235
Anna Zaks5b7aa342012-06-22 02:04:31 +00002236 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks04130232013-04-09 00:30:28 +00002237 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks431e35c2012-08-09 00:42:24 +00002238 State = State->remove<RegionState>(sym);
Anna Zaks04130232013-04-09 00:30:28 +00002239 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2240 }
Anna Zaks5b7aa342012-06-22 02:04:31 +00002241 }
Anna Zaks4fb54872012-02-11 21:02:35 +00002242 }
Anna Zaks66c40402012-02-14 21:55:24 +00002243 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00002244}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002245
Jordy Rose393f98b2012-03-18 07:43:35 +00002246static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2247 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00002248 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2249 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00002250
Jordan Rose166d5022012-11-02 01:54:06 +00002251 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00002252 I != E; ++I) {
2253 SymbolRef sym = I.getKey();
2254 if (!currMap.lookup(sym))
2255 return sym;
2256 }
2257
2258 return NULL;
2259}
2260
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002261PathDiagnosticPiece *
2262MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2263 const ExplodedNode *PrevN,
2264 BugReporterContext &BRC,
2265 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00002266 ProgramStateRef state = N->getState();
2267 ProgramStateRef statePrev = PrevN->getState();
2268
2269 const RefState *RS = state->get<RegionState>(Sym);
2270 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00002271 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002272 return 0;
2273
Anna Zaksfe571602012-02-16 22:26:07 +00002274 const Stmt *S = 0;
2275 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002276 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00002277
2278 // Retrieve the associated statement.
2279 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002280 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002281 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00002282 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002283 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00002284 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00002285 // If an assumption was made on a branch, it should be caught
2286 // here by looking at the state transition.
2287 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00002288 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00002289
Anna Zaksfe571602012-02-16 22:26:07 +00002290 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002291 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002292
Jordan Rose28038f32012-07-10 22:07:42 +00002293 // FIXME: We will eventually need to handle non-statement-based events
2294 // (__attribute__((cleanup))).
2295
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002296 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00002297 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00002298 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002299 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00002300 StackHint = new StackHintGeneratorForSymbol(Sym,
2301 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00002302 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002303 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00002304 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zaks148d9222013-04-16 00:22:55 +00002305 "Returning; memory was released");
Anna Zaks5b7aa342012-06-22 02:04:31 +00002306 } else if (isRelinquished(RS, RSPrev, S)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002307 Msg = "Memory ownership is transferred";
Anna Zaks5b7aa342012-06-22 02:04:31 +00002308 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00002309 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002310 Mode = ReallocationFailed;
2311 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00002312 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00002313 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00002314
Jordy Roseb000fb52012-03-24 03:15:09 +00002315 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2316 // Is it possible to fail two reallocs WITHOUT testing in between?
2317 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2318 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00002319 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00002320 FailedReallocSymbol = sym;
2321 }
Anna Zaksfe571602012-02-16 22:26:07 +00002322 }
2323
2324 // We are in a special mode if a reallocation failed later in the path.
2325 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002326 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00002327
Jordy Roseb000fb52012-03-24 03:15:09 +00002328 // Is this is the first appearance of the reallocated symbol?
2329 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002330 // We're at the reallocation point.
2331 Msg = "Attempt to reallocate memory";
2332 StackHint = new StackHintGeneratorForSymbol(Sym,
2333 "Returned reallocated memory");
2334 FailedReallocSymbol = NULL;
2335 Mode = Normal;
2336 }
Anna Zaksfe571602012-02-16 22:26:07 +00002337 }
2338
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002339 if (!Msg)
2340 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002341 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002342
2343 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00002344 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002345 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00002346 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002347}
2348
Anna Zaks93c5a242012-05-02 00:05:20 +00002349void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2350 const char *NL, const char *Sep) const {
2351
2352 RegionStateTy RS = State->get<RegionState>();
2353
Ted Kremenekc37fad62013-01-03 01:30:12 +00002354 if (!RS.isEmpty()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002355 Out << Sep << "MallocChecker :" << NL;
Ted Kremenekc37fad62013-01-03 01:30:12 +00002356 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002357 const RefState *RefS = State->get<RegionState>(I.getKey());
2358 AllocationFamily Family = RefS->getAllocationFamily();
2359 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2360
Ted Kremenekc37fad62013-01-03 01:30:12 +00002361 I.getKey()->dumpToStream(Out);
2362 Out << " : ";
2363 I.getData().dump(Out);
Stephen Hines651f13c2014-04-23 16:59:28 -07002364 if (CheckKind.hasValue())
2365 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenekc37fad62013-01-03 01:30:12 +00002366 Out << NL;
2367 }
2368 }
Anna Zaks93c5a242012-05-02 00:05:20 +00002369}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002370
Anna Zaks148d9222013-04-16 00:22:55 +00002371void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2372 registerCStringCheckerBasic(mgr);
Stephen Hines651f13c2014-04-23 16:59:28 -07002373 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2374 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2375 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2376 mgr.getCurrentCheckName();
Anna Zaks148d9222013-04-16 00:22:55 +00002377 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2378 // checker.
Stephen Hines651f13c2014-04-23 16:59:28 -07002379 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
2380 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zaks148d9222013-04-16 00:22:55 +00002381}
Anton Yartsev9df151c2013-04-12 23:25:40 +00002382
Stephen Hines651f13c2014-04-23 16:59:28 -07002383#define REGISTER_CHECKER(name) \
2384 void ento::register##name(CheckerManager &mgr) { \
2385 registerCStringCheckerBasic(mgr); \
2386 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2387 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2388 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2389 }
Anna Zaks231361a2012-02-08 23:16:52 +00002390
2391REGISTER_CHECKER(MallocPessimistic)
2392REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00002393REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002394REGISTER_CHECKER(MismatchedDeallocatorChecker)