blob: fee030feb6d20e5c1fd29a745ec8e6c243de9ad0 [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);
Alexander Kornienko9c104902015-12-28 13:06:58 +00001003 return FirstSlot == "dataWithBytesNoCopy" ||
1004 FirstSlot == "initWithBytesNoCopy" ||
1005 FirstSlot == "initWithCharactersNoCopy";
Anna Zaks0d6989b2012-06-22 02:04:31 +00001006}
1007
Jordan Rose613f3c02013-03-09 00:59:10 +00001008static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1009 Selector S = Call.getSelector();
1010
1011 // FIXME: We should not rely on fully-constrained symbols being folded.
1012 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1013 if (S.getNameForSlot(i).equals("freeWhenDone"))
1014 return !Call.getArgSVal(i).isZeroConstant();
1015
1016 return None;
1017}
1018
Anna Zaks67291b92012-11-13 03:18:01 +00001019void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1020 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001021 if (C.wasInlined)
1022 return;
1023
Jordan Rose613f3c02013-03-09 00:59:10 +00001024 if (!isKnownDeallocObjCMethodName(Call))
1025 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001026
Jordan Rose613f3c02013-03-09 00:59:10 +00001027 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1028 if (!*FreeWhenDone)
1029 return;
1030
1031 bool ReleasedAllocatedMemory;
1032 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1033 Call.getOriginExpr(), C.getState(),
1034 /*Hold=*/true, ReleasedAllocatedMemory,
1035 /*RetNullOnFailure=*/true);
1036
1037 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001038}
1039
Richard Smith852e9ce2013-11-27 01:46:48 +00001040ProgramStateRef
1041MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001042 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001043 ProgramStateRef State) const {
1044 if (!State)
1045 return nullptr;
1046
Richard Smith852e9ce2013-11-27 01:46:48 +00001047 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001048 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001049
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001050 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001051 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001052 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001053 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001054 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1055}
1056
1057ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1058 const CallExpr *CE,
1059 const Expr *SizeEx, SVal Init,
1060 ProgramStateRef State,
1061 AllocationFamily Family) {
1062 if (!State)
1063 return nullptr;
1064
1065 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1066 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001067}
1068
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001069ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001070 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001071 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001072 ProgramStateRef State,
1073 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001074 if (!State)
1075 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001076
Jordan Rosef69e65f2014-09-05 16:33:51 +00001077 // We expect the malloc functions to return a pointer.
1078 if (!Loc::isLocType(CE->getType()))
1079 return nullptr;
1080
Anna Zaks3563fde2012-06-07 03:57:32 +00001081 // Bind the return value to the symbolic value from the heap region.
1082 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1083 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001084 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001085 SValBuilder &svalBuilder = C.getSValBuilder();
1086 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001087 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1088 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001089 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001090
Jordy Rose674bd552010-07-04 00:00:41 +00001091 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +00001092 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001093
Jordy Rose674bd552010-07-04 00:00:41 +00001094 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001095 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001096 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001097 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001098 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001099 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001100 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001101 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001102 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001103 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001104 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001105
Anton Yartsev05789592013-03-28 17:05:19 +00001106 State = State->assume(extentMatchesSize, true);
1107 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001108 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001109
Anton Yartsev05789592013-03-28 17:05:19 +00001110 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001111}
1112
1113ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001114 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001115 ProgramStateRef State,
1116 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001117 if (!State)
1118 return nullptr;
1119
Anna Zaks40a7eb32012-02-22 19:24:52 +00001120 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001121 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001122
1123 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001124 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001125 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001126
Ted Kremenek90af9092010-12-02 07:49:45 +00001127 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001128 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001129
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001130 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001131 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001132}
1133
Anna Zaks40a7eb32012-02-22 19:24:52 +00001134ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1135 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001136 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001137 ProgramStateRef State) const {
1138 if (!State)
1139 return nullptr;
1140
Richard Smith852e9ce2013-11-27 01:46:48 +00001141 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001142 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001143
Anna Zaksfe6eb672012-08-24 02:28:20 +00001144 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001145
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001146 for (const auto &Arg : Att->args()) {
1147 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001148 Att->getOwnKind() == OwnershipAttr::Holds,
1149 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001150 if (StateI)
1151 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001152 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001153 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001154}
1155
Ted Kremenek49b1e382012-01-26 21:29:00 +00001156ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001157 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001158 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001159 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001160 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001161 bool &ReleasedAllocated,
1162 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001163 if (!State)
1164 return nullptr;
1165
Anna Zaksb508d292012-04-10 23:41:11 +00001166 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001167 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001168
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001169 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001170 ReleasedAllocated, ReturnsNullOnFailure);
1171}
1172
Anna Zaksa14c1d02012-11-13 19:47:40 +00001173/// Checks if the previous call to free on the given symbol failed - if free
1174/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001175static bool didPreviousFreeFail(ProgramStateRef State,
1176 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001177 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001178 if (Ret) {
1179 assert(*Ret && "We should not store the null return symbol");
1180 ConstraintManager &CMgr = State->getConstraintManager();
1181 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001182 RetStatusSymbol = *Ret;
1183 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001184 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001185 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001186}
1187
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001188AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001189 const Stmt *S) const {
1190 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001191 return AF_None;
1192
Anton Yartseve3377fb2013-04-04 23:46:29 +00001193 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001194 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001195
1196 if (!FD)
1197 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1198
Anton Yartsev05789592013-03-28 17:05:19 +00001199 ASTContext &Ctx = C.getASTContext();
1200
Anna Zaksd79b8402014-10-03 21:48:59 +00001201 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001202 return AF_Malloc;
1203
1204 if (isStandardNewDelete(FD, Ctx)) {
1205 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001206 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001207 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001208 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001209 return AF_CXXNewArray;
1210 }
1211
Anna Zaksd79b8402014-10-03 21:48:59 +00001212 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1213 return AF_IfNameIndex;
1214
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001215 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1216 return AF_Alloca;
1217
Anton Yartsev05789592013-03-28 17:05:19 +00001218 return AF_None;
1219 }
1220
Anton Yartseve3377fb2013-04-04 23:46:29 +00001221 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1222 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1223
1224 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001225 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1226
Anton Yartseve3377fb2013-04-04 23:46:29 +00001227 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001228 return AF_Malloc;
1229
1230 return AF_None;
1231}
1232
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001233bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001234 const Expr *E) const {
1235 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1236 // FIXME: This doesn't handle indirect calls.
1237 const FunctionDecl *FD = CE->getDirectCallee();
1238 if (!FD)
1239 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001240
Anton Yartsev05789592013-03-28 17:05:19 +00001241 os << *FD;
1242 if (!FD->isOverloadedOperator())
1243 os << "()";
1244 return true;
1245 }
1246
1247 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1248 if (Msg->isInstanceMessage())
1249 os << "-";
1250 else
1251 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001252 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001253 return true;
1254 }
1255
1256 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001257 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001258 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1259 << "'";
1260 return true;
1261 }
1262
1263 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001264 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001265 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1266 << "'";
1267 return true;
1268 }
1269
1270 return false;
1271}
1272
1273void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1274 const Expr *E) const {
1275 AllocationFamily Family = getAllocationFamily(C, E);
1276
1277 switch(Family) {
1278 case AF_Malloc: os << "malloc()"; return;
1279 case AF_CXXNew: os << "'new'"; return;
1280 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001281 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001282 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001283 case AF_None: llvm_unreachable("not a deallocation expression");
1284 }
1285}
1286
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001287void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001288 AllocationFamily Family) const {
1289 switch(Family) {
1290 case AF_Malloc: os << "free()"; return;
1291 case AF_CXXNew: os << "'delete'"; return;
1292 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001293 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001294 case AF_Alloca:
1295 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001296 }
1297}
1298
Anna Zaks0d6989b2012-06-22 02:04:31 +00001299ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1300 const Expr *ArgExpr,
1301 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001302 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001303 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001304 bool &ReleasedAllocated,
1305 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001306
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001307 if (!State)
1308 return nullptr;
1309
Anna Zaks67291b92012-11-13 03:18:01 +00001310 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001311 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001312 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001313 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001314
1315 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001316 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001317 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001318
Anna Zaksad01ef52012-02-14 00:26:13 +00001319 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001320 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001321 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001322 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001323 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001324
Jordy Rose3597b212010-06-07 19:32:37 +00001325 // Unknown values could easily be okay
1326 // Undefined values are handled elsewhere
1327 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001328 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001329
Jordy Rose3597b212010-06-07 19:32:37 +00001330 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001331
Jordy Rose3597b212010-06-07 19:32:37 +00001332 // Nonlocs can't be freed, of course.
1333 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1334 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001335 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001336 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001337 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001338
Jordy Rose3597b212010-06-07 19:32:37 +00001339 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001340
Jordy Rose3597b212010-06-07 19:32:37 +00001341 // Blocks might show up as heap data, but should not be free()d
1342 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001343 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001344 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001345 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001346
Jordy Rose3597b212010-06-07 19:32:37 +00001347 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001348
1349 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001350 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001351 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1352 // FIXME: at the time this code was written, malloc() regions were
1353 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1354 // This means that there isn't actually anything from HeapSpaceRegion
1355 // that should be freed, even though we allow it here.
1356 // Of course, free() can work on memory allocated outside the current
1357 // function, so UnknownSpaceRegion is always a possibility.
1358 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001359
1360 if (isa<AllocaRegion>(R))
1361 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1362 else
1363 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1364
Craig Topper0dbb7832014-05-27 02:45:47 +00001365 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001366 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001367
1368 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001369 // Various cases could lead to non-symbol values here.
1370 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001371 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001372 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001373
Anna Zaksc89ad072013-02-07 23:05:47 +00001374 SymbolRef SymBase = SrBase->getSymbol();
1375 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001376 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001377
Anton Yartseve3377fb2013-04-04 23:46:29 +00001378 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001379
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001380 // Memory returned by alloca() shouldn't be freed.
1381 if (RsBase->getAllocationFamily() == AF_Alloca) {
1382 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1383 return nullptr;
1384 }
1385
Anna Zaks93a21a82013-04-09 00:30:28 +00001386 // Check for double free first.
1387 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001388 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1389 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1390 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001391 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001392
Anna Zaks93a21a82013-04-09 00:30:28 +00001393 // If the pointer is allocated or escaped, but we are now trying to free it,
1394 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001395 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001396 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001397
1398 // Check if an expected deallocation function matches the real one.
1399 bool DeallocMatchesAlloc =
1400 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1401 if (!DeallocMatchesAlloc) {
1402 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001403 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001404 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001405 }
1406
1407 // Check if the memory location being freed is the actual location
1408 // allocated, or an offset.
1409 RegionOffset Offset = R->getAsOffset();
1410 if (Offset.isValid() &&
1411 !Offset.hasSymbolicOffset() &&
1412 Offset.getOffset() != 0) {
1413 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001414 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001415 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001416 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001417 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001418 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001419 }
1420
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001421 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001422 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001423
Anna Zaksa14c1d02012-11-13 19:47:40 +00001424 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001425 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001426
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001427 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001428 // failed.
1429 if (ReturnsNullOnFailure) {
1430 SVal RetVal = C.getSVal(ParentExpr);
1431 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1432 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001433 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1434 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001435 }
1436 }
1437
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001438 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1439 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001440 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001441 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001442 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001443 RefState::getRelinquished(Family,
1444 ParentExpr));
1445
1446 return State->set<RegionState>(SymBase,
1447 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001448}
1449
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001450Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001451MallocChecker::getCheckIfTracked(AllocationFamily Family,
1452 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001453 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001454 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001455 case AF_Alloca:
1456 case AF_IfNameIndex: {
1457 if (ChecksEnabled[CK_MallocChecker])
1458 return CK_MallocChecker;
1459
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001460 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001461 }
1462 case AF_CXXNew:
1463 case AF_CXXNewArray: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001464 if (IsALeakCheck) {
1465 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1466 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001467 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001468 else {
1469 if (ChecksEnabled[CK_NewDeleteChecker])
1470 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001471 }
1472 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001473 }
1474 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001475 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001476 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001477 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001478 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001479}
1480
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001481Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001482MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001483 const Stmt *AllocDeallocStmt,
1484 bool IsALeakCheck) const {
1485 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1486 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001487}
1488
1489Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001490MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1491 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001492 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1493 return CK_MallocChecker;
1494
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001495 const RefState *RS = C.getState()->get<RegionState>(Sym);
1496 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001497 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001498}
1499
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001500bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001501 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001502 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001503 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001504 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001505 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001506 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001507 else
1508 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001509
Jordy Rose3597b212010-06-07 19:32:37 +00001510 return true;
1511}
1512
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001513bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001514 const MemRegion *MR) {
1515 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +00001516 case MemRegion::FunctionCodeRegionKind: {
1517 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001518 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001519 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001520 else
1521 os << "the address of a function";
1522 return true;
1523 }
Artem Dergachev73f018e2016-01-13 13:49:29 +00001524 case MemRegion::BlockCodeRegionKind:
Jordy Rose3597b212010-06-07 19:32:37 +00001525 os << "block text";
1526 return true;
1527 case MemRegion::BlockDataRegionKind:
1528 // FIXME: where the block came from?
1529 os << "a block";
1530 return true;
1531 default: {
1532 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001533
Anna Zaks8158ef02012-01-04 23:54:01 +00001534 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001535 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1536 const VarDecl *VD;
1537 if (VR)
1538 VD = VR->getDecl();
1539 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001540 VD = nullptr;
1541
Jordy Rose3597b212010-06-07 19:32:37 +00001542 if (VD)
1543 os << "the address of the local variable '" << VD->getName() << "'";
1544 else
1545 os << "the address of a local stack variable";
1546 return true;
1547 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001548
1549 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001550 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1551 const VarDecl *VD;
1552 if (VR)
1553 VD = VR->getDecl();
1554 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001555 VD = nullptr;
1556
Jordy Rose3597b212010-06-07 19:32:37 +00001557 if (VD)
1558 os << "the address of the parameter '" << VD->getName() << "'";
1559 else
1560 os << "the address of a parameter";
1561 return true;
1562 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001563
1564 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001565 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1566 const VarDecl *VD;
1567 if (VR)
1568 VD = VR->getDecl();
1569 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001570 VD = nullptr;
1571
Jordy Rose3597b212010-06-07 19:32:37 +00001572 if (VD) {
1573 if (VD->isStaticLocal())
1574 os << "the address of the static variable '" << VD->getName() << "'";
1575 else
1576 os << "the address of the global variable '" << VD->getName() << "'";
1577 } else
1578 os << "the address of a global variable";
1579 return true;
1580 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001581
1582 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001583 }
1584 }
1585}
1586
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001587void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1588 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001589 const Expr *DeallocExpr) const {
1590
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001591 if (!ChecksEnabled[CK_MallocChecker] &&
1592 !ChecksEnabled[CK_NewDeleteChecker])
1593 return;
1594
1595 Optional<MallocChecker::CheckKind> CheckKind =
1596 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001597 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001598 return;
1599
Devin Coughline39bd402015-09-16 22:03:05 +00001600 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001601 if (!BT_BadFree[*CheckKind])
1602 BT_BadFree[*CheckKind].reset(
1603 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1604
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001605 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001606 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001607
Jordy Rose3597b212010-06-07 19:32:37 +00001608 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001609 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1610 MR = ER->getSuperRegion();
1611
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001612 os << "Argument to ";
1613 if (!printAllocDeallocName(os, C, DeallocExpr))
1614 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001615
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001616 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001617 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001618 : SummarizeValue(os, ArgVal);
1619 if (Summarized)
1620 os << ", which is not memory allocated by ";
1621 else
1622 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001623
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001624 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001625
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001626 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001627 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001628 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001629 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001630 }
1631}
1632
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001633void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001634 SourceRange Range) const {
1635
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001636 Optional<MallocChecker::CheckKind> CheckKind;
1637
1638 if (ChecksEnabled[CK_MallocChecker])
1639 CheckKind = CK_MallocChecker;
1640 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1641 CheckKind = CK_MismatchedDeallocatorChecker;
1642 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001643 return;
1644
Devin Coughline39bd402015-09-16 22:03:05 +00001645 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001646 if (!BT_FreeAlloca[*CheckKind])
1647 BT_FreeAlloca[*CheckKind].reset(
1648 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1649
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001650 auto R = llvm::make_unique<BugReport>(
1651 *BT_FreeAlloca[*CheckKind],
1652 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001653 R->markInteresting(ArgVal.getAsRegion());
1654 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001655 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001656 }
1657}
1658
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001659void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001660 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001661 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001662 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001663 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001664 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001665
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001666 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001667 return;
1668
Devin Coughline39bd402015-09-16 22:03:05 +00001669 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001670 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001671 BT_MismatchedDealloc.reset(
1672 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1673 "Bad deallocator", "Memory Error"));
1674
Anton Yartsev05789592013-03-28 17:05:19 +00001675 SmallString<100> buf;
1676 llvm::raw_svector_ostream os(buf);
1677
1678 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1679 SmallString<20> AllocBuf;
1680 llvm::raw_svector_ostream AllocOs(AllocBuf);
1681 SmallString<20> DeallocBuf;
1682 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1683
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001684 if (OwnershipTransferred) {
1685 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1686 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001687 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001688 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001689
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001690 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001691
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001692 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1693 os << " allocated by " << AllocOs.str();
1694 } else {
1695 os << "Memory";
1696 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1697 os << " allocated by " << AllocOs.str();
1698
1699 os << " should be deallocated by ";
1700 printExpectedDeallocName(os, RS->getAllocationFamily());
1701
1702 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1703 os << ", not " << DeallocOs.str();
1704 }
Anton Yartsev05789592013-03-28 17:05:19 +00001705
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001706 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001707 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001708 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001709 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001710 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001711 }
1712}
1713
Anna Zaksc89ad072013-02-07 23:05:47 +00001714void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001715 SourceRange Range, const Expr *DeallocExpr,
1716 const Expr *AllocExpr) const {
1717
Anton Yartsev05789592013-03-28 17:05:19 +00001718
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001719 if (!ChecksEnabled[CK_MallocChecker] &&
1720 !ChecksEnabled[CK_NewDeleteChecker])
1721 return;
1722
1723 Optional<MallocChecker::CheckKind> CheckKind =
1724 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001725 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001726 return;
1727
Devin Coughline39bd402015-09-16 22:03:05 +00001728 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001729 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001730 return;
1731
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001732 if (!BT_OffsetFree[*CheckKind])
1733 BT_OffsetFree[*CheckKind].reset(
1734 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001735
1736 SmallString<100> buf;
1737 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001738 SmallString<20> AllocNameBuf;
1739 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001740
1741 const MemRegion *MR = ArgVal.getAsRegion();
1742 assert(MR && "Only MemRegion based symbols can have offset free errors");
1743
1744 RegionOffset Offset = MR->getAsOffset();
1745 assert((Offset.isValid() &&
1746 !Offset.hasSymbolicOffset() &&
1747 Offset.getOffset() != 0) &&
1748 "Only symbols with a valid offset can have offset free errors");
1749
1750 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1751
Anton Yartsev05789592013-03-28 17:05:19 +00001752 os << "Argument to ";
1753 if (!printAllocDeallocName(os, C, DeallocExpr))
1754 os << "deallocator";
1755 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001756 << offsetBytes
1757 << " "
1758 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001759 << " from the start of ";
1760 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1761 os << "memory allocated by " << AllocNameOs.str();
1762 else
1763 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001764
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001765 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001766 R->markInteresting(MR->getBaseRegion());
1767 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001768 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001769}
1770
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001771void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1772 SymbolRef Sym) const {
1773
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001774 if (!ChecksEnabled[CK_MallocChecker] &&
1775 !ChecksEnabled[CK_NewDeleteChecker])
1776 return;
1777
1778 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001779 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001780 return;
1781
Devin Coughline39bd402015-09-16 22:03:05 +00001782 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001783 if (!BT_UseFree[*CheckKind])
1784 BT_UseFree[*CheckKind].reset(new BugType(
1785 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001786
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001787 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1788 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001789
1790 R->markInteresting(Sym);
1791 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001792 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001793 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001794 }
1795}
1796
1797void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001798 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001799 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001800
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001801 if (!ChecksEnabled[CK_MallocChecker] &&
1802 !ChecksEnabled[CK_NewDeleteChecker])
1803 return;
1804
1805 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001806 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001807 return;
1808
Devin Coughline39bd402015-09-16 22:03:05 +00001809 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001810 if (!BT_DoubleFree[*CheckKind])
1811 BT_DoubleFree[*CheckKind].reset(
1812 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001813
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001814 auto R = llvm::make_unique<BugReport>(
1815 *BT_DoubleFree[*CheckKind],
1816 (Released ? "Attempt to free released memory"
1817 : "Attempt to free non-owned memory"),
1818 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001819 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001820 R->markInteresting(Sym);
1821 if (PrevSym)
1822 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001823 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001824 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001825 }
1826}
1827
Jordan Rose656fdd52014-01-08 18:46:55 +00001828void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1829
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001830 if (!ChecksEnabled[CK_NewDeleteChecker])
1831 return;
1832
1833 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001834 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001835 return;
1836
Devin Coughline39bd402015-09-16 22:03:05 +00001837 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00001838 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001839 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1840 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001841
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001842 auto R = llvm::make_unique<BugReport>(
1843 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00001844
1845 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001846 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001847 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00001848 }
1849}
1850
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001851void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1852 SourceRange Range,
1853 SymbolRef Sym) const {
1854
1855 if (!ChecksEnabled[CK_MallocChecker] &&
1856 !ChecksEnabled[CK_NewDeleteChecker])
1857 return;
1858
1859 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1860
1861 if (!CheckKind.hasValue())
1862 return;
1863
Devin Coughline39bd402015-09-16 22:03:05 +00001864 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001865 if (!BT_UseZerroAllocated[*CheckKind])
1866 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
1867 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
1868
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001869 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
1870 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001871
1872 R->addRange(Range);
1873 if (Sym) {
1874 R->markInteresting(Sym);
1875 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1876 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001877 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001878 }
1879}
1880
Anna Zaks40a7eb32012-02-22 19:24:52 +00001881ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1882 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001883 bool FreesOnFail,
1884 ProgramStateRef State) const {
1885 if (!State)
1886 return nullptr;
1887
Anna Zaksb508d292012-04-10 23:41:11 +00001888 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001889 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001890
Ted Kremenek90af9092010-12-02 07:49:45 +00001891 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001892 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001893 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001894 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001895 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001896 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001897
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001898 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001899
Ted Kremenek90af9092010-12-02 07:49:45 +00001900 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001901 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001902
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001903 // Get the size argument. If there is no size arg then give up.
1904 const Expr *Arg1 = CE->getArg(1);
1905 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00001906 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001907
1908 // Get the value of the size argument.
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001909 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001910 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001911 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001912 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001913
1914 // Compare the size argument to 0.
1915 DefinedOrUnknownSVal SizeZero =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001916 svalBuilder.evalEQ(State, Arg1Val,
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001917 svalBuilder.makeIntValWithPtrWidth(0, false));
1918
Anna Zaksd56c8792012-02-13 18:05:39 +00001919 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001920 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001921 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001922 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001923 // We only assume exceptional states if they are definitely true; if the
1924 // state is under-constrained, assume regular realloc behavior.
1925 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1926 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1927
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001928 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001929 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001930 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001931 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001932 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001933 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001934 }
1935
Anna Zaksd56c8792012-02-13 18:05:39 +00001936 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00001937 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001938
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001939 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001940 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001941 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001942 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001943 SymbolRef ToPtr = RetVal.getAsSymbol();
1944 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00001945 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00001946
Anna Zaksfe6eb672012-08-24 02:28:20 +00001947 bool ReleasedAllocated = false;
1948
Anna Zaksd56c8792012-02-13 18:05:39 +00001949 // If the size is 0, free the memory.
1950 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001951 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1952 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001953 // The semantics of the return value are:
1954 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001955 // to free() is returned. We just free the input pointer and do not add
1956 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001957 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001958 }
1959
1960 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001961 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001962 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00001963
Anna Zaksd56c8792012-02-13 18:05:39 +00001964 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1965 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001966 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001967 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001968
Anna Zaks75cfbb62012-09-12 22:57:34 +00001969 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1970 if (FreesOnFail)
1971 Kind = RPIsFreeOnFailure;
1972 else if (!ReleasedAllocated)
1973 Kind = RPDoNotTrackAfterFailure;
1974
Anna Zaksfe6eb672012-08-24 02:28:20 +00001975 // Record the info about the reallocated symbol so that we could properly
1976 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001977 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001978 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001979 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001980 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001981 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001982 }
Craig Topper0dbb7832014-05-27 02:45:47 +00001983 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001984}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001985
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001986ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001987 ProgramStateRef State) {
1988 if (!State)
1989 return nullptr;
1990
Anna Zaksb508d292012-04-10 23:41:11 +00001991 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001992 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001993
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001994 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001995 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001996 SVal count = State->getSVal(CE->getArg(0), LCtx);
1997 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1998 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001999 svalBuilder.getContext().getSizeType());
Ted Kremenek90af9092010-12-02 07:49:45 +00002000 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002001
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002002 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002003}
2004
Anna Zaksfc2e1532012-03-21 19:45:08 +00002005LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002006MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2007 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002008 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002009 // Walk the ExplodedGraph backwards and find the first node that referred to
2010 // the tracked symbol.
2011 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002012 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002013
2014 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002015 ProgramStateRef State = N->getState();
2016 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002017 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002018
2019 // Find the most recent expression bound to the symbol in the current
2020 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002021 if (!ReferenceRegion) {
2022 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2023 SVal Val = State->getSVal(MR);
2024 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002025 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002026 // Do not show local variables belonging to a function other than
2027 // where the error is reported.
2028 if (!VR ||
2029 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2030 ReferenceRegion = MR;
2031 }
2032 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002033 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002034
Anna Zaks486a0ff2015-02-05 01:02:53 +00002035 // Allocation node, is the last node in the current or parent context in
2036 // which the symbol was tracked.
2037 const LocationContext *NContext = N->getLocationContext();
2038 if (NContext == LeakContext ||
2039 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002040 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002041 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002042 }
2043
Anna Zaksa043d0c2013-01-08 00:25:29 +00002044 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002045}
2046
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002047void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2048 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002049
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002050 if (!ChecksEnabled[CK_MallocChecker] &&
2051 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002052 return;
2053
Anton Yartsev9907fc92015-03-04 23:18:21 +00002054 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002055 assert(RS && "cannot leak an untracked symbol");
2056 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002057
2058 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002059 return;
2060
Anton Yartsev2487dd62015-03-10 22:24:21 +00002061 Optional<MallocChecker::CheckKind>
2062 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002063
Anton Yartsev2487dd62015-03-10 22:24:21 +00002064 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002065 return;
2066
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002067 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002068 if (!BT_Leak[*CheckKind]) {
2069 BT_Leak[*CheckKind].reset(
2070 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002071 // Leaks should not be reported if they are post-dominated by a sink:
2072 // (1) Sinks are higher importance bugs.
2073 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2074 // with __noreturn functions such as assert() or exit(). We choose not
2075 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002076 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002077 }
2078
Anna Zaksdf901a42012-02-23 21:38:21 +00002079 // Most bug reports are cached at the location where they occurred.
2080 // With leaks, we want to unique them by the location where they were
2081 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002082 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002083 const ExplodedNode *AllocNode = nullptr;
2084 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002085 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002086
Anna Zaksa043d0c2013-01-08 00:25:29 +00002087 ProgramPoint P = AllocNode->getLocation();
Craig Topper0dbb7832014-05-27 02:45:47 +00002088 const Stmt *AllocationStmt = nullptr;
David Blaikie87396b92013-02-21 22:23:56 +00002089 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00002090 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002091 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00002092 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00002093 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002094 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2095 C.getSourceManager(),
2096 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002097
Anna Zaksfc2e1532012-03-21 19:45:08 +00002098 SmallString<200> buf;
2099 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002100 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002101 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002102 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002103 } else {
2104 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002105 }
2106
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002107 auto R = llvm::make_unique<BugReport>(
2108 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2109 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002110 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002111 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002112 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002113}
2114
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002115void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2116 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002117{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002118 if (!SymReaper.hasDeadSymbols())
2119 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002120
Ted Kremenek49b1e382012-01-26 21:29:00 +00002121 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002122 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002123 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002124
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002125 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002126 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2127 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002128 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002129 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002130 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002131 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002132
Zhongxing Xuc7460962009-11-13 07:48:11 +00002133 }
2134 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002135
Anna Zaksd56c8792012-02-13 18:05:39 +00002136 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002137 ReallocPairsTy RP = state->get<ReallocPairs>();
2138 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002139 if (SymReaper.isDead(I->first) ||
2140 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002141 state = state->remove<ReallocPairs>(I->first);
2142 }
2143 }
2144
Anna Zaks67291b92012-11-13 03:18:01 +00002145 // Cleanup the FreeReturnValue Map.
2146 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2147 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2148 if (SymReaper.isDead(I->first) ||
2149 SymReaper.isDead(I->second)) {
2150 state = state->remove<FreeReturnValue>(I->first);
2151 }
2152 }
2153
Anna Zaksdf901a42012-02-23 21:38:21 +00002154 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002155 ExplodedNode *N = C.getPredecessor();
2156 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002157 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002158 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2159 if (N) {
2160 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002161 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002162 reportLeak(*I, N, C);
2163 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002164 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002165 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002166
Anna Zaksdf901a42012-02-23 21:38:21 +00002167 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002168}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002169
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002170void MallocChecker::checkPreCall(const CallEvent &Call,
2171 CheckerContext &C) const {
2172
Jordan Rose656fdd52014-01-08 18:46:55 +00002173 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2174 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2175 if (!Sym || checkDoubleDelete(Sym, C))
2176 return;
2177 }
2178
Anna Zaks46d01602012-05-18 01:16:10 +00002179 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002180 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2181 const FunctionDecl *FD = FC->getDecl();
2182 if (!FD)
2183 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002184
Anna Zaksd79b8402014-10-03 21:48:59 +00002185 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002186 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002187 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2188 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2189 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002190 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002191
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002192 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002193 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002194 return;
2195 }
2196
2197 // Check if the callee of a method is deleted.
2198 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2199 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2200 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2201 return;
2202 }
2203
2204 // Check arguments for being used after free.
2205 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2206 SVal ArgSVal = Call.getArgSVal(I);
2207 if (ArgSVal.getAs<Loc>()) {
2208 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002209 if (!Sym)
2210 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002211 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002212 return;
2213 }
2214 }
2215}
2216
Anna Zaksa1b227b2012-02-08 23:16:56 +00002217void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2218 const Expr *E = S->getRetValue();
2219 if (!E)
2220 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002221
2222 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002223 ProgramStateRef State = C.getState();
2224 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002225 SymbolRef Sym = RetVal.getAsSymbol();
2226 if (!Sym)
2227 // If we are returning a field of the allocated struct or an array element,
2228 // the callee could still free the memory.
2229 // TODO: This logic should be a part of generic symbol escape callback.
2230 if (const MemRegion *MR = RetVal.getAsRegion())
2231 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2232 if (const SymbolicRegion *BMR =
2233 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2234 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002235
Anna Zaks3aa52252012-02-11 21:44:39 +00002236 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002237 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002238 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002239}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002240
Anna Zaks9fe80982012-03-22 00:57:20 +00002241// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002242// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002243// needed.
2244void MallocChecker::checkPostStmt(const BlockExpr *BE,
2245 CheckerContext &C) const {
2246
2247 // Scan the BlockDecRefExprs for any object the retain count checker
2248 // may be tracking.
2249 if (!BE->getBlockDecl()->hasCaptures())
2250 return;
2251
2252 ProgramStateRef state = C.getState();
2253 const BlockDataRegion *R =
2254 cast<BlockDataRegion>(state->getSVal(BE,
2255 C.getLocationContext()).getAsRegion());
2256
2257 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2258 E = R->referenced_vars_end();
2259
2260 if (I == E)
2261 return;
2262
2263 SmallVector<const MemRegion*, 10> Regions;
2264 const LocationContext *LC = C.getLocationContext();
2265 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2266
2267 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002268 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002269 if (VR->getSuperRegion() == R) {
2270 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2271 }
2272 Regions.push_back(VR);
2273 }
2274
2275 state =
2276 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2277 Regions.data() + Regions.size()).getState();
2278 C.addTransition(state);
2279}
2280
Anna Zaks46d01602012-05-18 01:16:10 +00002281bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002282 assert(Sym);
2283 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002284 return (RS && RS->isReleased());
2285}
2286
2287bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2288 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002289
Jordan Rose656fdd52014-01-08 18:46:55 +00002290 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002291 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2292 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002293 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002294
Anna Zaksa1b227b2012-02-08 23:16:56 +00002295 return false;
2296}
2297
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002298void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2299 const Stmt *S) const {
2300 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002301
Devin Coughlin81771732015-09-22 22:47:14 +00002302 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2303 if (RS->isAllocatedOfSizeZero())
2304 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2305 }
2306 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2307 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2308 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002309}
2310
Jordan Rose656fdd52014-01-08 18:46:55 +00002311bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2312
2313 if (isReleased(Sym, C)) {
2314 ReportDoubleDelete(C, Sym);
2315 return true;
2316 }
2317 return false;
2318}
2319
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002320// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002321void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2322 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002323 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002324 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002325 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002326 checkUseZeroAllocated(Sym, C, S);
2327 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002328}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002329
Anna Zaksbb1ef902012-02-11 21:02:35 +00002330// If a symbolic region is assumed to NULL (or another constant), stop tracking
2331// it - assuming that allocation failed on this path.
2332ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2333 SVal Cond,
2334 bool Assumption) const {
2335 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002336 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002337 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002338 ConstraintManager &CMgr = state->getConstraintManager();
2339 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2340 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002341 state = state->remove<RegionState>(I.getKey());
2342 }
2343
Anna Zaksd56c8792012-02-13 18:05:39 +00002344 // Realloc returns 0 when reallocation fails, which means that we should
2345 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002346 ReallocPairsTy RP = state->get<ReallocPairs>();
2347 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002348 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002349 ConstraintManager &CMgr = state->getConstraintManager();
2350 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002351 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002352 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002353
Anna Zaks75cfbb62012-09-12 22:57:34 +00002354 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2355 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2356 if (RS->isReleased()) {
2357 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002358 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002359 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002360 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2361 state = state->remove<RegionState>(ReallocSym);
2362 else
2363 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002364 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002365 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002366 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002367 }
2368
Anna Zaksbb1ef902012-02-11 21:02:35 +00002369 return state;
2370}
2371
Anna Zaks8ebeb642013-06-08 00:29:29 +00002372bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002373 const CallEvent *Call,
2374 ProgramStateRef State,
2375 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002376 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002377 EscapingSymbol = nullptr;
2378
Jordan Rose2a833ca2014-01-15 17:25:15 +00002379 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002380 // TODO: If we want to be more optimistic here, we'll need to make sure that
2381 // regions escape to C++ containers. They seem to do that even now, but for
2382 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002383 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002384 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002385
Jordan Rose742920c2012-07-02 19:27:35 +00002386 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002387 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002388 // If it's not a framework call, or if it takes a callback, assume it
2389 // can free memory.
Anna Zaksfe1eca52015-10-27 20:19:45 +00002390 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002391 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002392
Jordan Rose613f3c02013-03-09 00:59:10 +00002393 // If it's a method we know about, handle it explicitly post-call.
2394 // This should happen before the "freeWhenDone" check below.
2395 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002396 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002397
Jordan Rose613f3c02013-03-09 00:59:10 +00002398 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2399 // about, we can't be sure that the object will use free() to deallocate the
2400 // memory, so we can't model it explicitly. The best we can do is use it to
2401 // decide whether the pointer escapes.
2402 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002403 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002404
Jordan Rose613f3c02013-03-09 00:59:10 +00002405 // If the first selector piece ends with "NoCopy", and there is no
2406 // "freeWhenDone" parameter set to zero, we know ownership is being
2407 // transferred. Again, though, we can't be sure that the object will use
2408 // free() to deallocate the memory, so we can't model it explicitly.
2409 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002410 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002411 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002412
Anna Zaks42908c72012-06-19 05:10:32 +00002413 // If the first selector starts with addPointer, insertPointer,
2414 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2415 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002416 // that the pointers get freed by following the container itself.
2417 if (FirstSlot.startswith("addPointer") ||
2418 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002419 FirstSlot.startswith("replacePointer") ||
2420 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002421 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002422 }
2423
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002424 // We should escape receiver on call to 'init'. This is especially relevant
2425 // to the receiver, as the corresponding symbol is usually not referenced
2426 // after the call.
2427 if (Msg->getMethodFamily() == OMF_init) {
2428 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2429 return true;
2430 }
Anna Zaks737926b2013-05-31 22:39:13 +00002431
Jordan Rose742920c2012-07-02 19:27:35 +00002432 // Otherwise, assume that the method does not free memory.
2433 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002434 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002435 }
2436
Jordan Rose742920c2012-07-02 19:27:35 +00002437 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002438 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002439 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002440 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002441
Jordan Rose742920c2012-07-02 19:27:35 +00002442 ASTContext &ASTC = State->getStateManager().getContext();
2443
2444 // If it's one of the allocation functions we can reason about, we model
2445 // its behavior explicitly.
2446 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002447 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002448
2449 // If it's not a system call, assume it frees memory.
2450 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002451 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002452
2453 // White list the system functions whose arguments escape.
2454 const IdentifierInfo *II = FD->getIdentifier();
2455 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002456 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002457 StringRef FName = II->getName();
2458
Jordan Rose742920c2012-07-02 19:27:35 +00002459 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002460 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002461 if (FName.endswith("NoCopy")) {
2462 // Look for the deallocator argument. We know that the memory ownership
2463 // is not transferred only if the deallocator argument is
2464 // 'kCFAllocatorNull'.
2465 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2466 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2467 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2468 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2469 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002470 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002471 }
2472 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002473 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002474 }
2475
Jordan Rose742920c2012-07-02 19:27:35 +00002476 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002477 // 'closefn' is specified (and if that function does free memory),
2478 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002479 // Currently, we do not inspect the 'closefn' function (PR12101).
2480 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002481 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002482 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002483
2484 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2485 // these leaks might be intentional when setting the buffer for stdio.
2486 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2487 if (FName == "setbuf" || FName =="setbuffer" ||
2488 FName == "setlinebuf" || FName == "setvbuf") {
2489 if (Call->getNumArgs() >= 1) {
2490 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2491 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2492 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2493 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002494 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002495 }
2496 }
2497
2498 // A bunch of other functions which either take ownership of a pointer or
2499 // wrap the result up in a struct or object, meaning it can be freed later.
2500 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2501 // but the Malloc checker cannot differentiate between them. The right way
2502 // of doing this would be to implement a pointer escapes callback.
2503 if (FName == "CGBitmapContextCreate" ||
2504 FName == "CGBitmapContextCreateWithData" ||
2505 FName == "CVPixelBufferCreateWithBytes" ||
2506 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2507 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002508 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002509 }
2510
Anna Zaks03f48332016-01-06 00:32:56 +00002511 if (FName == "postEvent" &&
2512 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2513 return true;
2514 }
2515
2516 if (FName == "postEvent" &&
2517 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2518 return true;
2519 }
2520
Jordan Rose7ab01822012-07-02 19:27:51 +00002521 // Handle cases where we know a buffer's /address/ can escape.
2522 // Note that the above checks handle some special cases where we know that
2523 // even though the address escapes, it's still our responsibility to free the
2524 // buffer.
2525 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002526 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002527
2528 // Otherwise, assume that the function does not free memory.
2529 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002530 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002531}
2532
Anna Zaks333481b2013-03-28 23:15:29 +00002533static bool retTrue(const RefState *RS) {
2534 return true;
2535}
2536
2537static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2538 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2539 RS->getAllocationFamily() == AF_CXXNew);
2540}
2541
Anna Zaksdc154152012-12-20 00:38:25 +00002542ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2543 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002544 const CallEvent *Call,
2545 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002546 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2547}
2548
2549ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2550 const InvalidatedSymbols &Escaped,
2551 const CallEvent *Call,
2552 PointerEscapeKind Kind) const {
2553 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2554 &checkIfNewOrNewArrayFamily);
2555}
2556
2557ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2558 const InvalidatedSymbols &Escaped,
2559 const CallEvent *Call,
2560 PointerEscapeKind Kind,
2561 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002562 // If we know that the call does not free memory, or we want to process the
2563 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002564 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002565 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002566 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2567 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002568 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002569 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002570 }
Anna Zaks3d348342012-02-14 21:55:24 +00002571
Anna Zaksdc154152012-12-20 00:38:25 +00002572 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002573 E = Escaped.end();
2574 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002575 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002576
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002577 if (EscapingSymbol && EscapingSymbol != sym)
2578 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002579
Anna Zaks0d6989b2012-06-22 02:04:31 +00002580 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002581 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2582 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002583 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002584 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2585 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002586 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002587 }
Anna Zaks3d348342012-02-14 21:55:24 +00002588 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002589}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002590
Jordy Rosebf38f202012-03-18 07:43:35 +00002591static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2592 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002593 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2594 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002595
Jordan Rose0c153cb2012-11-02 01:54:06 +00002596 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002597 I != E; ++I) {
2598 SymbolRef sym = I.getKey();
2599 if (!currMap.lookup(sym))
2600 return sym;
2601 }
2602
Craig Topper0dbb7832014-05-27 02:45:47 +00002603 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002604}
2605
Anna Zaks2b5bb972012-02-09 06:25:51 +00002606PathDiagnosticPiece *
2607MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2608 const ExplodedNode *PrevN,
2609 BugReporterContext &BRC,
2610 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002611 ProgramStateRef state = N->getState();
2612 ProgramStateRef statePrev = PrevN->getState();
2613
2614 const RefState *RS = state->get<RegionState>(Sym);
2615 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002616 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002617 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002618
Craig Topper0dbb7832014-05-27 02:45:47 +00002619 const Stmt *S = nullptr;
2620 const char *Msg = nullptr;
2621 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002622
2623 // Retrieve the associated statement.
2624 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002625 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002626 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002627 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002628 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002629 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002630 // If an assumption was made on a branch, it should be caught
2631 // here by looking at the state transition.
2632 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002633 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002634
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002635 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002636 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002637
Jordan Rose681cce92012-07-10 22:07:42 +00002638 // FIXME: We will eventually need to handle non-statement-based events
2639 // (__attribute__((cleanup))).
2640
Anna Zaks2b5bb972012-02-09 06:25:51 +00002641 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002642 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002643 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002644 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002645 StackHint = new StackHintGeneratorForSymbol(Sym,
2646 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002647 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002648 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002649 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002650 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002651 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002652 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002653 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002654 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002655 Mode = ReallocationFailed;
2656 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002657 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002658 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002659
Jordy Rose21ff76e2012-03-24 03:15:09 +00002660 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2661 // Is it possible to fail two reallocs WITHOUT testing in between?
2662 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2663 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002664 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002665 FailedReallocSymbol = sym;
2666 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002667 }
2668
2669 // We are in a special mode if a reallocation failed later in the path.
2670 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002671 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002672
Jordy Rose21ff76e2012-03-24 03:15:09 +00002673 // Is this is the first appearance of the reallocated symbol?
2674 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002675 // We're at the reallocation point.
2676 Msg = "Attempt to reallocate memory";
2677 StackHint = new StackHintGeneratorForSymbol(Sym,
2678 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002679 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002680 Mode = Normal;
2681 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002682 }
2683
Anna Zaks2b5bb972012-02-09 06:25:51 +00002684 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002685 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002686 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002687
2688 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002689 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002690 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002691 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002692}
2693
Anna Zaks263b7e02012-05-02 00:05:20 +00002694void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2695 const char *NL, const char *Sep) const {
2696
2697 RegionStateTy RS = State->get<RegionState>();
2698
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002699 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002700 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002701 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002702 const RefState *RefS = State->get<RegionState>(I.getKey());
2703 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002704 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002705 if (!CheckKind.hasValue())
2706 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002707
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002708 I.getKey()->dumpToStream(Out);
2709 Out << " : ";
2710 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002711 if (CheckKind.hasValue())
2712 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002713 Out << NL;
2714 }
2715 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002716}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002717
Anna Zakse4cfcd42013-04-16 00:22:55 +00002718void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2719 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002720 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002721 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2722 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002723 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2724 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2725 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002726 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00002727 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002728 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002729 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002730}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002731
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002732#define REGISTER_CHECKER(name) \
2733 void ento::register##name(CheckerManager &mgr) { \
2734 registerCStringCheckerBasic(mgr); \
2735 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002736 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2737 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002738 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2739 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2740 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002741
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002742REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002743REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002744REGISTER_CHECKER(MismatchedDeallocatorChecker)