blob: 07c607212d7f47bd5b18caece810a667c04f8db4 [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"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000029#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000031#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000032#include <climits>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000033#include <utility>
Anna Zaks199e8e52012-02-22 03:14:20 +000034
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()
Anna Zaks30d46682016-03-08 01:21:51 +0000172 : II_alloca(nullptr), II_win_alloca(nullptr), II_malloc(nullptr),
173 II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
174 II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
175 II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr),
176 II_if_nameindex(nullptr), II_if_freenameindex(nullptr),
177 II_wcsdup(nullptr), II_win_wcsdup(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000178
179 /// In pessimistic mode, the checker assumes that it does not know which
180 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000181 enum CheckKind {
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000182 CK_MallocChecker,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000183 CK_NewDeleteChecker,
184 CK_NewDeleteLeaksChecker,
185 CK_MismatchedDeallocatorChecker,
186 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000187 };
188
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000189 enum class MemoryOperationKind {
Anna Zaksd79b8402014-10-03 21:48:59 +0000190 MOK_Allocate,
191 MOK_Free,
192 MOK_Any
193 };
194
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000195 DefaultBool IsOptimistic;
196
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000197 DefaultBool ChecksEnabled[CK_NumCheckKinds];
198 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000199
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000200 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000201 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000202 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
203 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000204 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000205 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000206 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000207 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000208 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000209 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000210 void checkLocation(SVal l, bool isLoad, const Stmt *S,
211 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000212
213 ProgramStateRef checkPointerEscape(ProgramStateRef State,
214 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000215 const CallEvent *Call,
216 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000217 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
218 const InvalidatedSymbols &Escaped,
219 const CallEvent *Call,
220 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000221
Anna Zaks263b7e02012-05-02 00:05:20 +0000222 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000223 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000224
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000225private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000226 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
227 mutable std::unique_ptr<BugType> BT_DoubleDelete;
228 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
229 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
230 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000231 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000232 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
233 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000234 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
Anna Zaks30d46682016-03-08 01:21:51 +0000235 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
236 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
237 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
238 *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
239 *II_win_wcsdup;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000240 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000241
Anna Zaks3d348342012-02-14 21:55:24 +0000242 void initIdentifierInfo(ASTContext &C) const;
243
Anton Yartsev05789592013-03-28 17:05:19 +0000244 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000245 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000246
247 /// \brief Print names of allocators and deallocators.
248 ///
249 /// \returns true on success.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000250 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000251 const Expr *E) const;
252
253 /// \brief Print expected name of an allocator based on the deallocator's
254 /// family derived from the DeallocExpr.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000255 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000256 const Expr *DeallocExpr) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000257 /// \brief Print expected name of a deallocator based on the allocator's
Anton Yartsev05789592013-03-28 17:05:19 +0000258 /// family.
259 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
260
Jordan Rose613f3c02013-03-09 00:59:10 +0000261 ///@{
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000262 /// Check if this is one of the functions which can allocate/reallocate memory
Anna Zaks3d348342012-02-14 21:55:24 +0000263 /// pointed to by one of its arguments.
264 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000265 bool isCMemFunction(const FunctionDecl *FD,
266 ASTContext &C,
267 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000268 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000269 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000270 ///@}
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000271
272 /// \brief Perform a zero-allocation check.
273 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
274 const unsigned AllocationSizeArg,
275 ProgramStateRef State) const;
276
Richard Smith852e9ce2013-11-27 01:46:48 +0000277 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
278 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000279 const OwnershipAttr* Att,
280 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000281 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000282 const Expr *SizeEx, SVal Init,
283 ProgramStateRef State,
284 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000285 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000286 SVal SizeEx, SVal Init,
287 ProgramStateRef State,
288 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000289
Gabor Horvath73040272016-09-19 20:39:52 +0000290 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
291 ProgramStateRef State);
292
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000293 // Check if this malloc() for special flags. At present that means M_ZERO or
294 // __GFP_ZERO (in which case, treat it like calloc).
295 llvm::Optional<ProgramStateRef>
296 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
297 const ProgramStateRef &State) const;
298
Anna Zaks40a7eb32012-02-22 19:24:52 +0000299 /// Update the RefState to reflect the new memory allocation.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000300 static ProgramStateRef
Anton Yartsev05789592013-03-28 17:05:19 +0000301 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
302 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000303
304 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000305 const OwnershipAttr* Att,
306 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000307 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000308 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000309 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000310 bool &ReleasedAllocated,
311 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000312 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
313 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000314 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000315 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000316 bool &ReleasedAllocated,
317 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000318
Anna Zaks40a7eb32012-02-22 19:24:52 +0000319 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000320 bool FreesMemOnFailure,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000321 ProgramStateRef State) const;
322 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
323 ProgramStateRef State);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000324
Anna Zaks46d01602012-05-18 01:16:10 +0000325 ///\brief Check if the memory associated with this symbol was released.
326 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
327
Anton Yartsev13df0362013-03-25 01:35:45 +0000328 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000329
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000330 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000331 const Stmt *S) const;
332
Jordan Rose656fdd52014-01-08 18:46:55 +0000333 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
334
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000335 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000336 /// "interesting" and should be modeled explicitly.
337 ///
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000338 /// \param [out] EscapingSymbol A function might not free memory in general,
Anna Zaks8ebeb642013-06-08 00:29:29 +0000339 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000340 /// returned and the single escaping symbol is returned through the out
341 /// parameter.
342 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000343 /// We assume that pointers do not escape through calls to system functions
344 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000345 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000346 ProgramStateRef State,
347 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000348
Anna Zaks333481b2013-03-28 23:15:29 +0000349 // Implementation of the checkPointerEscape callabcks.
350 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
351 const InvalidatedSymbols &Escaped,
352 const CallEvent *Call,
353 PointerEscapeKind Kind,
354 bool(*CheckRefState)(const RefState*)) const;
355
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000356 ///@{
357 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000358 /// Sets CheckKind to the kind of the checker responsible for this
359 /// family/call/symbol.
Anton Yartsev2487dd62015-03-10 22:24:21 +0000360 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
361 bool IsALeakCheck = false) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000362 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000363 const Stmt *AllocDeallocStmt,
364 bool IsALeakCheck = false) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000365 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000366 bool IsALeakCheck = false) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000367 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000368 static bool SummarizeValue(raw_ostream &os, SVal V);
369 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000370 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +0000371 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000372 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
373 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000374 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000375 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000376 SymbolRef Sym, bool OwnershipTransferred) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000377 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
378 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000379 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000380 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
381 SymbolRef Sym) const;
382 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000383 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000384
Jordan Rose656fdd52014-01-08 18:46:55 +0000385 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
386
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000387 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
388 SymbolRef Sym) const;
389
Anna Zaksdf901a42012-02-23 21:38:21 +0000390 /// Find the location of the allocation for Sym on the path leading to the
391 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000392 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
393 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000394
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000395 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
396
Anna Zaks2b5bb972012-02-09 06:25:51 +0000397 /// The bug visitor which allows us to print extra diagnostics along the
398 /// BugReport path. For example, showing the allocation site of the leaked
399 /// region.
David Blaikie6951e3e2015-08-13 22:58:37 +0000400 class MallocBugVisitor final
401 : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000402 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000403 enum NotificationMode {
404 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000405 ReallocationFailed
406 };
407
Anna Zaks2b5bb972012-02-09 06:25:51 +0000408 // The allocated region symbol tracked by the main analysis.
409 SymbolRef Sym;
410
Anna Zaks62cce9e2012-05-10 01:37:40 +0000411 // The mode we are in, i.e. what kind of diagnostics will be emitted.
412 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000413
Anna Zaks62cce9e2012-05-10 01:37:40 +0000414 // A symbol from when the primary region should have been reallocated.
415 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000416
Anna Zaks62cce9e2012-05-10 01:37:40 +0000417 bool IsLeak;
418
419 public:
420 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000421 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000422
Craig Topperfb6b25b2014-03-15 04:29:04 +0000423 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000424 static int X = 0;
425 ID.AddPointer(&X);
426 ID.AddPointer(Sym);
427 }
428
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000429 inline bool isAllocated(const RefState *S, const RefState *SPrev,
430 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000431 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000432 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000433 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
434 (!SPrev || !(SPrev->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000435 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000436 }
437
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000438 inline bool isReleased(const RefState *S, const RefState *SPrev,
439 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000440 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000441 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000442 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
443 }
444
Anna Zaks0d6989b2012-06-22 02:04:31 +0000445 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
446 const Stmt *Stmt) {
447 // Did not track -> relinquished. Other state (allocated) -> relinquished.
448 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
449 isa<ObjCPropertyRefExpr>(Stmt)) &&
450 (S && S->isRelinquished()) &&
451 (!SPrev || !SPrev->isRelinquished()));
452 }
453
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000454 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
455 const Stmt *Stmt) {
456 // If the expression is not a call, and the state change is
457 // released -> allocated, it must be the realloc return value
458 // check. If we have to handle more cases here, it might be cleaner just
459 // to track this extra bit in the state itself.
460 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000461 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
462 (SPrev && !(SPrev->isAllocated() ||
463 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000464 }
465
466 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
467 const ExplodedNode *PrevN,
468 BugReporterContext &BRC,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000469 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000470
David Blaikied15481c2014-08-29 18:18:43 +0000471 std::unique_ptr<PathDiagnosticPiece>
472 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
473 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000474 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000475 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000476
477 PathDiagnosticLocation L =
478 PathDiagnosticLocation::createEndOfPath(EndPathNode,
479 BRC.getSourceManager());
480 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000481 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
482 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000483 }
484
Anna Zakscba4f292012-03-16 23:24:20 +0000485 private:
486 class StackHintGeneratorForReallocationFailed
487 : public StackHintGeneratorForSymbol {
488 public:
489 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
490 : StackHintGeneratorForSymbol(S, M) {}
491
Craig Topperfb6b25b2014-03-15 04:29:04 +0000492 std::string getMessageForArg(const Expr *ArgE,
493 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000494 // Printed parameters start at 1, not 0.
495 ++ArgIndex;
496
Anna Zakscba4f292012-03-16 23:24:20 +0000497 SmallString<200> buf;
498 llvm::raw_svector_ostream os(buf);
499
Jordan Rosec102b352012-09-22 01:24:42 +0000500 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
501 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000502
503 return os.str();
504 }
505
Craig Topperfb6b25b2014-03-15 04:29:04 +0000506 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000507 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000508 }
509 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000510 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000511};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000512} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000513
Jordan Rose0c153cb2012-11-02 01:54:06 +0000514REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
515REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Devin Coughlin81771732015-09-22 22:47:14 +0000516REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000517
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000518// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000519// the free function.
520REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
521
Anna Zaksbb1ef902012-02-11 21:02:35 +0000522namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000523class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000524 ProgramStateRef state;
525public:
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000526 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
Anna Zaksbb1ef902012-02-11 21:02:35 +0000527 ProgramStateRef getState() const { return state; }
528
Craig Topperfb6b25b2014-03-15 04:29:04 +0000529 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000530 state = state->remove<RegionState>(sym);
531 return true;
532 }
533};
534} // end anonymous namespace
535
Anna Zaks3d348342012-02-14 21:55:24 +0000536void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000537 if (II_malloc)
538 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000539 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000540 II_malloc = &Ctx.Idents.get("malloc");
541 II_free = &Ctx.Idents.get("free");
542 II_realloc = &Ctx.Idents.get("realloc");
543 II_reallocf = &Ctx.Idents.get("reallocf");
544 II_calloc = &Ctx.Idents.get("calloc");
545 II_valloc = &Ctx.Idents.get("valloc");
546 II_strdup = &Ctx.Idents.get("strdup");
547 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaks30d46682016-03-08 01:21:51 +0000548 II_wcsdup = &Ctx.Idents.get("wcsdup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000549 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000550 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
551 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaks30d46682016-03-08 01:21:51 +0000552
553 //MSVC uses `_`-prefixed instead, so we check for them too.
554 II_win_strdup = &Ctx.Idents.get("_strdup");
555 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
556 II_win_alloca = &Ctx.Idents.get("_alloca");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000557}
558
Anna Zaks3d348342012-02-14 21:55:24 +0000559bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000560 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000561 return true;
562
Anna Zaksd79b8402014-10-03 21:48:59 +0000563 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000564 return true;
565
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000566 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
567 return true;
568
Anton Yartsev13df0362013-03-25 01:35:45 +0000569 if (isStandardNewDelete(FD, C))
570 return true;
571
Anna Zaks46d01602012-05-18 01:16:10 +0000572 return false;
573}
574
Anna Zaksd79b8402014-10-03 21:48:59 +0000575bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
576 ASTContext &C,
577 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000578 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000579 if (!FD)
580 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000581
Anna Zaksd79b8402014-10-03 21:48:59 +0000582 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
583 MemKind == MemoryOperationKind::MOK_Free);
584 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
585 MemKind == MemoryOperationKind::MOK_Allocate);
586
Jordan Rose6cd16c52012-07-10 23:13:01 +0000587 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000588 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000589 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000590
Anna Zaksd79b8402014-10-03 21:48:59 +0000591 if (Family == AF_Malloc && CheckFree) {
592 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
593 return true;
594 }
595
596 if (Family == AF_Malloc && CheckAlloc) {
597 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
598 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
Anna Zaks30d46682016-03-08 01:21:51 +0000599 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
600 FunI == II_win_wcsdup || FunI == II_kmalloc)
Anna Zaksd79b8402014-10-03 21:48:59 +0000601 return true;
602 }
603
604 if (Family == AF_IfNameIndex && CheckFree) {
605 if (FunI == II_if_freenameindex)
606 return true;
607 }
608
609 if (Family == AF_IfNameIndex && CheckAlloc) {
610 if (FunI == II_if_nameindex)
611 return true;
612 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000613
614 if (Family == AF_Alloca && CheckAlloc) {
Anna Zaks30d46682016-03-08 01:21:51 +0000615 if (FunI == II_alloca || FunI == II_win_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000616 return true;
617 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000618 }
Anna Zaks3d348342012-02-14 21:55:24 +0000619
Anna Zaksd79b8402014-10-03 21:48:59 +0000620 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000621 return false;
622
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000623 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000624 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
625 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
626 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
627 if (CheckFree)
628 return true;
629 } else if (OwnKind == OwnershipAttr::Returns) {
630 if (CheckAlloc)
631 return true;
632 }
633 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000634 }
Anna Zaks3d348342012-02-14 21:55:24 +0000635
Anna Zaks3d348342012-02-14 21:55:24 +0000636 return false;
637}
638
Anton Yartsev8b662702013-03-28 16:10:38 +0000639// Tells if the callee is one of the following:
640// 1) A global non-placement new/delete operator function.
641// 2) A global placement operator function with the single placement argument
642// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000643bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
644 ASTContext &C) const {
645 if (!FD)
646 return false;
647
648 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000649 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000650 Kind != OO_Delete && Kind != OO_Array_Delete)
651 return false;
652
Anton Yartsev8b662702013-03-28 16:10:38 +0000653 // Skip all operator new/delete methods.
654 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000655 return false;
656
657 // Return true if tested operator is a standard placement nothrow operator.
658 if (FD->getNumParams() == 2) {
659 QualType T = FD->getParamDecl(1)->getType();
660 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
661 return II->getName().equals("nothrow_t");
662 }
663
664 // Skip placement operators.
665 if (FD->getNumParams() != 1 || FD->isVariadic())
666 return false;
667
668 // One of the standard new/new[]/delete/delete[] non-placement operators.
669 return true;
670}
671
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000672llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
673 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
674 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
675 //
676 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
677 //
678 // One of the possible flags is M_ZERO, which means 'give me back an
679 // allocation which is already zeroed', like calloc.
680
681 // 2-argument kmalloc(), as used in the Linux kernel:
682 //
683 // void *kmalloc(size_t size, gfp_t flags);
684 //
685 // Has the similar flag value __GFP_ZERO.
686
687 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
688 // code could be shared.
689
690 ASTContext &Ctx = C.getASTContext();
691 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
692
693 if (!KernelZeroFlagVal.hasValue()) {
694 if (OS == llvm::Triple::FreeBSD)
695 KernelZeroFlagVal = 0x0100;
696 else if (OS == llvm::Triple::NetBSD)
697 KernelZeroFlagVal = 0x0002;
698 else if (OS == llvm::Triple::OpenBSD)
699 KernelZeroFlagVal = 0x0008;
700 else if (OS == llvm::Triple::Linux)
701 // __GFP_ZERO
702 KernelZeroFlagVal = 0x8000;
703 else
704 // FIXME: We need a more general way of getting the M_ZERO value.
705 // See also: O_CREAT in UnixAPIChecker.cpp.
706
707 // Fall back to normal malloc behavior on platforms where we don't
708 // know M_ZERO.
709 return None;
710 }
711
712 // We treat the last argument as the flags argument, and callers fall-back to
713 // normal malloc on a None return. This works for the FreeBSD kernel malloc
714 // as well as Linux kmalloc.
715 if (CE->getNumArgs() < 2)
716 return None;
717
718 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
719 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
720 if (!V.getAs<NonLoc>()) {
721 // The case where 'V' can be a location can only be due to a bad header,
722 // so in this case bail out.
723 return None;
724 }
725
726 NonLoc Flags = V.castAs<NonLoc>();
727 NonLoc ZeroFlag = C.getSValBuilder()
728 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
729 .castAs<NonLoc>();
730 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
731 Flags, ZeroFlag,
732 FlagsEx->getType());
733 if (MaskedFlagsUC.isUnknownOrUndef())
734 return None;
735 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
736
737 // Check if maskedFlags is non-zero.
738 ProgramStateRef TrueState, FalseState;
739 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
740
741 // If M_ZERO is set, treat this like calloc (initialized).
742 if (TrueState && !FalseState) {
743 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
744 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
745 }
746
747 return None;
748}
749
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000750void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000751 if (C.wasInlined)
752 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000753
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000754 const FunctionDecl *FD = C.getCalleeDecl(CE);
755 if (!FD)
756 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000757
Anna Zaks40a7eb32012-02-22 19:24:52 +0000758 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000759 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000760
761 if (FD->getKind() == Decl::Function) {
762 initIdentifierInfo(C.getASTContext());
763 IdentifierInfo *FunI = FD->getIdentifier();
764
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000765 if (FunI == II_malloc) {
766 if (CE->getNumArgs() < 1)
767 return;
768 if (CE->getNumArgs() < 3) {
769 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000770 if (CE->getNumArgs() == 1)
771 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000772 } else if (CE->getNumArgs() == 3) {
773 llvm::Optional<ProgramStateRef> MaybeState =
774 performKernelMalloc(CE, C, State);
775 if (MaybeState.hasValue())
776 State = MaybeState.getValue();
777 else
778 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
779 }
780 } else if (FunI == II_kmalloc) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000781 if (CE->getNumArgs() < 1)
782 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000783 llvm::Optional<ProgramStateRef> MaybeState =
784 performKernelMalloc(CE, C, State);
785 if (MaybeState.hasValue())
786 State = MaybeState.getValue();
787 else
788 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
789 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000790 if (CE->getNumArgs() < 1)
791 return;
792 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000793 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000794 } else if (FunI == II_realloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000795 State = ReallocMem(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000796 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000797 } else if (FunI == II_reallocf) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000798 State = ReallocMem(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000799 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000800 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000801 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000802 State = ProcessZeroAllocation(C, CE, 0, State);
803 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000804 } else if (FunI == II_free) {
805 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaks30d46682016-03-08 01:21:51 +0000806 } else if (FunI == II_strdup || FunI == II_win_strdup ||
807 FunI == II_wcsdup || FunI == II_win_wcsdup) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000808 State = MallocUpdateRefState(C, CE, State);
809 } else if (FunI == II_strndup) {
810 State = MallocUpdateRefState(C, CE, State);
Anna Zaks30d46682016-03-08 01:21:51 +0000811 } else if (FunI == II_alloca || FunI == II_win_alloca) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000812 if (CE->getNumArgs() < 1)
813 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000814 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
815 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000816 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000817 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000818 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000819 // as distinct from new/new[]/delete/delete[] expressions that are
820 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000821 // CXXDeleteExpr.
822 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000823 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000824 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
825 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000826 State = ProcessZeroAllocation(C, CE, 0, State);
827 }
828 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000829 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
830 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000831 State = ProcessZeroAllocation(C, CE, 0, State);
832 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000833 else if (K == OO_Delete || K == OO_Array_Delete)
834 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
835 else
836 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000837 } else if (FunI == II_if_nameindex) {
838 // Should we model this differently? We can allocate a fixed number of
839 // elements with zeros in the last one.
840 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
841 AF_IfNameIndex);
842 } else if (FunI == II_if_freenameindex) {
843 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000844 }
845 }
846
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000847 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000848 // Check all the attributes, if there are any.
849 // There can be multiple of these attributes.
850 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000851 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
852 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000853 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000854 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000855 break;
856 case OwnershipAttr::Takes:
857 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000858 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000859 break;
860 }
861 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000862 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000863 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000864}
865
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000866// Performs a 0-sized allocations check.
867ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
868 const Expr *E,
869 const unsigned AllocationSizeArg,
870 ProgramStateRef State) const {
871 if (!State)
872 return nullptr;
873
874 const Expr *Arg = nullptr;
875
876 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
877 Arg = CE->getArg(AllocationSizeArg);
878 }
879 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
880 if (NE->isArray())
881 Arg = NE->getArraySize();
882 else
883 return State;
884 }
885 else
886 llvm_unreachable("not a CallExpr or CXXNewExpr");
887
888 assert(Arg);
889
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000890 Optional<DefinedSVal> DefArgVal =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000891 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
892
893 if (!DefArgVal)
894 return State;
895
896 // Check if the allocation size is 0.
897 ProgramStateRef TrueState, FalseState;
898 SValBuilder &SvalBuilder = C.getSValBuilder();
899 DefinedSVal Zero =
900 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
901
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000902 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000903 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
904
905 if (TrueState && !FalseState) {
906 SVal retVal = State->getSVal(E, C.getLocationContext());
907 SymbolRef Sym = retVal.getAsLocSymbol();
908 if (!Sym)
909 return State;
910
911 const RefState *RS = State->get<RegionState>(Sym);
Devin Coughlin81771732015-09-22 22:47:14 +0000912 if (RS) {
913 if (RS->isAllocated())
914 return TrueState->set<RegionState>(Sym,
915 RefState::getAllocatedOfSizeZero(RS));
916 else
917 return State;
918 } else {
919 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
920 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
921 // tracked. Add zero-reallocated Sym to the state to catch references
922 // to zero-allocated memory.
923 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
924 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000925 }
926
927 // Assume the value is non-zero going forward.
928 assert(FalseState);
929 return FalseState;
930}
931
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000932static QualType getDeepPointeeType(QualType T) {
933 QualType Result = T, PointeeType = T->getPointeeType();
934 while (!PointeeType.isNull()) {
935 Result = PointeeType;
936 PointeeType = PointeeType->getPointeeType();
937 }
938 return Result;
939}
940
941static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
942
943 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
944 if (!ConstructE)
945 return false;
946
947 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
948 return false;
949
950 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
951
952 // Iterate over the constructor parameters.
David Majnemer59f77922016-06-24 04:05:48 +0000953 for (const auto *CtorParam : CtorD->parameters()) {
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000954
955 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
956 if (CtorParamPointeeT.isNull())
957 continue;
958
959 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
960
961 if (CtorParamPointeeT->getAsCXXRecordDecl())
962 return true;
963 }
964
965 return false;
966}
967
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000968void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
Anton Yartsev13df0362013-03-25 01:35:45 +0000969 CheckerContext &C) const {
970
971 if (NE->getNumPlacementArgs())
972 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
973 E = NE->placement_arg_end(); I != E; ++I)
974 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
975 checkUseAfterFree(Sym, C, *I);
976
Anton Yartsev13df0362013-03-25 01:35:45 +0000977 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
978 return;
979
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000980 ParentMap &PM = C.getLocationContext()->getParentMap();
981 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
982 return;
983
Anton Yartsev13df0362013-03-25 01:35:45 +0000984 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000985 // The return value from operator new is bound to a specified initialization
986 // value (if any) and we don't want to loose this value. So we call
987 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +0000988 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000989 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Anton Yartsev05789592013-03-28 17:05:19 +0000990 : AF_CXXNew);
Gabor Horvath73040272016-09-19 20:39:52 +0000991 State = addExtentSize(C, NE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000992 State = ProcessZeroAllocation(C, NE, 0, State);
Anton Yartsev13df0362013-03-25 01:35:45 +0000993 C.addTransition(State);
994}
995
Gabor Horvath73040272016-09-19 20:39:52 +0000996// Sets the extent value of the MemRegion allocated by
997// new expression NE to its size in Bytes.
998//
999ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1000 const CXXNewExpr *NE,
1001 ProgramStateRef State) {
1002 if (!State)
1003 return nullptr;
1004 SValBuilder &svalBuilder = C.getSValBuilder();
1005 SVal ElementCount;
1006 const LocationContext *LCtx = C.getLocationContext();
1007 const SubRegion *Region;
1008 if (NE->isArray()) {
1009 const Expr *SizeExpr = NE->getArraySize();
1010 ElementCount = State->getSVal(SizeExpr, C.getLocationContext());
1011 // Store the extent size for the (symbolic)region
1012 // containing the elements.
1013 Region = (State->getSVal(NE, LCtx))
1014 .getAsRegion()
1015 ->getAs<SubRegion>()
1016 ->getSuperRegion()
1017 ->getAs<SubRegion>();
1018 } else {
1019 ElementCount = svalBuilder.makeIntVal(1, true);
1020 Region = (State->getSVal(NE, LCtx)).getAsRegion()->getAs<SubRegion>();
1021 }
1022 assert(Region);
1023
1024 // Set the region's extent equal to the Size in Bytes.
1025 QualType ElementType = NE->getAllocatedType();
1026 ASTContext &AstContext = C.getASTContext();
1027 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1028
1029 if (Optional<DefinedOrUnknownSVal> DefinedSize =
1030 ElementCount.getAs<DefinedOrUnknownSVal>()) {
1031 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1032 // size in Bytes = ElementCount*TypeSize
1033 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1034 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1035 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1036 svalBuilder.getArrayIndexType());
1037 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1038 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1039 State = State->assume(extentMatchesSize, true);
1040 }
1041 return State;
1042}
1043
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001044void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001045 CheckerContext &C) const {
1046
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001047 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +00001048 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1049 checkUseAfterFree(Sym, C, DE->getArgument());
1050
Anton Yartsev13df0362013-03-25 01:35:45 +00001051 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1052 return;
1053
1054 ProgramStateRef State = C.getState();
1055 bool ReleasedAllocated;
1056 State = FreeMemAux(C, DE->getArgument(), DE, State,
1057 /*Hold*/false, ReleasedAllocated);
1058
1059 C.addTransition(State);
1060}
1061
Jordan Rose613f3c02013-03-09 00:59:10 +00001062static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1063 // If the first selector piece is one of the names below, assume that the
1064 // object takes ownership of the memory, promising to eventually deallocate it
1065 // with free().
1066 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1067 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1068 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
Alexander Kornienko9c104902015-12-28 13:06:58 +00001069 return FirstSlot == "dataWithBytesNoCopy" ||
1070 FirstSlot == "initWithBytesNoCopy" ||
1071 FirstSlot == "initWithCharactersNoCopy";
Anna Zaks0d6989b2012-06-22 02:04:31 +00001072}
1073
Jordan Rose613f3c02013-03-09 00:59:10 +00001074static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1075 Selector S = Call.getSelector();
1076
1077 // FIXME: We should not rely on fully-constrained symbols being folded.
1078 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1079 if (S.getNameForSlot(i).equals("freeWhenDone"))
1080 return !Call.getArgSVal(i).isZeroConstant();
1081
1082 return None;
1083}
1084
Anna Zaks67291b92012-11-13 03:18:01 +00001085void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1086 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001087 if (C.wasInlined)
1088 return;
1089
Jordan Rose613f3c02013-03-09 00:59:10 +00001090 if (!isKnownDeallocObjCMethodName(Call))
1091 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001092
Jordan Rose613f3c02013-03-09 00:59:10 +00001093 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1094 if (!*FreeWhenDone)
1095 return;
1096
1097 bool ReleasedAllocatedMemory;
1098 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1099 Call.getOriginExpr(), C.getState(),
1100 /*Hold=*/true, ReleasedAllocatedMemory,
1101 /*RetNullOnFailure=*/true);
1102
1103 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001104}
1105
Richard Smith852e9ce2013-11-27 01:46:48 +00001106ProgramStateRef
1107MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001108 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001109 ProgramStateRef State) const {
1110 if (!State)
1111 return nullptr;
1112
Richard Smith852e9ce2013-11-27 01:46:48 +00001113 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001114 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001115
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001116 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001117 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001118 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001119 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001120 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1121}
1122
1123ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1124 const CallExpr *CE,
1125 const Expr *SizeEx, SVal Init,
1126 ProgramStateRef State,
1127 AllocationFamily Family) {
1128 if (!State)
1129 return nullptr;
1130
1131 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1132 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001133}
1134
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001135ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001136 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001137 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001138 ProgramStateRef State,
1139 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001140 if (!State)
1141 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001142
Jordan Rosef69e65f2014-09-05 16:33:51 +00001143 // We expect the malloc functions to return a pointer.
1144 if (!Loc::isLocType(CE->getType()))
1145 return nullptr;
1146
Anna Zaks3563fde2012-06-07 03:57:32 +00001147 // Bind the return value to the symbolic value from the heap region.
1148 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1149 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001150 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001151 SValBuilder &svalBuilder = C.getSValBuilder();
1152 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001153 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1154 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001155 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001156
Jordy Rose674bd552010-07-04 00:00:41 +00001157 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +00001158 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001159
Jordy Rose674bd552010-07-04 00:00:41 +00001160 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001161 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001162 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001163 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001164 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001165 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001166 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001167 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001168 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001169 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001170 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001171
Anton Yartsev05789592013-03-28 17:05:19 +00001172 State = State->assume(extentMatchesSize, true);
1173 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001174 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001175
Anton Yartsev05789592013-03-28 17:05:19 +00001176 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001177}
1178
1179ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001180 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001181 ProgramStateRef State,
1182 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001183 if (!State)
1184 return nullptr;
1185
Anna Zaks40a7eb32012-02-22 19:24:52 +00001186 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001187 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001188
1189 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001190 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001191 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001192
Ted Kremenek90af9092010-12-02 07:49:45 +00001193 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001194 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001195
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001196 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001197 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001198}
1199
Anna Zaks40a7eb32012-02-22 19:24:52 +00001200ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1201 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001202 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001203 ProgramStateRef State) const {
1204 if (!State)
1205 return nullptr;
1206
Richard Smith852e9ce2013-11-27 01:46:48 +00001207 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001208 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001209
Anna Zaksfe6eb672012-08-24 02:28:20 +00001210 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001211
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001212 for (const auto &Arg : Att->args()) {
1213 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001214 Att->getOwnKind() == OwnershipAttr::Holds,
1215 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001216 if (StateI)
1217 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001218 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001219 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001220}
1221
Ted Kremenek49b1e382012-01-26 21:29:00 +00001222ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001223 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001224 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001225 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001226 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001227 bool &ReleasedAllocated,
1228 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001229 if (!State)
1230 return nullptr;
1231
Anna Zaksb508d292012-04-10 23:41:11 +00001232 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001233 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001234
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001235 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001236 ReleasedAllocated, ReturnsNullOnFailure);
1237}
1238
Anna Zaksa14c1d02012-11-13 19:47:40 +00001239/// Checks if the previous call to free on the given symbol failed - if free
1240/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001241static bool didPreviousFreeFail(ProgramStateRef State,
1242 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001243 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001244 if (Ret) {
1245 assert(*Ret && "We should not store the null return symbol");
1246 ConstraintManager &CMgr = State->getConstraintManager();
1247 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001248 RetStatusSymbol = *Ret;
1249 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001250 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001251 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001252}
1253
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001254AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001255 const Stmt *S) const {
1256 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001257 return AF_None;
1258
Anton Yartseve3377fb2013-04-04 23:46:29 +00001259 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001260 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001261
1262 if (!FD)
1263 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1264
Anton Yartsev05789592013-03-28 17:05:19 +00001265 ASTContext &Ctx = C.getASTContext();
1266
Anna Zaksd79b8402014-10-03 21:48:59 +00001267 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001268 return AF_Malloc;
1269
1270 if (isStandardNewDelete(FD, Ctx)) {
1271 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001272 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001273 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001274 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001275 return AF_CXXNewArray;
1276 }
1277
Anna Zaksd79b8402014-10-03 21:48:59 +00001278 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1279 return AF_IfNameIndex;
1280
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001281 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1282 return AF_Alloca;
1283
Anton Yartsev05789592013-03-28 17:05:19 +00001284 return AF_None;
1285 }
1286
Anton Yartseve3377fb2013-04-04 23:46:29 +00001287 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1288 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1289
1290 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001291 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1292
Anton Yartseve3377fb2013-04-04 23:46:29 +00001293 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001294 return AF_Malloc;
1295
1296 return AF_None;
1297}
1298
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001299bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001300 const Expr *E) const {
1301 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1302 // FIXME: This doesn't handle indirect calls.
1303 const FunctionDecl *FD = CE->getDirectCallee();
1304 if (!FD)
1305 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001306
Anton Yartsev05789592013-03-28 17:05:19 +00001307 os << *FD;
1308 if (!FD->isOverloadedOperator())
1309 os << "()";
1310 return true;
1311 }
1312
1313 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1314 if (Msg->isInstanceMessage())
1315 os << "-";
1316 else
1317 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001318 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001319 return true;
1320 }
1321
1322 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001323 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001324 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1325 << "'";
1326 return true;
1327 }
1328
1329 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001330 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001331 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1332 << "'";
1333 return true;
1334 }
1335
1336 return false;
1337}
1338
1339void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1340 const Expr *E) const {
1341 AllocationFamily Family = getAllocationFamily(C, E);
1342
1343 switch(Family) {
1344 case AF_Malloc: os << "malloc()"; return;
1345 case AF_CXXNew: os << "'new'"; return;
1346 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001347 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001348 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001349 case AF_None: llvm_unreachable("not a deallocation expression");
1350 }
1351}
1352
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001353void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001354 AllocationFamily Family) const {
1355 switch(Family) {
1356 case AF_Malloc: os << "free()"; return;
1357 case AF_CXXNew: os << "'delete'"; return;
1358 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001359 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001360 case AF_Alloca:
1361 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001362 }
1363}
1364
Anna Zaks0d6989b2012-06-22 02:04:31 +00001365ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1366 const Expr *ArgExpr,
1367 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001368 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001369 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001370 bool &ReleasedAllocated,
1371 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001372
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001373 if (!State)
1374 return nullptr;
1375
Anna Zaks67291b92012-11-13 03:18:01 +00001376 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001377 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001378 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001379 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001380
1381 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001382 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001383 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001384
Anna Zaksad01ef52012-02-14 00:26:13 +00001385 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001386 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001387 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001388 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001389 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001390
Jordy Rose3597b212010-06-07 19:32:37 +00001391 // Unknown values could easily be okay
1392 // Undefined values are handled elsewhere
1393 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001394 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001395
Jordy Rose3597b212010-06-07 19:32:37 +00001396 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001397
Jordy Rose3597b212010-06-07 19:32:37 +00001398 // Nonlocs can't be freed, of course.
1399 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1400 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001401 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001402 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001403 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001404
Jordy Rose3597b212010-06-07 19:32:37 +00001405 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001406
Jordy Rose3597b212010-06-07 19:32:37 +00001407 // Blocks might show up as heap data, but should not be free()d
1408 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001409 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001410 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001411 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001412
Jordy Rose3597b212010-06-07 19:32:37 +00001413 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001414
1415 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001416 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001417 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1418 // FIXME: at the time this code was written, malloc() regions were
1419 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1420 // This means that there isn't actually anything from HeapSpaceRegion
1421 // that should be freed, even though we allow it here.
1422 // Of course, free() can work on memory allocated outside the current
1423 // function, so UnknownSpaceRegion is always a possibility.
1424 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001425
1426 if (isa<AllocaRegion>(R))
1427 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1428 else
1429 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1430
Craig Topper0dbb7832014-05-27 02:45:47 +00001431 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001432 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001433
1434 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001435 // Various cases could lead to non-symbol values here.
1436 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001437 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001438 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001439
Anna Zaksc89ad072013-02-07 23:05:47 +00001440 SymbolRef SymBase = SrBase->getSymbol();
1441 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001442 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001443
Anton Yartseve3377fb2013-04-04 23:46:29 +00001444 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001445
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001446 // Memory returned by alloca() shouldn't be freed.
1447 if (RsBase->getAllocationFamily() == AF_Alloca) {
1448 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1449 return nullptr;
1450 }
1451
Anna Zaks93a21a82013-04-09 00:30:28 +00001452 // Check for double free first.
1453 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001454 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1455 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1456 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001457 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001458
Anna Zaks93a21a82013-04-09 00:30:28 +00001459 // If the pointer is allocated or escaped, but we are now trying to free it,
1460 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001461 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001462 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001463
1464 // Check if an expected deallocation function matches the real one.
1465 bool DeallocMatchesAlloc =
1466 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1467 if (!DeallocMatchesAlloc) {
1468 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001469 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001470 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001471 }
1472
1473 // Check if the memory location being freed is the actual location
1474 // allocated, or an offset.
1475 RegionOffset Offset = R->getAsOffset();
1476 if (Offset.isValid() &&
1477 !Offset.hasSymbolicOffset() &&
1478 Offset.getOffset() != 0) {
1479 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001480 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001481 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001482 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001483 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001484 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001485 }
1486
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001487 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001488 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001489
Anna Zaksa14c1d02012-11-13 19:47:40 +00001490 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001491 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001492
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001493 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001494 // failed.
1495 if (ReturnsNullOnFailure) {
1496 SVal RetVal = C.getSVal(ParentExpr);
1497 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1498 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001499 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1500 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001501 }
1502 }
1503
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001504 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1505 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001506 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001507 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001508 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001509 RefState::getRelinquished(Family,
1510 ParentExpr));
1511
1512 return State->set<RegionState>(SymBase,
1513 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001514}
1515
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001516Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001517MallocChecker::getCheckIfTracked(AllocationFamily Family,
1518 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001519 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001520 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001521 case AF_Alloca:
1522 case AF_IfNameIndex: {
1523 if (ChecksEnabled[CK_MallocChecker])
1524 return CK_MallocChecker;
1525
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001526 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001527 }
1528 case AF_CXXNew:
1529 case AF_CXXNewArray: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001530 if (IsALeakCheck) {
1531 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1532 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001533 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001534 else {
1535 if (ChecksEnabled[CK_NewDeleteChecker])
1536 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001537 }
1538 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001539 }
1540 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001541 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001542 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001543 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001544 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001545}
1546
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001547Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001548MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001549 const Stmt *AllocDeallocStmt,
1550 bool IsALeakCheck) const {
1551 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1552 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001553}
1554
1555Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001556MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1557 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001558 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1559 return CK_MallocChecker;
1560
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001561 const RefState *RS = C.getState()->get<RegionState>(Sym);
1562 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001563 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001564}
1565
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001566bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001567 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001568 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001569 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001570 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001571 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001572 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001573 else
1574 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001575
Jordy Rose3597b212010-06-07 19:32:37 +00001576 return true;
1577}
1578
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001579bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001580 const MemRegion *MR) {
1581 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +00001582 case MemRegion::FunctionCodeRegionKind: {
1583 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001584 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001585 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001586 else
1587 os << "the address of a function";
1588 return true;
1589 }
Artem Dergachev73f018e2016-01-13 13:49:29 +00001590 case MemRegion::BlockCodeRegionKind:
Jordy Rose3597b212010-06-07 19:32:37 +00001591 os << "block text";
1592 return true;
1593 case MemRegion::BlockDataRegionKind:
1594 // FIXME: where the block came from?
1595 os << "a block";
1596 return true;
1597 default: {
1598 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001599
Anna Zaks8158ef02012-01-04 23:54:01 +00001600 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001601 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1602 const VarDecl *VD;
1603 if (VR)
1604 VD = VR->getDecl();
1605 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001606 VD = nullptr;
1607
Jordy Rose3597b212010-06-07 19:32:37 +00001608 if (VD)
1609 os << "the address of the local variable '" << VD->getName() << "'";
1610 else
1611 os << "the address of a local stack variable";
1612 return true;
1613 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001614
1615 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001616 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1617 const VarDecl *VD;
1618 if (VR)
1619 VD = VR->getDecl();
1620 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001621 VD = nullptr;
1622
Jordy Rose3597b212010-06-07 19:32:37 +00001623 if (VD)
1624 os << "the address of the parameter '" << VD->getName() << "'";
1625 else
1626 os << "the address of a parameter";
1627 return true;
1628 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001629
1630 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001631 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1632 const VarDecl *VD;
1633 if (VR)
1634 VD = VR->getDecl();
1635 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001636 VD = nullptr;
1637
Jordy Rose3597b212010-06-07 19:32:37 +00001638 if (VD) {
1639 if (VD->isStaticLocal())
1640 os << "the address of the static variable '" << VD->getName() << "'";
1641 else
1642 os << "the address of the global variable '" << VD->getName() << "'";
1643 } else
1644 os << "the address of a global variable";
1645 return true;
1646 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001647
1648 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001649 }
1650 }
1651}
1652
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001653void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1654 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001655 const Expr *DeallocExpr) const {
1656
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001657 if (!ChecksEnabled[CK_MallocChecker] &&
1658 !ChecksEnabled[CK_NewDeleteChecker])
1659 return;
1660
1661 Optional<MallocChecker::CheckKind> CheckKind =
1662 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001663 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001664 return;
1665
Devin Coughline39bd402015-09-16 22:03:05 +00001666 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001667 if (!BT_BadFree[*CheckKind])
1668 BT_BadFree[*CheckKind].reset(
1669 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1670
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001671 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001672 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001673
Jordy Rose3597b212010-06-07 19:32:37 +00001674 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001675 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1676 MR = ER->getSuperRegion();
1677
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001678 os << "Argument to ";
1679 if (!printAllocDeallocName(os, C, DeallocExpr))
1680 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001681
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001682 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001683 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001684 : SummarizeValue(os, ArgVal);
1685 if (Summarized)
1686 os << ", which is not memory allocated by ";
1687 else
1688 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001689
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001690 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001691
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001692 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001693 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001694 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001695 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001696 }
1697}
1698
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001699void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001700 SourceRange Range) const {
1701
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001702 Optional<MallocChecker::CheckKind> CheckKind;
1703
1704 if (ChecksEnabled[CK_MallocChecker])
1705 CheckKind = CK_MallocChecker;
1706 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1707 CheckKind = CK_MismatchedDeallocatorChecker;
1708 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001709 return;
1710
Devin Coughline39bd402015-09-16 22:03:05 +00001711 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001712 if (!BT_FreeAlloca[*CheckKind])
1713 BT_FreeAlloca[*CheckKind].reset(
1714 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1715
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001716 auto R = llvm::make_unique<BugReport>(
1717 *BT_FreeAlloca[*CheckKind],
1718 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001719 R->markInteresting(ArgVal.getAsRegion());
1720 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001721 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001722 }
1723}
1724
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001725void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001726 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001727 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001728 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001729 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001730 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001731
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001732 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001733 return;
1734
Devin Coughline39bd402015-09-16 22:03:05 +00001735 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001736 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001737 BT_MismatchedDealloc.reset(
1738 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1739 "Bad deallocator", "Memory Error"));
1740
Anton Yartsev05789592013-03-28 17:05:19 +00001741 SmallString<100> buf;
1742 llvm::raw_svector_ostream os(buf);
1743
1744 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1745 SmallString<20> AllocBuf;
1746 llvm::raw_svector_ostream AllocOs(AllocBuf);
1747 SmallString<20> DeallocBuf;
1748 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1749
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001750 if (OwnershipTransferred) {
1751 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1752 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001753 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001754 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001755
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001756 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001757
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001758 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1759 os << " allocated by " << AllocOs.str();
1760 } else {
1761 os << "Memory";
1762 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1763 os << " allocated by " << AllocOs.str();
1764
1765 os << " should be deallocated by ";
1766 printExpectedDeallocName(os, RS->getAllocationFamily());
1767
1768 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1769 os << ", not " << DeallocOs.str();
1770 }
Anton Yartsev05789592013-03-28 17:05:19 +00001771
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001772 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001773 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001774 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001775 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001776 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001777 }
1778}
1779
Anna Zaksc89ad072013-02-07 23:05:47 +00001780void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001781 SourceRange Range, const Expr *DeallocExpr,
1782 const Expr *AllocExpr) const {
1783
Anton Yartsev05789592013-03-28 17:05:19 +00001784
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001785 if (!ChecksEnabled[CK_MallocChecker] &&
1786 !ChecksEnabled[CK_NewDeleteChecker])
1787 return;
1788
1789 Optional<MallocChecker::CheckKind> CheckKind =
1790 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001791 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001792 return;
1793
Devin Coughline39bd402015-09-16 22:03:05 +00001794 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001795 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001796 return;
1797
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001798 if (!BT_OffsetFree[*CheckKind])
1799 BT_OffsetFree[*CheckKind].reset(
1800 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001801
1802 SmallString<100> buf;
1803 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001804 SmallString<20> AllocNameBuf;
1805 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001806
1807 const MemRegion *MR = ArgVal.getAsRegion();
1808 assert(MR && "Only MemRegion based symbols can have offset free errors");
1809
1810 RegionOffset Offset = MR->getAsOffset();
1811 assert((Offset.isValid() &&
1812 !Offset.hasSymbolicOffset() &&
1813 Offset.getOffset() != 0) &&
1814 "Only symbols with a valid offset can have offset free errors");
1815
1816 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1817
Anton Yartsev05789592013-03-28 17:05:19 +00001818 os << "Argument to ";
1819 if (!printAllocDeallocName(os, C, DeallocExpr))
1820 os << "deallocator";
1821 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001822 << offsetBytes
1823 << " "
1824 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001825 << " from the start of ";
1826 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1827 os << "memory allocated by " << AllocNameOs.str();
1828 else
1829 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001830
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001831 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001832 R->markInteresting(MR->getBaseRegion());
1833 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001834 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001835}
1836
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001837void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1838 SymbolRef Sym) const {
1839
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001840 if (!ChecksEnabled[CK_MallocChecker] &&
1841 !ChecksEnabled[CK_NewDeleteChecker])
1842 return;
1843
1844 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001845 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001846 return;
1847
Devin Coughline39bd402015-09-16 22:03:05 +00001848 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001849 if (!BT_UseFree[*CheckKind])
1850 BT_UseFree[*CheckKind].reset(new BugType(
1851 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001852
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001853 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1854 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001855
1856 R->markInteresting(Sym);
1857 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001858 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001859 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001860 }
1861}
1862
1863void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001864 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001865 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001866
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001867 if (!ChecksEnabled[CK_MallocChecker] &&
1868 !ChecksEnabled[CK_NewDeleteChecker])
1869 return;
1870
1871 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001872 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001873 return;
1874
Devin Coughline39bd402015-09-16 22:03:05 +00001875 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001876 if (!BT_DoubleFree[*CheckKind])
1877 BT_DoubleFree[*CheckKind].reset(
1878 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001879
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001880 auto R = llvm::make_unique<BugReport>(
1881 *BT_DoubleFree[*CheckKind],
1882 (Released ? "Attempt to free released memory"
1883 : "Attempt to free non-owned memory"),
1884 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001885 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001886 R->markInteresting(Sym);
1887 if (PrevSym)
1888 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001889 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001890 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001891 }
1892}
1893
Jordan Rose656fdd52014-01-08 18:46:55 +00001894void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1895
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001896 if (!ChecksEnabled[CK_NewDeleteChecker])
1897 return;
1898
1899 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001900 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001901 return;
1902
Devin Coughline39bd402015-09-16 22:03:05 +00001903 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00001904 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001905 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1906 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001907
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001908 auto R = llvm::make_unique<BugReport>(
1909 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00001910
1911 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001912 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001913 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00001914 }
1915}
1916
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001917void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1918 SourceRange Range,
1919 SymbolRef Sym) const {
1920
1921 if (!ChecksEnabled[CK_MallocChecker] &&
1922 !ChecksEnabled[CK_NewDeleteChecker])
1923 return;
1924
1925 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1926
1927 if (!CheckKind.hasValue())
1928 return;
1929
Devin Coughline39bd402015-09-16 22:03:05 +00001930 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001931 if (!BT_UseZerroAllocated[*CheckKind])
1932 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
1933 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
1934
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001935 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
1936 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001937
1938 R->addRange(Range);
1939 if (Sym) {
1940 R->markInteresting(Sym);
1941 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1942 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001943 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001944 }
1945}
1946
Anna Zaks40a7eb32012-02-22 19:24:52 +00001947ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1948 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001949 bool FreesOnFail,
1950 ProgramStateRef State) const {
1951 if (!State)
1952 return nullptr;
1953
Anna Zaksb508d292012-04-10 23:41:11 +00001954 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001955 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001956
Ted Kremenek90af9092010-12-02 07:49:45 +00001957 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001958 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001959 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001960 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001961 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001962 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001963
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001964 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001965
Ted Kremenek90af9092010-12-02 07:49:45 +00001966 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001967 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001968
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001969 // Get the size argument. If there is no size arg then give up.
1970 const Expr *Arg1 = CE->getArg(1);
1971 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00001972 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001973
1974 // Get the value of the size argument.
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001975 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001976 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001977 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001978 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001979
1980 // Compare the size argument to 0.
1981 DefinedOrUnknownSVal SizeZero =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001982 svalBuilder.evalEQ(State, Arg1Val,
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001983 svalBuilder.makeIntValWithPtrWidth(0, false));
1984
Anna Zaksd56c8792012-02-13 18:05:39 +00001985 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001986 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001987 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001988 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001989 // We only assume exceptional states if they are definitely true; if the
1990 // state is under-constrained, assume regular realloc behavior.
1991 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1992 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1993
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001994 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001995 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001996 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001997 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001998 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001999 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002000 }
2001
Anna Zaksd56c8792012-02-13 18:05:39 +00002002 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00002003 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002004
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002005 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00002006 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002007 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002008 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002009 SymbolRef ToPtr = RetVal.getAsSymbol();
2010 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00002011 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00002012
Anna Zaksfe6eb672012-08-24 02:28:20 +00002013 bool ReleasedAllocated = false;
2014
Anna Zaksd56c8792012-02-13 18:05:39 +00002015 // If the size is 0, free the memory.
2016 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00002017 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2018 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00002019 // The semantics of the return value are:
2020 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00002021 // to free() is returned. We just free the input pointer and do not add
2022 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00002023 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00002024 }
2025
2026 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00002027 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002028 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00002029
Anna Zaksd56c8792012-02-13 18:05:39 +00002030 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
2031 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002032 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00002033 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00002034
Anna Zaks75cfbb62012-09-12 22:57:34 +00002035 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2036 if (FreesOnFail)
2037 Kind = RPIsFreeOnFailure;
2038 else if (!ReleasedAllocated)
2039 Kind = RPDoNotTrackAfterFailure;
2040
Anna Zaksfe6eb672012-08-24 02:28:20 +00002041 // Record the info about the reallocated symbol so that we could properly
2042 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00002043 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00002044 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00002045 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00002046 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002047 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002048 }
Craig Topper0dbb7832014-05-27 02:45:47 +00002049 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00002050}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002051
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002052ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002053 ProgramStateRef State) {
2054 if (!State)
2055 return nullptr;
2056
Anna Zaksb508d292012-04-10 23:41:11 +00002057 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002058 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002059
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002060 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002061 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002062 SVal count = State->getSVal(CE->getArg(0), LCtx);
2063 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
2064 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002065 svalBuilder.getContext().getSizeType());
Ted Kremenek90af9092010-12-02 07:49:45 +00002066 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002067
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002068 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002069}
2070
Anna Zaksfc2e1532012-03-21 19:45:08 +00002071LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002072MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2073 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002074 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002075 // Walk the ExplodedGraph backwards and find the first node that referred to
2076 // the tracked symbol.
2077 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002078 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002079
2080 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002081 ProgramStateRef State = N->getState();
2082 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002083 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002084
2085 // Find the most recent expression bound to the symbol in the current
2086 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002087 if (!ReferenceRegion) {
2088 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2089 SVal Val = State->getSVal(MR);
2090 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002091 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002092 // Do not show local variables belonging to a function other than
2093 // where the error is reported.
2094 if (!VR ||
2095 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2096 ReferenceRegion = MR;
2097 }
2098 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002099 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002100
Anna Zaks486a0ff2015-02-05 01:02:53 +00002101 // Allocation node, is the last node in the current or parent context in
2102 // which the symbol was tracked.
2103 const LocationContext *NContext = N->getLocationContext();
2104 if (NContext == LeakContext ||
2105 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002106 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002107 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002108 }
2109
Anna Zaksa043d0c2013-01-08 00:25:29 +00002110 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002111}
2112
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002113void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2114 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002115
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002116 if (!ChecksEnabled[CK_MallocChecker] &&
2117 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002118 return;
2119
Anton Yartsev9907fc92015-03-04 23:18:21 +00002120 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002121 assert(RS && "cannot leak an untracked symbol");
2122 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002123
2124 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002125 return;
2126
Anton Yartsev2487dd62015-03-10 22:24:21 +00002127 Optional<MallocChecker::CheckKind>
2128 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002129
Anton Yartsev2487dd62015-03-10 22:24:21 +00002130 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002131 return;
2132
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002133 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002134 if (!BT_Leak[*CheckKind]) {
2135 BT_Leak[*CheckKind].reset(
2136 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002137 // Leaks should not be reported if they are post-dominated by a sink:
2138 // (1) Sinks are higher importance bugs.
2139 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2140 // with __noreturn functions such as assert() or exit(). We choose not
2141 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002142 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002143 }
2144
Anna Zaksdf901a42012-02-23 21:38:21 +00002145 // Most bug reports are cached at the location where they occurred.
2146 // With leaks, we want to unique them by the location where they were
2147 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002148 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002149 const ExplodedNode *AllocNode = nullptr;
2150 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002151 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002152
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002153 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
Anton Yartsev6e499252013-04-05 02:25:02 +00002154 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002155 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2156 C.getSourceManager(),
2157 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002158
Anna Zaksfc2e1532012-03-21 19:45:08 +00002159 SmallString<200> buf;
2160 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002161 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002162 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002163 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002164 } else {
2165 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002166 }
2167
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002168 auto R = llvm::make_unique<BugReport>(
2169 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2170 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002171 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002172 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002173 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002174}
2175
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002176void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2177 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002178{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002179 if (!SymReaper.hasDeadSymbols())
2180 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002181
Ted Kremenek49b1e382012-01-26 21:29:00 +00002182 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002183 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002184 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002185
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002186 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002187 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2188 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002189 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002190 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002191 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002192 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002193
Zhongxing Xuc7460962009-11-13 07:48:11 +00002194 }
2195 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002196
Anna Zaksd56c8792012-02-13 18:05:39 +00002197 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002198 ReallocPairsTy RP = state->get<ReallocPairs>();
2199 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002200 if (SymReaper.isDead(I->first) ||
2201 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002202 state = state->remove<ReallocPairs>(I->first);
2203 }
2204 }
2205
Anna Zaks67291b92012-11-13 03:18:01 +00002206 // Cleanup the FreeReturnValue Map.
2207 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2208 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2209 if (SymReaper.isDead(I->first) ||
2210 SymReaper.isDead(I->second)) {
2211 state = state->remove<FreeReturnValue>(I->first);
2212 }
2213 }
2214
Anna Zaksdf901a42012-02-23 21:38:21 +00002215 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002216 ExplodedNode *N = C.getPredecessor();
2217 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002218 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002219 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2220 if (N) {
2221 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002222 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002223 reportLeak(*I, N, C);
2224 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002225 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002226 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002227
Anna Zaksdf901a42012-02-23 21:38:21 +00002228 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002229}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002230
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002231void MallocChecker::checkPreCall(const CallEvent &Call,
2232 CheckerContext &C) const {
2233
Jordan Rose656fdd52014-01-08 18:46:55 +00002234 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2235 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2236 if (!Sym || checkDoubleDelete(Sym, C))
2237 return;
2238 }
2239
Anna Zaks46d01602012-05-18 01:16:10 +00002240 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002241 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2242 const FunctionDecl *FD = FC->getDecl();
2243 if (!FD)
2244 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002245
Anna Zaksd79b8402014-10-03 21:48:59 +00002246 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002247 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002248 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2249 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2250 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002251 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002252
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002253 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002254 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002255 return;
2256 }
2257
2258 // Check if the callee of a method is deleted.
2259 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2260 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2261 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2262 return;
2263 }
2264
2265 // Check arguments for being used after free.
2266 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2267 SVal ArgSVal = Call.getArgSVal(I);
2268 if (ArgSVal.getAs<Loc>()) {
2269 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002270 if (!Sym)
2271 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002272 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002273 return;
2274 }
2275 }
2276}
2277
Anna Zaksa1b227b2012-02-08 23:16:56 +00002278void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2279 const Expr *E = S->getRetValue();
2280 if (!E)
2281 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002282
2283 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002284 ProgramStateRef State = C.getState();
2285 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002286 SymbolRef Sym = RetVal.getAsSymbol();
2287 if (!Sym)
2288 // If we are returning a field of the allocated struct or an array element,
2289 // the callee could still free the memory.
2290 // TODO: This logic should be a part of generic symbol escape callback.
2291 if (const MemRegion *MR = RetVal.getAsRegion())
2292 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2293 if (const SymbolicRegion *BMR =
2294 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2295 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002296
Anna Zaks3aa52252012-02-11 21:44:39 +00002297 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002298 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002299 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002300}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002301
Anna Zaks9fe80982012-03-22 00:57:20 +00002302// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002303// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002304// needed.
2305void MallocChecker::checkPostStmt(const BlockExpr *BE,
2306 CheckerContext &C) const {
2307
2308 // Scan the BlockDecRefExprs for any object the retain count checker
2309 // may be tracking.
2310 if (!BE->getBlockDecl()->hasCaptures())
2311 return;
2312
2313 ProgramStateRef state = C.getState();
2314 const BlockDataRegion *R =
2315 cast<BlockDataRegion>(state->getSVal(BE,
2316 C.getLocationContext()).getAsRegion());
2317
2318 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2319 E = R->referenced_vars_end();
2320
2321 if (I == E)
2322 return;
2323
2324 SmallVector<const MemRegion*, 10> Regions;
2325 const LocationContext *LC = C.getLocationContext();
2326 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2327
2328 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002329 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002330 if (VR->getSuperRegion() == R) {
2331 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2332 }
2333 Regions.push_back(VR);
2334 }
2335
2336 state =
2337 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2338 Regions.data() + Regions.size()).getState();
2339 C.addTransition(state);
2340}
2341
Anna Zaks46d01602012-05-18 01:16:10 +00002342bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002343 assert(Sym);
2344 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002345 return (RS && RS->isReleased());
2346}
2347
2348bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2349 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002350
Jordan Rose656fdd52014-01-08 18:46:55 +00002351 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002352 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2353 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002354 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002355
Anna Zaksa1b227b2012-02-08 23:16:56 +00002356 return false;
2357}
2358
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002359void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2360 const Stmt *S) const {
2361 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002362
Devin Coughlin81771732015-09-22 22:47:14 +00002363 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2364 if (RS->isAllocatedOfSizeZero())
2365 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2366 }
2367 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2368 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2369 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002370}
2371
Jordan Rose656fdd52014-01-08 18:46:55 +00002372bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2373
2374 if (isReleased(Sym, C)) {
2375 ReportDoubleDelete(C, Sym);
2376 return true;
2377 }
2378 return false;
2379}
2380
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002381// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002382void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2383 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002384 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002385 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002386 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002387 checkUseZeroAllocated(Sym, C, S);
2388 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002389}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002390
Anna Zaksbb1ef902012-02-11 21:02:35 +00002391// If a symbolic region is assumed to NULL (or another constant), stop tracking
2392// it - assuming that allocation failed on this path.
2393ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2394 SVal Cond,
2395 bool Assumption) const {
2396 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002397 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002398 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002399 ConstraintManager &CMgr = state->getConstraintManager();
2400 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2401 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002402 state = state->remove<RegionState>(I.getKey());
2403 }
2404
Anna Zaksd56c8792012-02-13 18:05:39 +00002405 // Realloc returns 0 when reallocation fails, which means that we should
2406 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002407 ReallocPairsTy RP = state->get<ReallocPairs>();
2408 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002409 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002410 ConstraintManager &CMgr = state->getConstraintManager();
2411 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002412 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002413 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002414
Anna Zaks75cfbb62012-09-12 22:57:34 +00002415 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2416 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2417 if (RS->isReleased()) {
2418 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002419 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002420 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002421 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2422 state = state->remove<RegionState>(ReallocSym);
2423 else
2424 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002425 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002426 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002427 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002428 }
2429
Anna Zaksbb1ef902012-02-11 21:02:35 +00002430 return state;
2431}
2432
Anna Zaks8ebeb642013-06-08 00:29:29 +00002433bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002434 const CallEvent *Call,
2435 ProgramStateRef State,
2436 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002437 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002438 EscapingSymbol = nullptr;
2439
Jordan Rose2a833ca2014-01-15 17:25:15 +00002440 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002441 // TODO: If we want to be more optimistic here, we'll need to make sure that
2442 // regions escape to C++ containers. They seem to do that even now, but for
2443 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002444 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002445 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002446
Jordan Rose742920c2012-07-02 19:27:35 +00002447 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002448 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002449 // If it's not a framework call, or if it takes a callback, assume it
2450 // can free memory.
Anna Zaksfe1eca52015-10-27 20:19:45 +00002451 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002452 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002453
Jordan Rose613f3c02013-03-09 00:59:10 +00002454 // If it's a method we know about, handle it explicitly post-call.
2455 // This should happen before the "freeWhenDone" check below.
2456 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002457 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002458
Jordan Rose613f3c02013-03-09 00:59:10 +00002459 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2460 // about, we can't be sure that the object will use free() to deallocate the
2461 // memory, so we can't model it explicitly. The best we can do is use it to
2462 // decide whether the pointer escapes.
2463 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002464 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002465
Jordan Rose613f3c02013-03-09 00:59:10 +00002466 // If the first selector piece ends with "NoCopy", and there is no
2467 // "freeWhenDone" parameter set to zero, we know ownership is being
2468 // transferred. Again, though, we can't be sure that the object will use
2469 // free() to deallocate the memory, so we can't model it explicitly.
2470 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002471 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002472 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002473
Anna Zaks42908c72012-06-19 05:10:32 +00002474 // If the first selector starts with addPointer, insertPointer,
2475 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2476 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002477 // that the pointers get freed by following the container itself.
2478 if (FirstSlot.startswith("addPointer") ||
2479 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002480 FirstSlot.startswith("replacePointer") ||
2481 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002482 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002483 }
2484
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002485 // We should escape receiver on call to 'init'. This is especially relevant
2486 // to the receiver, as the corresponding symbol is usually not referenced
2487 // after the call.
2488 if (Msg->getMethodFamily() == OMF_init) {
2489 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2490 return true;
2491 }
Anna Zaks737926b2013-05-31 22:39:13 +00002492
Jordan Rose742920c2012-07-02 19:27:35 +00002493 // Otherwise, assume that the method does not free memory.
2494 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002495 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002496 }
2497
Jordan Rose742920c2012-07-02 19:27:35 +00002498 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002499 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002500 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002501 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002502
Jordan Rose742920c2012-07-02 19:27:35 +00002503 ASTContext &ASTC = State->getStateManager().getContext();
2504
2505 // If it's one of the allocation functions we can reason about, we model
2506 // its behavior explicitly.
2507 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002508 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002509
2510 // If it's not a system call, assume it frees memory.
2511 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002512 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002513
2514 // White list the system functions whose arguments escape.
2515 const IdentifierInfo *II = FD->getIdentifier();
2516 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002517 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002518 StringRef FName = II->getName();
2519
Jordan Rose742920c2012-07-02 19:27:35 +00002520 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002521 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002522 if (FName.endswith("NoCopy")) {
2523 // Look for the deallocator argument. We know that the memory ownership
2524 // is not transferred only if the deallocator argument is
2525 // 'kCFAllocatorNull'.
2526 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2527 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2528 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2529 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2530 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002531 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002532 }
2533 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002534 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002535 }
2536
Jordan Rose742920c2012-07-02 19:27:35 +00002537 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002538 // 'closefn' is specified (and if that function does free memory),
2539 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002540 // Currently, we do not inspect the 'closefn' function (PR12101).
2541 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002542 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002543 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002544
2545 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2546 // these leaks might be intentional when setting the buffer for stdio.
2547 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2548 if (FName == "setbuf" || FName =="setbuffer" ||
2549 FName == "setlinebuf" || FName == "setvbuf") {
2550 if (Call->getNumArgs() >= 1) {
2551 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2552 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2553 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2554 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002555 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002556 }
2557 }
2558
2559 // A bunch of other functions which either take ownership of a pointer or
2560 // wrap the result up in a struct or object, meaning it can be freed later.
2561 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2562 // but the Malloc checker cannot differentiate between them. The right way
2563 // of doing this would be to implement a pointer escapes callback.
2564 if (FName == "CGBitmapContextCreate" ||
2565 FName == "CGBitmapContextCreateWithData" ||
2566 FName == "CVPixelBufferCreateWithBytes" ||
2567 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2568 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002569 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002570 }
2571
Anna Zaks03f48332016-01-06 00:32:56 +00002572 if (FName == "postEvent" &&
2573 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2574 return true;
2575 }
2576
2577 if (FName == "postEvent" &&
2578 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2579 return true;
2580 }
2581
Artem Dergachev85c92112016-12-16 12:21:55 +00002582 if (FName == "connectImpl" &&
2583 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2584 return true;
2585 }
2586
Jordan Rose7ab01822012-07-02 19:27:51 +00002587 // Handle cases where we know a buffer's /address/ can escape.
2588 // Note that the above checks handle some special cases where we know that
2589 // even though the address escapes, it's still our responsibility to free the
2590 // buffer.
2591 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002592 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002593
2594 // Otherwise, assume that the function does not free memory.
2595 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002596 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002597}
2598
Anna Zaks333481b2013-03-28 23:15:29 +00002599static bool retTrue(const RefState *RS) {
2600 return true;
2601}
2602
2603static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2604 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2605 RS->getAllocationFamily() == AF_CXXNew);
2606}
2607
Anna Zaksdc154152012-12-20 00:38:25 +00002608ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2609 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002610 const CallEvent *Call,
2611 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002612 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2613}
2614
2615ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2616 const InvalidatedSymbols &Escaped,
2617 const CallEvent *Call,
2618 PointerEscapeKind Kind) const {
2619 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2620 &checkIfNewOrNewArrayFamily);
2621}
2622
2623ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2624 const InvalidatedSymbols &Escaped,
2625 const CallEvent *Call,
2626 PointerEscapeKind Kind,
2627 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002628 // If we know that the call does not free memory, or we want to process the
2629 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002630 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002631 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002632 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2633 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002634 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002635 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002636 }
Anna Zaks3d348342012-02-14 21:55:24 +00002637
Anna Zaksdc154152012-12-20 00:38:25 +00002638 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002639 E = Escaped.end();
2640 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002641 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002642
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002643 if (EscapingSymbol && EscapingSymbol != sym)
2644 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002645
Anna Zaks0d6989b2012-06-22 02:04:31 +00002646 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002647 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2648 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002649 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002650 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2651 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002652 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002653 }
Anna Zaks3d348342012-02-14 21:55:24 +00002654 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002655}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002656
Jordy Rosebf38f202012-03-18 07:43:35 +00002657static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2658 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002659 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2660 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002661
Jordan Rose0c153cb2012-11-02 01:54:06 +00002662 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002663 I != E; ++I) {
2664 SymbolRef sym = I.getKey();
2665 if (!currMap.lookup(sym))
2666 return sym;
2667 }
2668
Craig Topper0dbb7832014-05-27 02:45:47 +00002669 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002670}
2671
Anna Zaks2b5bb972012-02-09 06:25:51 +00002672PathDiagnosticPiece *
2673MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2674 const ExplodedNode *PrevN,
2675 BugReporterContext &BRC,
2676 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002677 ProgramStateRef state = N->getState();
2678 ProgramStateRef statePrev = PrevN->getState();
2679
2680 const RefState *RS = state->get<RegionState>(Sym);
2681 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002682 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002683 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002684
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002685 const Stmt *S = PathDiagnosticLocation::getStmt(N);
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002686 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002687 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002688
Jordan Rose681cce92012-07-10 22:07:42 +00002689 // FIXME: We will eventually need to handle non-statement-based events
2690 // (__attribute__((cleanup))).
2691
Anna Zaks2b5bb972012-02-09 06:25:51 +00002692 // Find out if this is an interesting point and what is the kind.
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002693 const char *Msg = nullptr;
2694 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002695 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002696 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002697 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002698 StackHint = new StackHintGeneratorForSymbol(Sym,
2699 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002700 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002701 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002702 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002703 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002704 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002705 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002706 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002707 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002708 Mode = ReallocationFailed;
2709 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002710 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002711 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002712
Jordy Rose21ff76e2012-03-24 03:15:09 +00002713 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2714 // Is it possible to fail two reallocs WITHOUT testing in between?
2715 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2716 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002717 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002718 FailedReallocSymbol = sym;
2719 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002720 }
2721
2722 // We are in a special mode if a reallocation failed later in the path.
2723 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002724 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002725
Jordy Rose21ff76e2012-03-24 03:15:09 +00002726 // Is this is the first appearance of the reallocated symbol?
2727 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002728 // We're at the reallocation point.
2729 Msg = "Attempt to reallocate memory";
2730 StackHint = new StackHintGeneratorForSymbol(Sym,
2731 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002732 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002733 Mode = Normal;
2734 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002735 }
2736
Anna Zaks2b5bb972012-02-09 06:25:51 +00002737 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002738 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002739 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002740
2741 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002742 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002743 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002744 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002745}
2746
Anna Zaks263b7e02012-05-02 00:05:20 +00002747void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2748 const char *NL, const char *Sep) const {
2749
2750 RegionStateTy RS = State->get<RegionState>();
2751
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002752 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002753 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002754 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002755 const RefState *RefS = State->get<RegionState>(I.getKey());
2756 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002757 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002758 if (!CheckKind.hasValue())
2759 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002760
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002761 I.getKey()->dumpToStream(Out);
2762 Out << " : ";
2763 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002764 if (CheckKind.hasValue())
2765 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002766 Out << NL;
2767 }
2768 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002769}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002770
Anna Zakse4cfcd42013-04-16 00:22:55 +00002771void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2772 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002773 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002774 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2775 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002776 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2777 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2778 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002779 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00002780 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002781 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002782 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002783}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002784
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002785#define REGISTER_CHECKER(name) \
2786 void ento::register##name(CheckerManager &mgr) { \
2787 registerCStringCheckerBasic(mgr); \
2788 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002789 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2790 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002791 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2792 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2793 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002794
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002795REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002796REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002797REGISTER_CHECKER(MismatchedDeallocatorChecker)