blob: f924a767789406b8e7a4f0569fe3ed7efc3a5be0 [file] [log] [blame]
Zhongxing Xu88cca6b2009-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 Kyrtzidis183f0fb2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zakse56167e2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +000018#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/SourceManager.h"
Jordan Rose6b33c6f2014-03-26 17:05:46 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000023#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000029#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000030#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000032#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000033#include <climits>
34
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000035using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000036using namespace ento;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000037
38namespace {
39
Anton Yartsev05789592013-03-28 17:05:19 +000040// Used to check correspondence between allocators and deallocators.
41enum AllocationFamily {
42 AF_None,
43 AF_Malloc,
44 AF_CXXNew,
Anna Zaksd79b8402014-10-03 21:48:59 +000045 AF_CXXNewArray,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +000046 AF_IfNameIndex,
47 AF_Alloca
Anton Yartsev05789592013-03-28 17:05:19 +000048};
49
Zhongxing Xu1239de12009-12-11 00:55:44 +000050class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000051 enum Kind { // Reference to allocated memory.
52 Allocated,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000053 // Reference to zero-allocated memory.
54 AllocatedOfSizeZero,
Anna Zaks9050ffd2012-06-20 20:57:46 +000055 // Reference to released/freed memory.
56 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000057 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000058 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000059 Relinquished,
60 // We are no longer guaranteed to have observed all manipulations
61 // of this pointer/memory. For example, it could have been
62 // passed as a parameter to an opaque function.
63 Escaped
64 };
Anton Yartsev05789592013-03-28 17:05:19 +000065
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000066 const Stmt *S;
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000067 unsigned K : 3; // Kind enum, but stored as a bitfield.
Ted Kremenek3a0678e2015-09-08 03:50:52 +000068 unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
Anton Yartsev05789592013-03-28 17:05:19 +000069 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000070
Ted Kremenek3a0678e2015-09-08 03:50:52 +000071 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000072 : S(s), K(k), Family(family) {
73 assert(family != AF_None);
74 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000075public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000076 bool isAllocated() const { return K == Allocated; }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000077 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000078 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000079 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000080 bool isEscaped() const { return K == Escaped; }
81 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000082 return (AllocationFamily)Family;
83 }
Anna Zaksd56c8792012-02-13 18:05:39 +000084 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000085
86 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000087 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000088 }
89
Anton Yartsev05789592013-03-28 17:05:19 +000090 static RefState getAllocated(unsigned family, const Stmt *s) {
91 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000092 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000093 static RefState getAllocatedOfSizeZero(const RefState *RS) {
94 return RefState(AllocatedOfSizeZero, RS->getStmt(),
95 RS->getAllocationFamily());
96 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +000097 static RefState getReleased(unsigned family, const Stmt *s) {
Anton Yartsev05789592013-03-28 17:05:19 +000098 return RefState(Released, s, family);
99 }
100 static RefState getRelinquished(unsigned family, const Stmt *s) {
101 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +0000102 }
Anna Zaks93a21a82013-04-09 00:30:28 +0000103 static RefState getEscaped(const RefState *RS) {
104 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
105 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000106
107 void Profile(llvm::FoldingSetNodeID &ID) const {
108 ID.AddInteger(K);
109 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +0000110 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000111 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000112
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000113 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000114 switch (static_cast<Kind>(K)) {
115#define CASE(ID) case ID: OS << #ID; break;
116 CASE(Allocated)
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000117 CASE(AllocatedOfSizeZero)
Jordan Rose6adadb92014-01-23 03:59:01 +0000118 CASE(Released)
119 CASE(Relinquished)
120 CASE(Escaped)
121 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000122 }
123
Alp Tokeref6b0072014-01-04 13:47:14 +0000124 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000125};
126
Anna Zaks75cfbb62012-09-12 22:57:34 +0000127enum ReallocPairKind {
128 RPToBeFreedAfterFailure,
129 // The symbol has been freed when reallocation failed.
130 RPIsFreeOnFailure,
131 // The symbol does not need to be freed after reallocation fails.
132 RPDoNotTrackAfterFailure
133};
134
Anna Zaksfe6eb672012-08-24 02:28:20 +0000135/// \class ReallocPair
136/// \brief Stores information about the symbol being reallocated by a call to
137/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000138struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000139 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000140 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000141 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000142
Anna Zaks75cfbb62012-09-12 22:57:34 +0000143 ReallocPair(SymbolRef S, ReallocPairKind K) :
144 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000145 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000146 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000147 ID.AddPointer(ReallocatedSym);
148 }
149 bool operator==(const ReallocPair &X) const {
150 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000151 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000152 }
153};
154
Anna Zaksa043d0c2013-01-08 00:25:29 +0000155typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000156
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000157class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000158 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000159 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000160 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000161 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000162 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000163 check::PostStmt<CXXNewExpr>,
164 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000165 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000166 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000167 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000168 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000169{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000170public:
Craig Topper0dbb7832014-05-27 02:45:47 +0000171 MallocChecker()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000172 : II_alloca(nullptr), II_malloc(nullptr), II_free(nullptr),
Anton Yartsevc38d7952015-03-03 22:58:46 +0000173 II_realloc(nullptr), II_calloc(nullptr), II_valloc(nullptr),
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000174 II_reallocf(nullptr), II_strndup(nullptr), II_strdup(nullptr),
Anton Yartsevc38d7952015-03-03 22:58:46 +0000175 II_kmalloc(nullptr), II_if_nameindex(nullptr),
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000176 II_if_freenameindex(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000177
178 /// In pessimistic mode, the checker assumes that it does not know which
179 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000180 enum CheckKind {
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000181 CK_MallocChecker,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000182 CK_NewDeleteChecker,
183 CK_NewDeleteLeaksChecker,
184 CK_MismatchedDeallocatorChecker,
185 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000186 };
187
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000188 enum class MemoryOperationKind {
Anna Zaksd79b8402014-10-03 21:48:59 +0000189 MOK_Allocate,
190 MOK_Free,
191 MOK_Any
192 };
193
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000194 DefaultBool IsOptimistic;
195
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000196 DefaultBool ChecksEnabled[CK_NumCheckKinds];
197 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000198
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000199 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000200 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000201 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
202 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000203 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000204 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000205 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000206 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000207 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000208 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000209 void checkLocation(SVal l, bool isLoad, const Stmt *S,
210 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000211
212 ProgramStateRef checkPointerEscape(ProgramStateRef State,
213 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000214 const CallEvent *Call,
215 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000216 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
217 const InvalidatedSymbols &Escaped,
218 const CallEvent *Call,
219 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000220
Anna Zaks263b7e02012-05-02 00:05:20 +0000221 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000222 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000223
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000224private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000225 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
226 mutable std::unique_ptr<BugType> BT_DoubleDelete;
227 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
228 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
229 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000230 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000231 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
232 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000233 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
Anton Yartsevc38d7952015-03-03 22:58:46 +0000234 mutable IdentifierInfo *II_alloca, *II_malloc, *II_free, *II_realloc,
235 *II_calloc, *II_valloc, *II_reallocf, *II_strndup,
236 *II_strdup, *II_kmalloc, *II_if_nameindex,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000237 *II_if_freenameindex;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000238 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000239
Anna Zaks3d348342012-02-14 21:55:24 +0000240 void initIdentifierInfo(ASTContext &C) const;
241
Anton Yartsev05789592013-03-28 17:05:19 +0000242 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000243 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000244
245 /// \brief Print names of allocators and deallocators.
246 ///
247 /// \returns true on success.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000248 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000249 const Expr *E) const;
250
251 /// \brief Print expected name of an allocator based on the deallocator's
252 /// family derived from the DeallocExpr.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000253 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000254 const Expr *DeallocExpr) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000255 /// \brief Print expected name of a deallocator based on the allocator's
Anton Yartsev05789592013-03-28 17:05:19 +0000256 /// family.
257 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
258
Jordan Rose613f3c02013-03-09 00:59:10 +0000259 ///@{
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000260 /// Check if this is one of the functions which can allocate/reallocate memory
Anna Zaks3d348342012-02-14 21:55:24 +0000261 /// pointed to by one of its arguments.
262 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000263 bool isCMemFunction(const FunctionDecl *FD,
264 ASTContext &C,
265 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000266 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000267 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000268 ///@}
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000269
270 /// \brief Perform a zero-allocation check.
271 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
272 const unsigned AllocationSizeArg,
273 ProgramStateRef State) const;
274
Richard Smith852e9ce2013-11-27 01:46:48 +0000275 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
276 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000277 const OwnershipAttr* Att,
278 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000279 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000280 const Expr *SizeEx, SVal Init,
281 ProgramStateRef State,
282 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000283 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000284 SVal SizeEx, SVal Init,
285 ProgramStateRef State,
286 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000287
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000288 // Check if this malloc() for special flags. At present that means M_ZERO or
289 // __GFP_ZERO (in which case, treat it like calloc).
290 llvm::Optional<ProgramStateRef>
291 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
292 const ProgramStateRef &State) const;
293
Anna Zaks40a7eb32012-02-22 19:24:52 +0000294 /// Update the RefState to reflect the new memory allocation.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000295 static ProgramStateRef
Anton Yartsev05789592013-03-28 17:05:19 +0000296 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
297 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000298
299 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000300 const OwnershipAttr* Att,
301 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000302 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000303 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000304 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000305 bool &ReleasedAllocated,
306 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000307 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
308 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000309 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000310 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000311 bool &ReleasedAllocated,
312 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000313
Anna Zaks40a7eb32012-02-22 19:24:52 +0000314 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000315 bool FreesMemOnFailure,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000316 ProgramStateRef State) const;
317 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
318 ProgramStateRef State);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000319
Anna Zaks46d01602012-05-18 01:16:10 +0000320 ///\brief Check if the memory associated with this symbol was released.
321 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
322
Anton Yartsev13df0362013-03-25 01:35:45 +0000323 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000324
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000325 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000326 const Stmt *S) const;
327
Jordan Rose656fdd52014-01-08 18:46:55 +0000328 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
329
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000330 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000331 /// "interesting" and should be modeled explicitly.
332 ///
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000333 /// \param [out] EscapingSymbol A function might not free memory in general,
Anna Zaks8ebeb642013-06-08 00:29:29 +0000334 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000335 /// returned and the single escaping symbol is returned through the out
336 /// parameter.
337 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000338 /// We assume that pointers do not escape through calls to system functions
339 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000340 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000341 ProgramStateRef State,
342 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000343
Anna Zaks333481b2013-03-28 23:15:29 +0000344 // Implementation of the checkPointerEscape callabcks.
345 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
346 const InvalidatedSymbols &Escaped,
347 const CallEvent *Call,
348 PointerEscapeKind Kind,
349 bool(*CheckRefState)(const RefState*)) const;
350
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000351 ///@{
352 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000353 /// Sets CheckKind to the kind of the checker responsible for this
354 /// family/call/symbol.
Anton Yartsev2487dd62015-03-10 22:24:21 +0000355 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
356 bool IsALeakCheck = false) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000357 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000358 const Stmt *AllocDeallocStmt,
359 bool IsALeakCheck = false) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000360 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000361 bool IsALeakCheck = false) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000362 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000363 static bool SummarizeValue(raw_ostream &os, SVal V);
364 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000365 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +0000366 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000367 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
368 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000369 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000370 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000371 SymbolRef Sym, bool OwnershipTransferred) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000372 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
373 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000374 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000375 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
376 SymbolRef Sym) const;
377 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000378 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000379
Jordan Rose656fdd52014-01-08 18:46:55 +0000380 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
381
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000382 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
383 SymbolRef Sym) const;
384
Anna Zaksdf901a42012-02-23 21:38:21 +0000385 /// Find the location of the allocation for Sym on the path leading to the
386 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000387 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
388 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000389
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000390 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
391
Anna Zaks2b5bb972012-02-09 06:25:51 +0000392 /// The bug visitor which allows us to print extra diagnostics along the
393 /// BugReport path. For example, showing the allocation site of the leaked
394 /// region.
David Blaikie6951e3e2015-08-13 22:58:37 +0000395 class MallocBugVisitor final
396 : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000397 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000398 enum NotificationMode {
399 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000400 ReallocationFailed
401 };
402
Anna Zaks2b5bb972012-02-09 06:25:51 +0000403 // The allocated region symbol tracked by the main analysis.
404 SymbolRef Sym;
405
Anna Zaks62cce9e2012-05-10 01:37:40 +0000406 // The mode we are in, i.e. what kind of diagnostics will be emitted.
407 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000408
Anna Zaks62cce9e2012-05-10 01:37:40 +0000409 // A symbol from when the primary region should have been reallocated.
410 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000411
Anna Zaks62cce9e2012-05-10 01:37:40 +0000412 bool IsLeak;
413
414 public:
415 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000416 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000417
Craig Topperfb6b25b2014-03-15 04:29:04 +0000418 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000419 static int X = 0;
420 ID.AddPointer(&X);
421 ID.AddPointer(Sym);
422 }
423
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000424 inline bool isAllocated(const RefState *S, const RefState *SPrev,
425 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000426 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000427 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000428 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
429 (!SPrev || !(SPrev->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000430 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000431 }
432
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000433 inline bool isReleased(const RefState *S, const RefState *SPrev,
434 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000435 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000436 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000437 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
438 }
439
Anna Zaks0d6989b2012-06-22 02:04:31 +0000440 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
441 const Stmt *Stmt) {
442 // Did not track -> relinquished. Other state (allocated) -> relinquished.
443 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
444 isa<ObjCPropertyRefExpr>(Stmt)) &&
445 (S && S->isRelinquished()) &&
446 (!SPrev || !SPrev->isRelinquished()));
447 }
448
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000449 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
450 const Stmt *Stmt) {
451 // If the expression is not a call, and the state change is
452 // released -> allocated, it must be the realloc return value
453 // check. If we have to handle more cases here, it might be cleaner just
454 // to track this extra bit in the state itself.
455 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000456 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
457 (SPrev && !(SPrev->isAllocated() ||
458 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000459 }
460
461 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
462 const ExplodedNode *PrevN,
463 BugReporterContext &BRC,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000464 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000465
David Blaikied15481c2014-08-29 18:18:43 +0000466 std::unique_ptr<PathDiagnosticPiece>
467 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
468 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000469 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000470 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000471
472 PathDiagnosticLocation L =
473 PathDiagnosticLocation::createEndOfPath(EndPathNode,
474 BRC.getSourceManager());
475 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000476 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
477 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000478 }
479
Anna Zakscba4f292012-03-16 23:24:20 +0000480 private:
481 class StackHintGeneratorForReallocationFailed
482 : public StackHintGeneratorForSymbol {
483 public:
484 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
485 : StackHintGeneratorForSymbol(S, M) {}
486
Craig Topperfb6b25b2014-03-15 04:29:04 +0000487 std::string getMessageForArg(const Expr *ArgE,
488 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000489 // Printed parameters start at 1, not 0.
490 ++ArgIndex;
491
Anna Zakscba4f292012-03-16 23:24:20 +0000492 SmallString<200> buf;
493 llvm::raw_svector_ostream os(buf);
494
Jordan Rosec102b352012-09-22 01:24:42 +0000495 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
496 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000497
498 return os.str();
499 }
500
Craig Topperfb6b25b2014-03-15 04:29:04 +0000501 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000502 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000503 }
504 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000505 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000506};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000507} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000508
Jordan Rose0c153cb2012-11-02 01:54:06 +0000509REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
510REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Devin Coughlin81771732015-09-22 22:47:14 +0000511REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000512
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000513// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000514// the free function.
515REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
516
Anna Zaksbb1ef902012-02-11 21:02:35 +0000517namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000518class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000519 ProgramStateRef state;
520public:
521 StopTrackingCallback(ProgramStateRef st) : state(st) {}
522 ProgramStateRef getState() const { return state; }
523
Craig Topperfb6b25b2014-03-15 04:29:04 +0000524 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000525 state = state->remove<RegionState>(sym);
526 return true;
527 }
528};
529} // end anonymous namespace
530
Anna Zaks3d348342012-02-14 21:55:24 +0000531void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000532 if (II_malloc)
533 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000534 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000535 II_malloc = &Ctx.Idents.get("malloc");
536 II_free = &Ctx.Idents.get("free");
537 II_realloc = &Ctx.Idents.get("realloc");
538 II_reallocf = &Ctx.Idents.get("reallocf");
539 II_calloc = &Ctx.Idents.get("calloc");
540 II_valloc = &Ctx.Idents.get("valloc");
541 II_strdup = &Ctx.Idents.get("strdup");
542 II_strndup = &Ctx.Idents.get("strndup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000543 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000544 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
545 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000546}
547
Anna Zaks3d348342012-02-14 21:55:24 +0000548bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000549 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000550 return true;
551
Anna Zaksd79b8402014-10-03 21:48:59 +0000552 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000553 return true;
554
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000555 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
556 return true;
557
Anton Yartsev13df0362013-03-25 01:35:45 +0000558 if (isStandardNewDelete(FD, C))
559 return true;
560
Anna Zaks46d01602012-05-18 01:16:10 +0000561 return false;
562}
563
Anna Zaksd79b8402014-10-03 21:48:59 +0000564bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
565 ASTContext &C,
566 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000567 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000568 if (!FD)
569 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000570
Anna Zaksd79b8402014-10-03 21:48:59 +0000571 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
572 MemKind == MemoryOperationKind::MOK_Free);
573 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
574 MemKind == MemoryOperationKind::MOK_Allocate);
575
Jordan Rose6cd16c52012-07-10 23:13:01 +0000576 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000577 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000578 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000579
Anna Zaksd79b8402014-10-03 21:48:59 +0000580 if (Family == AF_Malloc && CheckFree) {
581 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
582 return true;
583 }
584
585 if (Family == AF_Malloc && CheckAlloc) {
586 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
587 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
588 FunI == II_strndup || FunI == II_kmalloc)
589 return true;
590 }
591
592 if (Family == AF_IfNameIndex && CheckFree) {
593 if (FunI == II_if_freenameindex)
594 return true;
595 }
596
597 if (Family == AF_IfNameIndex && CheckAlloc) {
598 if (FunI == II_if_nameindex)
599 return true;
600 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000601
602 if (Family == AF_Alloca && CheckAlloc) {
Anton Yartsevc38d7952015-03-03 22:58:46 +0000603 if (FunI == II_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000604 return true;
605 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000606 }
Anna Zaks3d348342012-02-14 21:55:24 +0000607
Anna Zaksd79b8402014-10-03 21:48:59 +0000608 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000609 return false;
610
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000611 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000612 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
613 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
614 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
615 if (CheckFree)
616 return true;
617 } else if (OwnKind == OwnershipAttr::Returns) {
618 if (CheckAlloc)
619 return true;
620 }
621 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000622 }
Anna Zaks3d348342012-02-14 21:55:24 +0000623
Anna Zaks3d348342012-02-14 21:55:24 +0000624 return false;
625}
626
Anton Yartsev8b662702013-03-28 16:10:38 +0000627// Tells if the callee is one of the following:
628// 1) A global non-placement new/delete operator function.
629// 2) A global placement operator function with the single placement argument
630// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000631bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
632 ASTContext &C) const {
633 if (!FD)
634 return false;
635
636 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000637 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000638 Kind != OO_Delete && Kind != OO_Array_Delete)
639 return false;
640
Anton Yartsev8b662702013-03-28 16:10:38 +0000641 // Skip all operator new/delete methods.
642 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000643 return false;
644
645 // Return true if tested operator is a standard placement nothrow operator.
646 if (FD->getNumParams() == 2) {
647 QualType T = FD->getParamDecl(1)->getType();
648 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
649 return II->getName().equals("nothrow_t");
650 }
651
652 // Skip placement operators.
653 if (FD->getNumParams() != 1 || FD->isVariadic())
654 return false;
655
656 // One of the standard new/new[]/delete/delete[] non-placement operators.
657 return true;
658}
659
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000660llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
661 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
662 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
663 //
664 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
665 //
666 // One of the possible flags is M_ZERO, which means 'give me back an
667 // allocation which is already zeroed', like calloc.
668
669 // 2-argument kmalloc(), as used in the Linux kernel:
670 //
671 // void *kmalloc(size_t size, gfp_t flags);
672 //
673 // Has the similar flag value __GFP_ZERO.
674
675 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
676 // code could be shared.
677
678 ASTContext &Ctx = C.getASTContext();
679 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
680
681 if (!KernelZeroFlagVal.hasValue()) {
682 if (OS == llvm::Triple::FreeBSD)
683 KernelZeroFlagVal = 0x0100;
684 else if (OS == llvm::Triple::NetBSD)
685 KernelZeroFlagVal = 0x0002;
686 else if (OS == llvm::Triple::OpenBSD)
687 KernelZeroFlagVal = 0x0008;
688 else if (OS == llvm::Triple::Linux)
689 // __GFP_ZERO
690 KernelZeroFlagVal = 0x8000;
691 else
692 // FIXME: We need a more general way of getting the M_ZERO value.
693 // See also: O_CREAT in UnixAPIChecker.cpp.
694
695 // Fall back to normal malloc behavior on platforms where we don't
696 // know M_ZERO.
697 return None;
698 }
699
700 // We treat the last argument as the flags argument, and callers fall-back to
701 // normal malloc on a None return. This works for the FreeBSD kernel malloc
702 // as well as Linux kmalloc.
703 if (CE->getNumArgs() < 2)
704 return None;
705
706 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
707 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
708 if (!V.getAs<NonLoc>()) {
709 // The case where 'V' can be a location can only be due to a bad header,
710 // so in this case bail out.
711 return None;
712 }
713
714 NonLoc Flags = V.castAs<NonLoc>();
715 NonLoc ZeroFlag = C.getSValBuilder()
716 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
717 .castAs<NonLoc>();
718 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
719 Flags, ZeroFlag,
720 FlagsEx->getType());
721 if (MaskedFlagsUC.isUnknownOrUndef())
722 return None;
723 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
724
725 // Check if maskedFlags is non-zero.
726 ProgramStateRef TrueState, FalseState;
727 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
728
729 // If M_ZERO is set, treat this like calloc (initialized).
730 if (TrueState && !FalseState) {
731 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
732 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
733 }
734
735 return None;
736}
737
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000738void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000739 if (C.wasInlined)
740 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000741
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000742 const FunctionDecl *FD = C.getCalleeDecl(CE);
743 if (!FD)
744 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000745
Anna Zaks40a7eb32012-02-22 19:24:52 +0000746 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000747 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000748
749 if (FD->getKind() == Decl::Function) {
750 initIdentifierInfo(C.getASTContext());
751 IdentifierInfo *FunI = FD->getIdentifier();
752
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000753 if (FunI == II_malloc) {
754 if (CE->getNumArgs() < 1)
755 return;
756 if (CE->getNumArgs() < 3) {
757 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000758 if (CE->getNumArgs() == 1)
759 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000760 } else if (CE->getNumArgs() == 3) {
761 llvm::Optional<ProgramStateRef> MaybeState =
762 performKernelMalloc(CE, C, State);
763 if (MaybeState.hasValue())
764 State = MaybeState.getValue();
765 else
766 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
767 }
768 } else if (FunI == II_kmalloc) {
769 llvm::Optional<ProgramStateRef> MaybeState =
770 performKernelMalloc(CE, C, State);
771 if (MaybeState.hasValue())
772 State = MaybeState.getValue();
773 else
774 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
775 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000776 if (CE->getNumArgs() < 1)
777 return;
778 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000779 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000780 } else if (FunI == II_realloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000781 State = ReallocMem(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000782 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000783 } else if (FunI == II_reallocf) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000784 State = ReallocMem(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000785 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000786 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000787 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000788 State = ProcessZeroAllocation(C, CE, 0, State);
789 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000790 } else if (FunI == II_free) {
791 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
792 } else if (FunI == II_strdup) {
793 State = MallocUpdateRefState(C, CE, State);
794 } else if (FunI == II_strndup) {
795 State = MallocUpdateRefState(C, CE, State);
Anton Yartsevc38d7952015-03-03 22:58:46 +0000796 } else if (FunI == II_alloca) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000797 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
798 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000799 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000800 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000801 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000802 // as distinct from new/new[]/delete/delete[] expressions that are
803 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000804 // CXXDeleteExpr.
805 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000806 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000807 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
808 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000809 State = ProcessZeroAllocation(C, CE, 0, State);
810 }
811 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000812 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
813 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000814 State = ProcessZeroAllocation(C, CE, 0, State);
815 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000816 else if (K == OO_Delete || K == OO_Array_Delete)
817 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
818 else
819 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000820 } else if (FunI == II_if_nameindex) {
821 // Should we model this differently? We can allocate a fixed number of
822 // elements with zeros in the last one.
823 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
824 AF_IfNameIndex);
825 } else if (FunI == II_if_freenameindex) {
826 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000827 }
828 }
829
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000830 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000831 // Check all the attributes, if there are any.
832 // There can be multiple of these attributes.
833 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000834 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
835 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000836 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000837 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000838 break;
839 case OwnershipAttr::Takes:
840 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000841 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000842 break;
843 }
844 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000845 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000846 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000847}
848
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000849// Performs a 0-sized allocations check.
850ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
851 const Expr *E,
852 const unsigned AllocationSizeArg,
853 ProgramStateRef State) const {
854 if (!State)
855 return nullptr;
856
857 const Expr *Arg = nullptr;
858
859 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
860 Arg = CE->getArg(AllocationSizeArg);
861 }
862 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
863 if (NE->isArray())
864 Arg = NE->getArraySize();
865 else
866 return State;
867 }
868 else
869 llvm_unreachable("not a CallExpr or CXXNewExpr");
870
871 assert(Arg);
872
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000873 Optional<DefinedSVal> DefArgVal =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000874 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
875
876 if (!DefArgVal)
877 return State;
878
879 // Check if the allocation size is 0.
880 ProgramStateRef TrueState, FalseState;
881 SValBuilder &SvalBuilder = C.getSValBuilder();
882 DefinedSVal Zero =
883 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
884
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000885 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000886 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
887
888 if (TrueState && !FalseState) {
889 SVal retVal = State->getSVal(E, C.getLocationContext());
890 SymbolRef Sym = retVal.getAsLocSymbol();
891 if (!Sym)
892 return State;
893
894 const RefState *RS = State->get<RegionState>(Sym);
Devin Coughlin81771732015-09-22 22:47:14 +0000895 if (RS) {
896 if (RS->isAllocated())
897 return TrueState->set<RegionState>(Sym,
898 RefState::getAllocatedOfSizeZero(RS));
899 else
900 return State;
901 } else {
902 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
903 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
904 // tracked. Add zero-reallocated Sym to the state to catch references
905 // to zero-allocated memory.
906 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
907 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000908 }
909
910 // Assume the value is non-zero going forward.
911 assert(FalseState);
912 return FalseState;
913}
914
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000915static QualType getDeepPointeeType(QualType T) {
916 QualType Result = T, PointeeType = T->getPointeeType();
917 while (!PointeeType.isNull()) {
918 Result = PointeeType;
919 PointeeType = PointeeType->getPointeeType();
920 }
921 return Result;
922}
923
924static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
925
926 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
927 if (!ConstructE)
928 return false;
929
930 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
931 return false;
932
933 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
934
935 // Iterate over the constructor parameters.
936 for (const auto *CtorParam : CtorD->params()) {
937
938 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
939 if (CtorParamPointeeT.isNull())
940 continue;
941
942 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
943
944 if (CtorParamPointeeT->getAsCXXRecordDecl())
945 return true;
946 }
947
948 return false;
949}
950
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000951void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
Anton Yartsev13df0362013-03-25 01:35:45 +0000952 CheckerContext &C) const {
953
954 if (NE->getNumPlacementArgs())
955 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
956 E = NE->placement_arg_end(); I != E; ++I)
957 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
958 checkUseAfterFree(Sym, C, *I);
959
Anton Yartsev13df0362013-03-25 01:35:45 +0000960 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
961 return;
962
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000963 ParentMap &PM = C.getLocationContext()->getParentMap();
964 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
965 return;
966
Anton Yartsev13df0362013-03-25 01:35:45 +0000967 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000968 // The return value from operator new is bound to a specified initialization
969 // value (if any) and we don't want to loose this value. So we call
970 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +0000971 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000972 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Anton Yartsev05789592013-03-28 17:05:19 +0000973 : AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000974 State = ProcessZeroAllocation(C, NE, 0, State);
Anton Yartsev13df0362013-03-25 01:35:45 +0000975 C.addTransition(State);
976}
977
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000978void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +0000979 CheckerContext &C) const {
980
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000981 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +0000982 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
983 checkUseAfterFree(Sym, C, DE->getArgument());
984
Anton Yartsev13df0362013-03-25 01:35:45 +0000985 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
986 return;
987
988 ProgramStateRef State = C.getState();
989 bool ReleasedAllocated;
990 State = FreeMemAux(C, DE->getArgument(), DE, State,
991 /*Hold*/false, ReleasedAllocated);
992
993 C.addTransition(State);
994}
995
Jordan Rose613f3c02013-03-09 00:59:10 +0000996static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
997 // If the first selector piece is one of the names below, assume that the
998 // object takes ownership of the memory, promising to eventually deallocate it
999 // with free().
1000 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1001 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1002 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1003 if (FirstSlot == "dataWithBytesNoCopy" ||
1004 FirstSlot == "initWithBytesNoCopy" ||
1005 FirstSlot == "initWithCharactersNoCopy")
1006 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001007
1008 return false;
1009}
1010
Jordan Rose613f3c02013-03-09 00:59:10 +00001011static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1012 Selector S = Call.getSelector();
1013
1014 // FIXME: We should not rely on fully-constrained symbols being folded.
1015 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1016 if (S.getNameForSlot(i).equals("freeWhenDone"))
1017 return !Call.getArgSVal(i).isZeroConstant();
1018
1019 return None;
1020}
1021
Anna Zaks67291b92012-11-13 03:18:01 +00001022void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1023 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001024 if (C.wasInlined)
1025 return;
1026
Jordan Rose613f3c02013-03-09 00:59:10 +00001027 if (!isKnownDeallocObjCMethodName(Call))
1028 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001029
Jordan Rose613f3c02013-03-09 00:59:10 +00001030 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1031 if (!*FreeWhenDone)
1032 return;
1033
1034 bool ReleasedAllocatedMemory;
1035 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1036 Call.getOriginExpr(), C.getState(),
1037 /*Hold=*/true, ReleasedAllocatedMemory,
1038 /*RetNullOnFailure=*/true);
1039
1040 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001041}
1042
Richard Smith852e9ce2013-11-27 01:46:48 +00001043ProgramStateRef
1044MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001045 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001046 ProgramStateRef State) const {
1047 if (!State)
1048 return nullptr;
1049
Richard Smith852e9ce2013-11-27 01:46:48 +00001050 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001051 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001052
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001053 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001054 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001055 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001056 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001057 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1058}
1059
1060ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1061 const CallExpr *CE,
1062 const Expr *SizeEx, SVal Init,
1063 ProgramStateRef State,
1064 AllocationFamily Family) {
1065 if (!State)
1066 return nullptr;
1067
1068 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1069 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001070}
1071
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001072ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001073 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001074 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001075 ProgramStateRef State,
1076 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001077 if (!State)
1078 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001079
Jordan Rosef69e65f2014-09-05 16:33:51 +00001080 // We expect the malloc functions to return a pointer.
1081 if (!Loc::isLocType(CE->getType()))
1082 return nullptr;
1083
Anna Zaks3563fde2012-06-07 03:57:32 +00001084 // Bind the return value to the symbolic value from the heap region.
1085 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1086 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001087 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001088 SValBuilder &svalBuilder = C.getSValBuilder();
1089 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001090 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1091 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001092 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001093
Jordy Rose674bd552010-07-04 00:00:41 +00001094 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +00001095 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001096
Jordy Rose674bd552010-07-04 00:00:41 +00001097 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001098 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001099 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001100 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001101 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001102 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001103 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001104 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001105 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001106 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001107 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001108
Anton Yartsev05789592013-03-28 17:05:19 +00001109 State = State->assume(extentMatchesSize, true);
1110 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001111 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001112
Anton Yartsev05789592013-03-28 17:05:19 +00001113 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001114}
1115
1116ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001117 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001118 ProgramStateRef State,
1119 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001120 if (!State)
1121 return nullptr;
1122
Anna Zaks40a7eb32012-02-22 19:24:52 +00001123 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001124 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001125
1126 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001127 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001128 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001129
Ted Kremenek90af9092010-12-02 07:49:45 +00001130 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001131 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001132
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001133 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001134 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001135}
1136
Anna Zaks40a7eb32012-02-22 19:24:52 +00001137ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1138 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001139 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001140 ProgramStateRef State) const {
1141 if (!State)
1142 return nullptr;
1143
Richard Smith852e9ce2013-11-27 01:46:48 +00001144 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001145 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001146
Anna Zaksfe6eb672012-08-24 02:28:20 +00001147 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001148
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001149 for (const auto &Arg : Att->args()) {
1150 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001151 Att->getOwnKind() == OwnershipAttr::Holds,
1152 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001153 if (StateI)
1154 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001155 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001156 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001157}
1158
Ted Kremenek49b1e382012-01-26 21:29:00 +00001159ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001160 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001161 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001162 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001163 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001164 bool &ReleasedAllocated,
1165 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001166 if (!State)
1167 return nullptr;
1168
Anna Zaksb508d292012-04-10 23:41:11 +00001169 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001170 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001171
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001172 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001173 ReleasedAllocated, ReturnsNullOnFailure);
1174}
1175
Anna Zaksa14c1d02012-11-13 19:47:40 +00001176/// Checks if the previous call to free on the given symbol failed - if free
1177/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001178static bool didPreviousFreeFail(ProgramStateRef State,
1179 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001180 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001181 if (Ret) {
1182 assert(*Ret && "We should not store the null return symbol");
1183 ConstraintManager &CMgr = State->getConstraintManager();
1184 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001185 RetStatusSymbol = *Ret;
1186 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001187 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001188 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001189}
1190
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001191AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001192 const Stmt *S) const {
1193 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001194 return AF_None;
1195
Anton Yartseve3377fb2013-04-04 23:46:29 +00001196 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001197 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001198
1199 if (!FD)
1200 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1201
Anton Yartsev05789592013-03-28 17:05:19 +00001202 ASTContext &Ctx = C.getASTContext();
1203
Anna Zaksd79b8402014-10-03 21:48:59 +00001204 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001205 return AF_Malloc;
1206
1207 if (isStandardNewDelete(FD, Ctx)) {
1208 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001209 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001210 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001211 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001212 return AF_CXXNewArray;
1213 }
1214
Anna Zaksd79b8402014-10-03 21:48:59 +00001215 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1216 return AF_IfNameIndex;
1217
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001218 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1219 return AF_Alloca;
1220
Anton Yartsev05789592013-03-28 17:05:19 +00001221 return AF_None;
1222 }
1223
Anton Yartseve3377fb2013-04-04 23:46:29 +00001224 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1225 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1226
1227 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001228 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1229
Anton Yartseve3377fb2013-04-04 23:46:29 +00001230 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001231 return AF_Malloc;
1232
1233 return AF_None;
1234}
1235
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001236bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001237 const Expr *E) const {
1238 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1239 // FIXME: This doesn't handle indirect calls.
1240 const FunctionDecl *FD = CE->getDirectCallee();
1241 if (!FD)
1242 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001243
Anton Yartsev05789592013-03-28 17:05:19 +00001244 os << *FD;
1245 if (!FD->isOverloadedOperator())
1246 os << "()";
1247 return true;
1248 }
1249
1250 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1251 if (Msg->isInstanceMessage())
1252 os << "-";
1253 else
1254 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001255 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001256 return true;
1257 }
1258
1259 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001260 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001261 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1262 << "'";
1263 return true;
1264 }
1265
1266 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001267 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001268 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1269 << "'";
1270 return true;
1271 }
1272
1273 return false;
1274}
1275
1276void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1277 const Expr *E) const {
1278 AllocationFamily Family = getAllocationFamily(C, E);
1279
1280 switch(Family) {
1281 case AF_Malloc: os << "malloc()"; return;
1282 case AF_CXXNew: os << "'new'"; return;
1283 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001284 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001285 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001286 case AF_None: llvm_unreachable("not a deallocation expression");
1287 }
1288}
1289
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001290void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001291 AllocationFamily Family) const {
1292 switch(Family) {
1293 case AF_Malloc: os << "free()"; return;
1294 case AF_CXXNew: os << "'delete'"; return;
1295 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001296 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001297 case AF_Alloca:
1298 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001299 }
1300}
1301
Anna Zaks0d6989b2012-06-22 02:04:31 +00001302ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1303 const Expr *ArgExpr,
1304 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001305 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001306 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001307 bool &ReleasedAllocated,
1308 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001309
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001310 if (!State)
1311 return nullptr;
1312
Anna Zaks67291b92012-11-13 03:18:01 +00001313 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001314 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001315 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001316 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001317
1318 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001319 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001320 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001321
Anna Zaksad01ef52012-02-14 00:26:13 +00001322 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001323 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001324 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001325 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001326 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001327
Jordy Rose3597b212010-06-07 19:32:37 +00001328 // Unknown values could easily be okay
1329 // Undefined values are handled elsewhere
1330 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001331 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001332
Jordy Rose3597b212010-06-07 19:32:37 +00001333 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001334
Jordy Rose3597b212010-06-07 19:32:37 +00001335 // Nonlocs can't be freed, of course.
1336 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1337 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001338 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001339 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001340 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001341
Jordy Rose3597b212010-06-07 19:32:37 +00001342 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001343
Jordy Rose3597b212010-06-07 19:32:37 +00001344 // Blocks might show up as heap data, but should not be free()d
1345 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001346 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001347 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001348 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001349
Jordy Rose3597b212010-06-07 19:32:37 +00001350 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001351
1352 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001353 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001354 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1355 // FIXME: at the time this code was written, malloc() regions were
1356 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1357 // This means that there isn't actually anything from HeapSpaceRegion
1358 // that should be freed, even though we allow it here.
1359 // Of course, free() can work on memory allocated outside the current
1360 // function, so UnknownSpaceRegion is always a possibility.
1361 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001362
1363 if (isa<AllocaRegion>(R))
1364 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1365 else
1366 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1367
Craig Topper0dbb7832014-05-27 02:45:47 +00001368 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001369 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001370
1371 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001372 // Various cases could lead to non-symbol values here.
1373 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001374 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001375 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001376
Anna Zaksc89ad072013-02-07 23:05:47 +00001377 SymbolRef SymBase = SrBase->getSymbol();
1378 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001379 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001380
Anton Yartseve3377fb2013-04-04 23:46:29 +00001381 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001382
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001383 // Memory returned by alloca() shouldn't be freed.
1384 if (RsBase->getAllocationFamily() == AF_Alloca) {
1385 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1386 return nullptr;
1387 }
1388
Anna Zaks93a21a82013-04-09 00:30:28 +00001389 // Check for double free first.
1390 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001391 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1392 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1393 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001394 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001395
Anna Zaks93a21a82013-04-09 00:30:28 +00001396 // If the pointer is allocated or escaped, but we are now trying to free it,
1397 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001398 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001399 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001400
1401 // Check if an expected deallocation function matches the real one.
1402 bool DeallocMatchesAlloc =
1403 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1404 if (!DeallocMatchesAlloc) {
1405 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001406 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001407 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001408 }
1409
1410 // Check if the memory location being freed is the actual location
1411 // allocated, or an offset.
1412 RegionOffset Offset = R->getAsOffset();
1413 if (Offset.isValid() &&
1414 !Offset.hasSymbolicOffset() &&
1415 Offset.getOffset() != 0) {
1416 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001417 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001418 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001419 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001420 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001421 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001422 }
1423
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001424 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001425 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001426
Anna Zaksa14c1d02012-11-13 19:47:40 +00001427 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001428 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001429
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001430 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001431 // failed.
1432 if (ReturnsNullOnFailure) {
1433 SVal RetVal = C.getSVal(ParentExpr);
1434 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1435 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001436 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1437 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001438 }
1439 }
1440
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001441 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1442 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001443 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001444 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001445 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001446 RefState::getRelinquished(Family,
1447 ParentExpr));
1448
1449 return State->set<RegionState>(SymBase,
1450 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001451}
1452
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001453Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001454MallocChecker::getCheckIfTracked(AllocationFamily Family,
1455 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001456 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001457 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001458 case AF_Alloca:
1459 case AF_IfNameIndex: {
1460 if (ChecksEnabled[CK_MallocChecker])
1461 return CK_MallocChecker;
1462
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001463 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001464 }
1465 case AF_CXXNew:
1466 case AF_CXXNewArray: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001467 if (IsALeakCheck) {
1468 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1469 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001470 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001471 else {
1472 if (ChecksEnabled[CK_NewDeleteChecker])
1473 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001474 }
1475 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001476 }
1477 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001478 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001479 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001480 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001481 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001482}
1483
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001484Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001485MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001486 const Stmt *AllocDeallocStmt,
1487 bool IsALeakCheck) const {
1488 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1489 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001490}
1491
1492Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001493MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1494 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001495 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1496 return CK_MallocChecker;
1497
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001498 const RefState *RS = C.getState()->get<RegionState>(Sym);
1499 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001500 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001501}
1502
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001503bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001504 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001505 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001506 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001507 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001508 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001509 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001510 else
1511 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001512
Jordy Rose3597b212010-06-07 19:32:37 +00001513 return true;
1514}
1515
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001516bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001517 const MemRegion *MR) {
1518 switch (MR->getKind()) {
1519 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001520 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001521 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001522 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001523 else
1524 os << "the address of a function";
1525 return true;
1526 }
1527 case MemRegion::BlockTextRegionKind:
1528 os << "block text";
1529 return true;
1530 case MemRegion::BlockDataRegionKind:
1531 // FIXME: where the block came from?
1532 os << "a block";
1533 return true;
1534 default: {
1535 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001536
Anna Zaks8158ef02012-01-04 23:54:01 +00001537 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001538 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1539 const VarDecl *VD;
1540 if (VR)
1541 VD = VR->getDecl();
1542 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001543 VD = nullptr;
1544
Jordy Rose3597b212010-06-07 19:32:37 +00001545 if (VD)
1546 os << "the address of the local variable '" << VD->getName() << "'";
1547 else
1548 os << "the address of a local stack variable";
1549 return true;
1550 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001551
1552 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001553 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1554 const VarDecl *VD;
1555 if (VR)
1556 VD = VR->getDecl();
1557 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001558 VD = nullptr;
1559
Jordy Rose3597b212010-06-07 19:32:37 +00001560 if (VD)
1561 os << "the address of the parameter '" << VD->getName() << "'";
1562 else
1563 os << "the address of a parameter";
1564 return true;
1565 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001566
1567 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001568 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1569 const VarDecl *VD;
1570 if (VR)
1571 VD = VR->getDecl();
1572 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001573 VD = nullptr;
1574
Jordy Rose3597b212010-06-07 19:32:37 +00001575 if (VD) {
1576 if (VD->isStaticLocal())
1577 os << "the address of the static variable '" << VD->getName() << "'";
1578 else
1579 os << "the address of the global variable '" << VD->getName() << "'";
1580 } else
1581 os << "the address of a global variable";
1582 return true;
1583 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001584
1585 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001586 }
1587 }
1588}
1589
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001590void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1591 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001592 const Expr *DeallocExpr) const {
1593
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001594 if (!ChecksEnabled[CK_MallocChecker] &&
1595 !ChecksEnabled[CK_NewDeleteChecker])
1596 return;
1597
1598 Optional<MallocChecker::CheckKind> CheckKind =
1599 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001600 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001601 return;
1602
Devin Coughline39bd402015-09-16 22:03:05 +00001603 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001604 if (!BT_BadFree[*CheckKind])
1605 BT_BadFree[*CheckKind].reset(
1606 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1607
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001608 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001609 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001610
Jordy Rose3597b212010-06-07 19:32:37 +00001611 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001612 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1613 MR = ER->getSuperRegion();
1614
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001615 os << "Argument to ";
1616 if (!printAllocDeallocName(os, C, DeallocExpr))
1617 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001618
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001619 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001620 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001621 : SummarizeValue(os, ArgVal);
1622 if (Summarized)
1623 os << ", which is not memory allocated by ";
1624 else
1625 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001626
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001627 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001628
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001629 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001630 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001631 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001632 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001633 }
1634}
1635
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001636void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001637 SourceRange Range) const {
1638
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001639 Optional<MallocChecker::CheckKind> CheckKind;
1640
1641 if (ChecksEnabled[CK_MallocChecker])
1642 CheckKind = CK_MallocChecker;
1643 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1644 CheckKind = CK_MismatchedDeallocatorChecker;
1645 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001646 return;
1647
Devin Coughline39bd402015-09-16 22:03:05 +00001648 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001649 if (!BT_FreeAlloca[*CheckKind])
1650 BT_FreeAlloca[*CheckKind].reset(
1651 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1652
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001653 auto R = llvm::make_unique<BugReport>(
1654 *BT_FreeAlloca[*CheckKind],
1655 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001656 R->markInteresting(ArgVal.getAsRegion());
1657 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001658 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001659 }
1660}
1661
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001662void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001663 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001664 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001665 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001666 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001667 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001668
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001669 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001670 return;
1671
Devin Coughline39bd402015-09-16 22:03:05 +00001672 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001673 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001674 BT_MismatchedDealloc.reset(
1675 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1676 "Bad deallocator", "Memory Error"));
1677
Anton Yartsev05789592013-03-28 17:05:19 +00001678 SmallString<100> buf;
1679 llvm::raw_svector_ostream os(buf);
1680
1681 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1682 SmallString<20> AllocBuf;
1683 llvm::raw_svector_ostream AllocOs(AllocBuf);
1684 SmallString<20> DeallocBuf;
1685 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1686
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001687 if (OwnershipTransferred) {
1688 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1689 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001690 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001691 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001692
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001693 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001694
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001695 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1696 os << " allocated by " << AllocOs.str();
1697 } else {
1698 os << "Memory";
1699 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1700 os << " allocated by " << AllocOs.str();
1701
1702 os << " should be deallocated by ";
1703 printExpectedDeallocName(os, RS->getAllocationFamily());
1704
1705 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1706 os << ", not " << DeallocOs.str();
1707 }
Anton Yartsev05789592013-03-28 17:05:19 +00001708
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001709 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001710 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001711 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001712 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001713 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001714 }
1715}
1716
Anna Zaksc89ad072013-02-07 23:05:47 +00001717void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001718 SourceRange Range, const Expr *DeallocExpr,
1719 const Expr *AllocExpr) const {
1720
Anton Yartsev05789592013-03-28 17:05:19 +00001721
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001722 if (!ChecksEnabled[CK_MallocChecker] &&
1723 !ChecksEnabled[CK_NewDeleteChecker])
1724 return;
1725
1726 Optional<MallocChecker::CheckKind> CheckKind =
1727 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001728 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001729 return;
1730
Devin Coughline39bd402015-09-16 22:03:05 +00001731 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001732 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001733 return;
1734
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001735 if (!BT_OffsetFree[*CheckKind])
1736 BT_OffsetFree[*CheckKind].reset(
1737 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001738
1739 SmallString<100> buf;
1740 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001741 SmallString<20> AllocNameBuf;
1742 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001743
1744 const MemRegion *MR = ArgVal.getAsRegion();
1745 assert(MR && "Only MemRegion based symbols can have offset free errors");
1746
1747 RegionOffset Offset = MR->getAsOffset();
1748 assert((Offset.isValid() &&
1749 !Offset.hasSymbolicOffset() &&
1750 Offset.getOffset() != 0) &&
1751 "Only symbols with a valid offset can have offset free errors");
1752
1753 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1754
Anton Yartsev05789592013-03-28 17:05:19 +00001755 os << "Argument to ";
1756 if (!printAllocDeallocName(os, C, DeallocExpr))
1757 os << "deallocator";
1758 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001759 << offsetBytes
1760 << " "
1761 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001762 << " from the start of ";
1763 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1764 os << "memory allocated by " << AllocNameOs.str();
1765 else
1766 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001767
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001768 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001769 R->markInteresting(MR->getBaseRegion());
1770 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001771 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001772}
1773
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001774void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1775 SymbolRef Sym) const {
1776
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001777 if (!ChecksEnabled[CK_MallocChecker] &&
1778 !ChecksEnabled[CK_NewDeleteChecker])
1779 return;
1780
1781 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001782 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001783 return;
1784
Devin Coughline39bd402015-09-16 22:03:05 +00001785 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001786 if (!BT_UseFree[*CheckKind])
1787 BT_UseFree[*CheckKind].reset(new BugType(
1788 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001789
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001790 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1791 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001792
1793 R->markInteresting(Sym);
1794 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001795 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001796 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001797 }
1798}
1799
1800void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001801 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001802 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001803
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001804 if (!ChecksEnabled[CK_MallocChecker] &&
1805 !ChecksEnabled[CK_NewDeleteChecker])
1806 return;
1807
1808 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001809 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001810 return;
1811
Devin Coughline39bd402015-09-16 22:03:05 +00001812 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001813 if (!BT_DoubleFree[*CheckKind])
1814 BT_DoubleFree[*CheckKind].reset(
1815 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001816
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001817 auto R = llvm::make_unique<BugReport>(
1818 *BT_DoubleFree[*CheckKind],
1819 (Released ? "Attempt to free released memory"
1820 : "Attempt to free non-owned memory"),
1821 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001822 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001823 R->markInteresting(Sym);
1824 if (PrevSym)
1825 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001826 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001827 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001828 }
1829}
1830
Jordan Rose656fdd52014-01-08 18:46:55 +00001831void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1832
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001833 if (!ChecksEnabled[CK_NewDeleteChecker])
1834 return;
1835
1836 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001837 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001838 return;
1839
Devin Coughline39bd402015-09-16 22:03:05 +00001840 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00001841 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001842 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1843 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001844
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001845 auto R = llvm::make_unique<BugReport>(
1846 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00001847
1848 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001849 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001850 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00001851 }
1852}
1853
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001854void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1855 SourceRange Range,
1856 SymbolRef Sym) const {
1857
1858 if (!ChecksEnabled[CK_MallocChecker] &&
1859 !ChecksEnabled[CK_NewDeleteChecker])
1860 return;
1861
1862 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1863
1864 if (!CheckKind.hasValue())
1865 return;
1866
Devin Coughline39bd402015-09-16 22:03:05 +00001867 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001868 if (!BT_UseZerroAllocated[*CheckKind])
1869 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
1870 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
1871
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001872 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
1873 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001874
1875 R->addRange(Range);
1876 if (Sym) {
1877 R->markInteresting(Sym);
1878 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1879 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001880 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001881 }
1882}
1883
Anna Zaks40a7eb32012-02-22 19:24:52 +00001884ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1885 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001886 bool FreesOnFail,
1887 ProgramStateRef State) const {
1888 if (!State)
1889 return nullptr;
1890
Anna Zaksb508d292012-04-10 23:41:11 +00001891 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001892 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001893
Ted Kremenek90af9092010-12-02 07:49:45 +00001894 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001895 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001896 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001897 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001898 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001899 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001900
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001901 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001902
Ted Kremenek90af9092010-12-02 07:49:45 +00001903 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001904 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001905
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001906 // Get the size argument. If there is no size arg then give up.
1907 const Expr *Arg1 = CE->getArg(1);
1908 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00001909 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001910
1911 // Get the value of the size argument.
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001912 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001913 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001914 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001915 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001916
1917 // Compare the size argument to 0.
1918 DefinedOrUnknownSVal SizeZero =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001919 svalBuilder.evalEQ(State, Arg1Val,
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001920 svalBuilder.makeIntValWithPtrWidth(0, false));
1921
Anna Zaksd56c8792012-02-13 18:05:39 +00001922 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001923 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001924 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001925 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001926 // We only assume exceptional states if they are definitely true; if the
1927 // state is under-constrained, assume regular realloc behavior.
1928 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1929 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1930
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001931 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001932 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001933 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001934 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001935 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001936 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001937 }
1938
Anna Zaksd56c8792012-02-13 18:05:39 +00001939 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00001940 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001941
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001942 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001943 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001944 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001945 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001946 SymbolRef ToPtr = RetVal.getAsSymbol();
1947 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00001948 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00001949
Anna Zaksfe6eb672012-08-24 02:28:20 +00001950 bool ReleasedAllocated = false;
1951
Anna Zaksd56c8792012-02-13 18:05:39 +00001952 // If the size is 0, free the memory.
1953 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001954 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1955 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001956 // The semantics of the return value are:
1957 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001958 // to free() is returned. We just free the input pointer and do not add
1959 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001960 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001961 }
1962
1963 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001964 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001965 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00001966
Anna Zaksd56c8792012-02-13 18:05:39 +00001967 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1968 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001969 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001970 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001971
Anna Zaks75cfbb62012-09-12 22:57:34 +00001972 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1973 if (FreesOnFail)
1974 Kind = RPIsFreeOnFailure;
1975 else if (!ReleasedAllocated)
1976 Kind = RPDoNotTrackAfterFailure;
1977
Anna Zaksfe6eb672012-08-24 02:28:20 +00001978 // Record the info about the reallocated symbol so that we could properly
1979 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001980 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001981 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001982 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001983 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001984 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001985 }
Craig Topper0dbb7832014-05-27 02:45:47 +00001986 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001987}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001988
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001989ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001990 ProgramStateRef State) {
1991 if (!State)
1992 return nullptr;
1993
Anna Zaksb508d292012-04-10 23:41:11 +00001994 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001995 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001996
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001997 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001998 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001999 SVal count = State->getSVal(CE->getArg(0), LCtx);
2000 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
2001 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002002 svalBuilder.getContext().getSizeType());
Ted Kremenek90af9092010-12-02 07:49:45 +00002003 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002004
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002005 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002006}
2007
Anna Zaksfc2e1532012-03-21 19:45:08 +00002008LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002009MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2010 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002011 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002012 // Walk the ExplodedGraph backwards and find the first node that referred to
2013 // the tracked symbol.
2014 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002015 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002016
2017 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002018 ProgramStateRef State = N->getState();
2019 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002020 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002021
2022 // Find the most recent expression bound to the symbol in the current
2023 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002024 if (!ReferenceRegion) {
2025 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2026 SVal Val = State->getSVal(MR);
2027 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002028 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002029 // Do not show local variables belonging to a function other than
2030 // where the error is reported.
2031 if (!VR ||
2032 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2033 ReferenceRegion = MR;
2034 }
2035 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002036 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002037
Anna Zaks486a0ff2015-02-05 01:02:53 +00002038 // Allocation node, is the last node in the current or parent context in
2039 // which the symbol was tracked.
2040 const LocationContext *NContext = N->getLocationContext();
2041 if (NContext == LeakContext ||
2042 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002043 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002044 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002045 }
2046
Anna Zaksa043d0c2013-01-08 00:25:29 +00002047 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002048}
2049
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002050void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2051 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002052
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002053 if (!ChecksEnabled[CK_MallocChecker] &&
2054 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002055 return;
2056
Anton Yartsev9907fc92015-03-04 23:18:21 +00002057 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002058 assert(RS && "cannot leak an untracked symbol");
2059 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002060
2061 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002062 return;
2063
Anton Yartsev2487dd62015-03-10 22:24:21 +00002064 Optional<MallocChecker::CheckKind>
2065 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002066
Anton Yartsev2487dd62015-03-10 22:24:21 +00002067 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002068 return;
2069
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002070 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002071 if (!BT_Leak[*CheckKind]) {
2072 BT_Leak[*CheckKind].reset(
2073 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002074 // Leaks should not be reported if they are post-dominated by a sink:
2075 // (1) Sinks are higher importance bugs.
2076 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2077 // with __noreturn functions such as assert() or exit(). We choose not
2078 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002079 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002080 }
2081
Anna Zaksdf901a42012-02-23 21:38:21 +00002082 // Most bug reports are cached at the location where they occurred.
2083 // With leaks, we want to unique them by the location where they were
2084 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002085 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002086 const ExplodedNode *AllocNode = nullptr;
2087 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002088 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002089
Anna Zaksa043d0c2013-01-08 00:25:29 +00002090 ProgramPoint P = AllocNode->getLocation();
Craig Topper0dbb7832014-05-27 02:45:47 +00002091 const Stmt *AllocationStmt = nullptr;
David Blaikie87396b92013-02-21 22:23:56 +00002092 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00002093 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002094 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00002095 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00002096 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002097 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2098 C.getSourceManager(),
2099 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002100
Anna Zaksfc2e1532012-03-21 19:45:08 +00002101 SmallString<200> buf;
2102 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002103 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002104 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002105 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002106 } else {
2107 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002108 }
2109
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002110 auto R = llvm::make_unique<BugReport>(
2111 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2112 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002113 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002114 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002115 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002116}
2117
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002118void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2119 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002120{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002121 if (!SymReaper.hasDeadSymbols())
2122 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002123
Ted Kremenek49b1e382012-01-26 21:29:00 +00002124 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002125 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002126 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002127
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002128 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002129 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2130 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002131 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002132 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002133 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002134 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002135
Zhongxing Xuc7460962009-11-13 07:48:11 +00002136 }
2137 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002138
Anna Zaksd56c8792012-02-13 18:05:39 +00002139 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002140 ReallocPairsTy RP = state->get<ReallocPairs>();
2141 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002142 if (SymReaper.isDead(I->first) ||
2143 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002144 state = state->remove<ReallocPairs>(I->first);
2145 }
2146 }
2147
Anna Zaks67291b92012-11-13 03:18:01 +00002148 // Cleanup the FreeReturnValue Map.
2149 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2150 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2151 if (SymReaper.isDead(I->first) ||
2152 SymReaper.isDead(I->second)) {
2153 state = state->remove<FreeReturnValue>(I->first);
2154 }
2155 }
2156
Anna Zaksdf901a42012-02-23 21:38:21 +00002157 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002158 ExplodedNode *N = C.getPredecessor();
2159 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002160 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002161 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2162 if (N) {
2163 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002164 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002165 reportLeak(*I, N, C);
2166 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002167 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002168 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002169
Anna Zaksdf901a42012-02-23 21:38:21 +00002170 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002171}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002172
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002173void MallocChecker::checkPreCall(const CallEvent &Call,
2174 CheckerContext &C) const {
2175
Jordan Rose656fdd52014-01-08 18:46:55 +00002176 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2177 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2178 if (!Sym || checkDoubleDelete(Sym, C))
2179 return;
2180 }
2181
Anna Zaks46d01602012-05-18 01:16:10 +00002182 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002183 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2184 const FunctionDecl *FD = FC->getDecl();
2185 if (!FD)
2186 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002187
Anna Zaksd79b8402014-10-03 21:48:59 +00002188 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002189 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002190 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2191 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2192 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002193 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002194
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002195 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002196 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002197 return;
2198 }
2199
2200 // Check if the callee of a method is deleted.
2201 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2202 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2203 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2204 return;
2205 }
2206
2207 // Check arguments for being used after free.
2208 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2209 SVal ArgSVal = Call.getArgSVal(I);
2210 if (ArgSVal.getAs<Loc>()) {
2211 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002212 if (!Sym)
2213 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002214 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002215 return;
2216 }
2217 }
2218}
2219
Anna Zaksa1b227b2012-02-08 23:16:56 +00002220void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2221 const Expr *E = S->getRetValue();
2222 if (!E)
2223 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002224
2225 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002226 ProgramStateRef State = C.getState();
2227 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002228 SymbolRef Sym = RetVal.getAsSymbol();
2229 if (!Sym)
2230 // If we are returning a field of the allocated struct or an array element,
2231 // the callee could still free the memory.
2232 // TODO: This logic should be a part of generic symbol escape callback.
2233 if (const MemRegion *MR = RetVal.getAsRegion())
2234 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2235 if (const SymbolicRegion *BMR =
2236 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2237 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002238
Anna Zaks3aa52252012-02-11 21:44:39 +00002239 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002240 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002241 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002242}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002243
Anna Zaks9fe80982012-03-22 00:57:20 +00002244// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002245// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002246// needed.
2247void MallocChecker::checkPostStmt(const BlockExpr *BE,
2248 CheckerContext &C) const {
2249
2250 // Scan the BlockDecRefExprs for any object the retain count checker
2251 // may be tracking.
2252 if (!BE->getBlockDecl()->hasCaptures())
2253 return;
2254
2255 ProgramStateRef state = C.getState();
2256 const BlockDataRegion *R =
2257 cast<BlockDataRegion>(state->getSVal(BE,
2258 C.getLocationContext()).getAsRegion());
2259
2260 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2261 E = R->referenced_vars_end();
2262
2263 if (I == E)
2264 return;
2265
2266 SmallVector<const MemRegion*, 10> Regions;
2267 const LocationContext *LC = C.getLocationContext();
2268 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2269
2270 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002271 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002272 if (VR->getSuperRegion() == R) {
2273 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2274 }
2275 Regions.push_back(VR);
2276 }
2277
2278 state =
2279 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2280 Regions.data() + Regions.size()).getState();
2281 C.addTransition(state);
2282}
2283
Anna Zaks46d01602012-05-18 01:16:10 +00002284bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002285 assert(Sym);
2286 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002287 return (RS && RS->isReleased());
2288}
2289
2290bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2291 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002292
Jordan Rose656fdd52014-01-08 18:46:55 +00002293 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002294 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2295 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002296 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002297
Anna Zaksa1b227b2012-02-08 23:16:56 +00002298 return false;
2299}
2300
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002301void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2302 const Stmt *S) const {
2303 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002304
Devin Coughlin81771732015-09-22 22:47:14 +00002305 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2306 if (RS->isAllocatedOfSizeZero())
2307 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2308 }
2309 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2310 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2311 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002312}
2313
Jordan Rose656fdd52014-01-08 18:46:55 +00002314bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2315
2316 if (isReleased(Sym, C)) {
2317 ReportDoubleDelete(C, Sym);
2318 return true;
2319 }
2320 return false;
2321}
2322
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002323// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002324void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2325 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002326 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002327 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002328 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002329 checkUseZeroAllocated(Sym, C, S);
2330 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002331}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002332
Anna Zaksbb1ef902012-02-11 21:02:35 +00002333// If a symbolic region is assumed to NULL (or another constant), stop tracking
2334// it - assuming that allocation failed on this path.
2335ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2336 SVal Cond,
2337 bool Assumption) const {
2338 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002339 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002340 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002341 ConstraintManager &CMgr = state->getConstraintManager();
2342 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2343 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002344 state = state->remove<RegionState>(I.getKey());
2345 }
2346
Anna Zaksd56c8792012-02-13 18:05:39 +00002347 // Realloc returns 0 when reallocation fails, which means that we should
2348 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002349 ReallocPairsTy RP = state->get<ReallocPairs>();
2350 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002351 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002352 ConstraintManager &CMgr = state->getConstraintManager();
2353 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002354 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002355 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002356
Anna Zaks75cfbb62012-09-12 22:57:34 +00002357 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2358 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2359 if (RS->isReleased()) {
2360 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002361 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002362 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002363 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2364 state = state->remove<RegionState>(ReallocSym);
2365 else
2366 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002367 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002368 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002369 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002370 }
2371
Anna Zaksbb1ef902012-02-11 21:02:35 +00002372 return state;
2373}
2374
Anna Zaks8ebeb642013-06-08 00:29:29 +00002375bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002376 const CallEvent *Call,
2377 ProgramStateRef State,
2378 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002379 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002380 EscapingSymbol = nullptr;
2381
Jordan Rose2a833ca2014-01-15 17:25:15 +00002382 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002383 // TODO: If we want to be more optimistic here, we'll need to make sure that
2384 // regions escape to C++ containers. They seem to do that even now, but for
2385 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002386 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002387 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002388
Jordan Rose742920c2012-07-02 19:27:35 +00002389 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002390 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002391 // If it's not a framework call, or if it takes a callback, assume it
2392 // can free memory.
2393 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002394 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002395
Jordan Rose613f3c02013-03-09 00:59:10 +00002396 // If it's a method we know about, handle it explicitly post-call.
2397 // This should happen before the "freeWhenDone" check below.
2398 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002399 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002400
Jordan Rose613f3c02013-03-09 00:59:10 +00002401 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2402 // about, we can't be sure that the object will use free() to deallocate the
2403 // memory, so we can't model it explicitly. The best we can do is use it to
2404 // decide whether the pointer escapes.
2405 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002406 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002407
Jordan Rose613f3c02013-03-09 00:59:10 +00002408 // If the first selector piece ends with "NoCopy", and there is no
2409 // "freeWhenDone" parameter set to zero, we know ownership is being
2410 // transferred. Again, though, we can't be sure that the object will use
2411 // free() to deallocate the memory, so we can't model it explicitly.
2412 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002413 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002414 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002415
Anna Zaks42908c72012-06-19 05:10:32 +00002416 // If the first selector starts with addPointer, insertPointer,
2417 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2418 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002419 // that the pointers get freed by following the container itself.
2420 if (FirstSlot.startswith("addPointer") ||
2421 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002422 FirstSlot.startswith("replacePointer") ||
2423 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002424 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002425 }
2426
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002427 // We should escape receiver on call to 'init'. This is especially relevant
2428 // to the receiver, as the corresponding symbol is usually not referenced
2429 // after the call.
2430 if (Msg->getMethodFamily() == OMF_init) {
2431 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2432 return true;
2433 }
Anna Zaks737926b2013-05-31 22:39:13 +00002434
Jordan Rose742920c2012-07-02 19:27:35 +00002435 // Otherwise, assume that the method does not free memory.
2436 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002437 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002438 }
2439
Jordan Rose742920c2012-07-02 19:27:35 +00002440 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002441 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002442 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002443 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002444
Jordan Rose742920c2012-07-02 19:27:35 +00002445 ASTContext &ASTC = State->getStateManager().getContext();
2446
2447 // If it's one of the allocation functions we can reason about, we model
2448 // its behavior explicitly.
2449 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002450 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002451
2452 // If it's not a system call, assume it frees memory.
2453 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002454 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002455
2456 // White list the system functions whose arguments escape.
2457 const IdentifierInfo *II = FD->getIdentifier();
2458 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002459 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002460 StringRef FName = II->getName();
2461
Jordan Rose742920c2012-07-02 19:27:35 +00002462 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002463 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002464 if (FName.endswith("NoCopy")) {
2465 // Look for the deallocator argument. We know that the memory ownership
2466 // is not transferred only if the deallocator argument is
2467 // 'kCFAllocatorNull'.
2468 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2469 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2470 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2471 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2472 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002473 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002474 }
2475 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002476 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002477 }
2478
Jordan Rose742920c2012-07-02 19:27:35 +00002479 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002480 // 'closefn' is specified (and if that function does free memory),
2481 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002482 // Currently, we do not inspect the 'closefn' function (PR12101).
2483 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002484 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002485 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002486
2487 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2488 // these leaks might be intentional when setting the buffer for stdio.
2489 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2490 if (FName == "setbuf" || FName =="setbuffer" ||
2491 FName == "setlinebuf" || FName == "setvbuf") {
2492 if (Call->getNumArgs() >= 1) {
2493 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2494 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2495 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2496 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002497 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002498 }
2499 }
2500
2501 // A bunch of other functions which either take ownership of a pointer or
2502 // wrap the result up in a struct or object, meaning it can be freed later.
2503 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2504 // but the Malloc checker cannot differentiate between them. The right way
2505 // of doing this would be to implement a pointer escapes callback.
2506 if (FName == "CGBitmapContextCreate" ||
2507 FName == "CGBitmapContextCreateWithData" ||
2508 FName == "CVPixelBufferCreateWithBytes" ||
2509 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2510 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002511 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002512 }
2513
Jordan Rose7ab01822012-07-02 19:27:51 +00002514 // Handle cases where we know a buffer's /address/ can escape.
2515 // Note that the above checks handle some special cases where we know that
2516 // even though the address escapes, it's still our responsibility to free the
2517 // buffer.
2518 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002519 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002520
2521 // Otherwise, assume that the function does not free memory.
2522 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002523 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002524}
2525
Anna Zaks333481b2013-03-28 23:15:29 +00002526static bool retTrue(const RefState *RS) {
2527 return true;
2528}
2529
2530static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2531 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2532 RS->getAllocationFamily() == AF_CXXNew);
2533}
2534
Anna Zaksdc154152012-12-20 00:38:25 +00002535ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2536 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002537 const CallEvent *Call,
2538 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002539 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2540}
2541
2542ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2543 const InvalidatedSymbols &Escaped,
2544 const CallEvent *Call,
2545 PointerEscapeKind Kind) const {
2546 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2547 &checkIfNewOrNewArrayFamily);
2548}
2549
2550ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2551 const InvalidatedSymbols &Escaped,
2552 const CallEvent *Call,
2553 PointerEscapeKind Kind,
2554 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002555 // If we know that the call does not free memory, or we want to process the
2556 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002557 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002558 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002559 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2560 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002561 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002562 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002563 }
Anna Zaks3d348342012-02-14 21:55:24 +00002564
Anna Zaksdc154152012-12-20 00:38:25 +00002565 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002566 E = Escaped.end();
2567 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002568 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002569
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002570 if (EscapingSymbol && EscapingSymbol != sym)
2571 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002572
Anna Zaks0d6989b2012-06-22 02:04:31 +00002573 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002574 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2575 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002576 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002577 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2578 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002579 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002580 }
Anna Zaks3d348342012-02-14 21:55:24 +00002581 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002582}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002583
Jordy Rosebf38f202012-03-18 07:43:35 +00002584static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2585 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002586 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2587 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002588
Jordan Rose0c153cb2012-11-02 01:54:06 +00002589 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002590 I != E; ++I) {
2591 SymbolRef sym = I.getKey();
2592 if (!currMap.lookup(sym))
2593 return sym;
2594 }
2595
Craig Topper0dbb7832014-05-27 02:45:47 +00002596 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002597}
2598
Anna Zaks2b5bb972012-02-09 06:25:51 +00002599PathDiagnosticPiece *
2600MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2601 const ExplodedNode *PrevN,
2602 BugReporterContext &BRC,
2603 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002604 ProgramStateRef state = N->getState();
2605 ProgramStateRef statePrev = PrevN->getState();
2606
2607 const RefState *RS = state->get<RegionState>(Sym);
2608 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002609 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002610 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002611
Craig Topper0dbb7832014-05-27 02:45:47 +00002612 const Stmt *S = nullptr;
2613 const char *Msg = nullptr;
2614 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002615
2616 // Retrieve the associated statement.
2617 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002618 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002619 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002620 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002621 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002622 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002623 // If an assumption was made on a branch, it should be caught
2624 // here by looking at the state transition.
2625 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002626 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002627
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002628 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002629 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002630
Jordan Rose681cce92012-07-10 22:07:42 +00002631 // FIXME: We will eventually need to handle non-statement-based events
2632 // (__attribute__((cleanup))).
2633
Anna Zaks2b5bb972012-02-09 06:25:51 +00002634 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002635 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002636 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002637 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002638 StackHint = new StackHintGeneratorForSymbol(Sym,
2639 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002640 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002641 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002642 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002643 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002644 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002645 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002646 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002647 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002648 Mode = ReallocationFailed;
2649 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002650 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002651 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002652
Jordy Rose21ff76e2012-03-24 03:15:09 +00002653 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2654 // Is it possible to fail two reallocs WITHOUT testing in between?
2655 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2656 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002657 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002658 FailedReallocSymbol = sym;
2659 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002660 }
2661
2662 // We are in a special mode if a reallocation failed later in the path.
2663 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002664 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002665
Jordy Rose21ff76e2012-03-24 03:15:09 +00002666 // Is this is the first appearance of the reallocated symbol?
2667 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002668 // We're at the reallocation point.
2669 Msg = "Attempt to reallocate memory";
2670 StackHint = new StackHintGeneratorForSymbol(Sym,
2671 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002672 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002673 Mode = Normal;
2674 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002675 }
2676
Anna Zaks2b5bb972012-02-09 06:25:51 +00002677 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002678 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002679 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002680
2681 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002682 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002683 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002684 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002685}
2686
Anna Zaks263b7e02012-05-02 00:05:20 +00002687void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2688 const char *NL, const char *Sep) const {
2689
2690 RegionStateTy RS = State->get<RegionState>();
2691
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002692 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002693 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002694 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002695 const RefState *RefS = State->get<RegionState>(I.getKey());
2696 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002697 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002698 if (!CheckKind.hasValue())
2699 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002700
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002701 I.getKey()->dumpToStream(Out);
2702 Out << " : ";
2703 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002704 if (CheckKind.hasValue())
2705 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002706 Out << NL;
2707 }
2708 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002709}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002710
Anna Zakse4cfcd42013-04-16 00:22:55 +00002711void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2712 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002713 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002714 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2715 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002716 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2717 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2718 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002719 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00002720 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002721 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002722 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002723}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002724
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002725#define REGISTER_CHECKER(name) \
2726 void ento::register##name(CheckerManager &mgr) { \
2727 registerCStringCheckerBasic(mgr); \
2728 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002729 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2730 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002731 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2732 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2733 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002734
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002735REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002736REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002737REGISTER_CHECKER(MismatchedDeallocatorChecker)