blob: 5730517289bb005fbe4f7ef4f5e994032e06c19d [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),
Anna Zaksbbec97c2017-03-09 00:01:01 +0000177 II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr),
178 II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr),
179 II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr),
Leslie Zhaie3986c52017-04-26 05:33:14 +0000180 II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr),
181 II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr),
182 II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr),
183 II_g_try_realloc_n(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000184
185 /// In pessimistic mode, the checker assumes that it does not know which
186 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000187 enum CheckKind {
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000188 CK_MallocChecker,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000189 CK_NewDeleteChecker,
190 CK_NewDeleteLeaksChecker,
191 CK_MismatchedDeallocatorChecker,
192 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000193 };
194
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000195 enum class MemoryOperationKind {
Anna Zaksd79b8402014-10-03 21:48:59 +0000196 MOK_Allocate,
197 MOK_Free,
198 MOK_Any
199 };
200
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000201 DefaultBool IsOptimistic;
202
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000203 DefaultBool ChecksEnabled[CK_NumCheckKinds];
204 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000205
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000206 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000207 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000208 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
209 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000210 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000211 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000212 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000213 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000214 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000215 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000216 void checkLocation(SVal l, bool isLoad, const Stmt *S,
217 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000218
219 ProgramStateRef checkPointerEscape(ProgramStateRef State,
220 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000221 const CallEvent *Call,
222 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000223 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
224 const InvalidatedSymbols &Escaped,
225 const CallEvent *Call,
226 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000227
Anna Zaks263b7e02012-05-02 00:05:20 +0000228 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000229 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000230
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000231private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000232 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
233 mutable std::unique_ptr<BugType> BT_DoubleDelete;
234 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
235 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
236 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000237 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000238 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
239 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000240 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
Anna Zaks30d46682016-03-08 01:21:51 +0000241 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
242 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
243 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
244 *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
Anna Zaksbbec97c2017-03-09 00:01:01 +0000245 *II_win_wcsdup, *II_g_malloc, *II_g_malloc0,
246 *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0,
Leslie Zhaie3986c52017-04-26 05:33:14 +0000247 *II_g_try_realloc, *II_g_free, *II_g_memdup,
248 *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n,
249 *II_g_try_malloc_n, *II_g_try_malloc0_n,
250 *II_g_try_realloc_n;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000251 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000252
Anna Zaks3d348342012-02-14 21:55:24 +0000253 void initIdentifierInfo(ASTContext &C) const;
254
Anton Yartsev05789592013-03-28 17:05:19 +0000255 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000256 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000257
258 /// \brief Print names of allocators and deallocators.
259 ///
260 /// \returns true on success.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000261 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000262 const Expr *E) const;
263
264 /// \brief Print expected name of an allocator based on the deallocator's
265 /// family derived from the DeallocExpr.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000266 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000267 const Expr *DeallocExpr) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000268 /// \brief Print expected name of a deallocator based on the allocator's
Anton Yartsev05789592013-03-28 17:05:19 +0000269 /// family.
270 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
271
Jordan Rose613f3c02013-03-09 00:59:10 +0000272 ///@{
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000273 /// Check if this is one of the functions which can allocate/reallocate memory
Anna Zaks3d348342012-02-14 21:55:24 +0000274 /// pointed to by one of its arguments.
275 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000276 bool isCMemFunction(const FunctionDecl *FD,
277 ASTContext &C,
278 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000279 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000280 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000281 ///@}
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000282
283 /// \brief Perform a zero-allocation check.
284 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
285 const unsigned AllocationSizeArg,
286 ProgramStateRef State) const;
287
Richard Smith852e9ce2013-11-27 01:46:48 +0000288 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
289 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000290 const OwnershipAttr* Att,
291 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000292 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000293 const Expr *SizeEx, SVal Init,
294 ProgramStateRef State,
295 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000296 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000297 SVal SizeEx, SVal Init,
298 ProgramStateRef State,
299 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000300
Gabor Horvath73040272016-09-19 20:39:52 +0000301 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
302 ProgramStateRef State);
303
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000304 // Check if this malloc() for special flags. At present that means M_ZERO or
305 // __GFP_ZERO (in which case, treat it like calloc).
306 llvm::Optional<ProgramStateRef>
307 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
308 const ProgramStateRef &State) const;
309
Anna Zaks40a7eb32012-02-22 19:24:52 +0000310 /// Update the RefState to reflect the new memory allocation.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000311 static ProgramStateRef
Anton Yartsev05789592013-03-28 17:05:19 +0000312 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
313 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000314
315 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000316 const OwnershipAttr* Att,
317 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000318 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000319 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000320 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000321 bool &ReleasedAllocated,
322 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000323 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
324 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000325 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000326 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000327 bool &ReleasedAllocated,
328 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000329
Leslie Zhaie3986c52017-04-26 05:33:14 +0000330 ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE,
331 bool FreesMemOnFailure,
332 ProgramStateRef State,
333 bool SuffixWithN = false) const;
334 static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
335 const Expr *BlockBytes);
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000336 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
337 ProgramStateRef State);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000338
Anna Zaks46d01602012-05-18 01:16:10 +0000339 ///\brief Check if the memory associated with this symbol was released.
340 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
341
Anton Yartsev13df0362013-03-25 01:35:45 +0000342 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000343
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000344 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000345 const Stmt *S) const;
346
Jordan Rose656fdd52014-01-08 18:46:55 +0000347 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
348
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000349 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000350 /// "interesting" and should be modeled explicitly.
351 ///
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000352 /// \param [out] EscapingSymbol A function might not free memory in general,
Anna Zaks8ebeb642013-06-08 00:29:29 +0000353 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000354 /// returned and the single escaping symbol is returned through the out
355 /// parameter.
356 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000357 /// We assume that pointers do not escape through calls to system functions
358 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000359 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000360 ProgramStateRef State,
361 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000362
Anna Zaks333481b2013-03-28 23:15:29 +0000363 // Implementation of the checkPointerEscape callabcks.
364 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
365 const InvalidatedSymbols &Escaped,
366 const CallEvent *Call,
367 PointerEscapeKind Kind,
368 bool(*CheckRefState)(const RefState*)) const;
369
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000370 ///@{
371 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000372 /// Sets CheckKind to the kind of the checker responsible for this
373 /// family/call/symbol.
Anton Yartsev2487dd62015-03-10 22:24:21 +0000374 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
375 bool IsALeakCheck = false) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000376 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000377 const Stmt *AllocDeallocStmt,
378 bool IsALeakCheck = false) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000379 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000380 bool IsALeakCheck = false) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000381 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000382 static bool SummarizeValue(raw_ostream &os, SVal V);
383 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000384 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +0000385 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000386 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
387 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000388 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000389 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000390 SymbolRef Sym, bool OwnershipTransferred) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000391 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
392 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000393 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000394 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
395 SymbolRef Sym) const;
396 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000397 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000398
Jordan Rose656fdd52014-01-08 18:46:55 +0000399 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
400
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000401 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
402 SymbolRef Sym) const;
403
Anna Zaksdf901a42012-02-23 21:38:21 +0000404 /// Find the location of the allocation for Sym on the path leading to the
405 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000406 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
407 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000408
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000409 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
410
Anna Zaks2b5bb972012-02-09 06:25:51 +0000411 /// The bug visitor which allows us to print extra diagnostics along the
412 /// BugReport path. For example, showing the allocation site of the leaked
413 /// region.
David Blaikie6951e3e2015-08-13 22:58:37 +0000414 class MallocBugVisitor final
415 : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000416 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000417 enum NotificationMode {
418 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000419 ReallocationFailed
420 };
421
Anna Zaks2b5bb972012-02-09 06:25:51 +0000422 // The allocated region symbol tracked by the main analysis.
423 SymbolRef Sym;
424
Anna Zaks62cce9e2012-05-10 01:37:40 +0000425 // The mode we are in, i.e. what kind of diagnostics will be emitted.
426 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000427
Anna Zaks62cce9e2012-05-10 01:37:40 +0000428 // A symbol from when the primary region should have been reallocated.
429 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000430
Anna Zaks62cce9e2012-05-10 01:37:40 +0000431 bool IsLeak;
432
433 public:
434 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000435 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000436
Craig Topperfb6b25b2014-03-15 04:29:04 +0000437 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000438 static int X = 0;
439 ID.AddPointer(&X);
440 ID.AddPointer(Sym);
441 }
442
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000443 inline bool isAllocated(const RefState *S, const RefState *SPrev,
444 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000445 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000446 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000447 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
448 (!SPrev || !(SPrev->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000449 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000450 }
451
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000452 inline bool isReleased(const RefState *S, const RefState *SPrev,
453 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000454 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000455 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000456 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
457 }
458
Anna Zaks0d6989b2012-06-22 02:04:31 +0000459 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
460 const Stmt *Stmt) {
461 // Did not track -> relinquished. Other state (allocated) -> relinquished.
462 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
463 isa<ObjCPropertyRefExpr>(Stmt)) &&
464 (S && S->isRelinquished()) &&
465 (!SPrev || !SPrev->isRelinquished()));
466 }
467
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000468 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
469 const Stmt *Stmt) {
470 // If the expression is not a call, and the state change is
471 // released -> allocated, it must be the realloc return value
472 // check. If we have to handle more cases here, it might be cleaner just
473 // to track this extra bit in the state itself.
474 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000475 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
476 (SPrev && !(SPrev->isAllocated() ||
477 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000478 }
479
David Blaikie0a0c2752017-01-05 17:26:53 +0000480 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
481 const ExplodedNode *PrevN,
482 BugReporterContext &BRC,
483 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000484
David Blaikied15481c2014-08-29 18:18:43 +0000485 std::unique_ptr<PathDiagnosticPiece>
486 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
487 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000488 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000489 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000490
491 PathDiagnosticLocation L =
492 PathDiagnosticLocation::createEndOfPath(EndPathNode,
493 BRC.getSourceManager());
494 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000495 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
496 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000497 }
498
Anna Zakscba4f292012-03-16 23:24:20 +0000499 private:
500 class StackHintGeneratorForReallocationFailed
501 : public StackHintGeneratorForSymbol {
502 public:
503 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
504 : StackHintGeneratorForSymbol(S, M) {}
505
Craig Topperfb6b25b2014-03-15 04:29:04 +0000506 std::string getMessageForArg(const Expr *ArgE,
507 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000508 // Printed parameters start at 1, not 0.
509 ++ArgIndex;
510
Anna Zakscba4f292012-03-16 23:24:20 +0000511 SmallString<200> buf;
512 llvm::raw_svector_ostream os(buf);
513
Jordan Rosec102b352012-09-22 01:24:42 +0000514 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
515 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000516
517 return os.str();
518 }
519
Craig Topperfb6b25b2014-03-15 04:29:04 +0000520 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000521 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000522 }
523 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000524 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000525};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000526} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000527
Jordan Rose0c153cb2012-11-02 01:54:06 +0000528REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
529REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Devin Coughlin81771732015-09-22 22:47:14 +0000530REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000531
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000532// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000533// the free function.
534REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
535
Anna Zaksbb1ef902012-02-11 21:02:35 +0000536namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000537class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000538 ProgramStateRef state;
539public:
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000540 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
Anna Zaksbb1ef902012-02-11 21:02:35 +0000541 ProgramStateRef getState() const { return state; }
542
Craig Topperfb6b25b2014-03-15 04:29:04 +0000543 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000544 state = state->remove<RegionState>(sym);
545 return true;
546 }
547};
548} // end anonymous namespace
549
Anna Zaks3d348342012-02-14 21:55:24 +0000550void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000551 if (II_malloc)
552 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000553 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000554 II_malloc = &Ctx.Idents.get("malloc");
555 II_free = &Ctx.Idents.get("free");
556 II_realloc = &Ctx.Idents.get("realloc");
557 II_reallocf = &Ctx.Idents.get("reallocf");
558 II_calloc = &Ctx.Idents.get("calloc");
559 II_valloc = &Ctx.Idents.get("valloc");
560 II_strdup = &Ctx.Idents.get("strdup");
561 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaks30d46682016-03-08 01:21:51 +0000562 II_wcsdup = &Ctx.Idents.get("wcsdup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000563 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000564 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
565 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaks30d46682016-03-08 01:21:51 +0000566
567 //MSVC uses `_`-prefixed instead, so we check for them too.
568 II_win_strdup = &Ctx.Idents.get("_strdup");
569 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
570 II_win_alloca = &Ctx.Idents.get("_alloca");
Anna Zaksbbec97c2017-03-09 00:01:01 +0000571
572 // Glib
573 II_g_malloc = &Ctx.Idents.get("g_malloc");
574 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
575 II_g_realloc = &Ctx.Idents.get("g_realloc");
576 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
577 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
578 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
579 II_g_free = &Ctx.Idents.get("g_free");
580 II_g_memdup = &Ctx.Idents.get("g_memdup");
Leslie Zhaie3986c52017-04-26 05:33:14 +0000581 II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
582 II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
583 II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
584 II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
585 II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
586 II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000587}
588
Anna Zaks3d348342012-02-14 21:55:24 +0000589bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000590 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000591 return true;
592
Anna Zaksd79b8402014-10-03 21:48:59 +0000593 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000594 return true;
595
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000596 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
597 return true;
598
Anton Yartsev13df0362013-03-25 01:35:45 +0000599 if (isStandardNewDelete(FD, C))
600 return true;
601
Anna Zaks46d01602012-05-18 01:16:10 +0000602 return false;
603}
604
Anna Zaksd79b8402014-10-03 21:48:59 +0000605bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
606 ASTContext &C,
607 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000608 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000609 if (!FD)
610 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000611
Anna Zaksd79b8402014-10-03 21:48:59 +0000612 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
613 MemKind == MemoryOperationKind::MOK_Free);
614 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
615 MemKind == MemoryOperationKind::MOK_Allocate);
616
Jordan Rose6cd16c52012-07-10 23:13:01 +0000617 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000618 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000619 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000620
Anna Zaksd79b8402014-10-03 21:48:59 +0000621 if (Family == AF_Malloc && CheckFree) {
Anna Zaksbbec97c2017-03-09 00:01:01 +0000622 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
623 FunI == II_g_free)
Anna Zaksd79b8402014-10-03 21:48:59 +0000624 return true;
625 }
626
627 if (Family == AF_Malloc && CheckAlloc) {
628 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
629 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
Anna Zaks30d46682016-03-08 01:21:51 +0000630 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
Anna Zaksbbec97c2017-03-09 00:01:01 +0000631 FunI == II_win_wcsdup || FunI == II_kmalloc ||
632 FunI == II_g_malloc || FunI == II_g_malloc0 ||
633 FunI == II_g_realloc || FunI == II_g_try_malloc ||
634 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
Leslie Zhaie3986c52017-04-26 05:33:14 +0000635 FunI == II_g_memdup || FunI == II_g_malloc_n ||
636 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
637 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
638 FunI == II_g_try_realloc_n)
Anna Zaksd79b8402014-10-03 21:48:59 +0000639 return true;
640 }
641
642 if (Family == AF_IfNameIndex && CheckFree) {
643 if (FunI == II_if_freenameindex)
644 return true;
645 }
646
647 if (Family == AF_IfNameIndex && CheckAlloc) {
648 if (FunI == II_if_nameindex)
649 return true;
650 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000651
652 if (Family == AF_Alloca && CheckAlloc) {
Anna Zaks30d46682016-03-08 01:21:51 +0000653 if (FunI == II_alloca || FunI == II_win_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000654 return true;
655 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000656 }
Anna Zaks3d348342012-02-14 21:55:24 +0000657
Anna Zaksd79b8402014-10-03 21:48:59 +0000658 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000659 return false;
660
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000661 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000662 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
663 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
664 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
665 if (CheckFree)
666 return true;
667 } else if (OwnKind == OwnershipAttr::Returns) {
668 if (CheckAlloc)
669 return true;
670 }
671 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000672 }
Anna Zaks3d348342012-02-14 21:55:24 +0000673
Anna Zaks3d348342012-02-14 21:55:24 +0000674 return false;
675}
676
Anton Yartsev8b662702013-03-28 16:10:38 +0000677// Tells if the callee is one of the following:
678// 1) A global non-placement new/delete operator function.
679// 2) A global placement operator function with the single placement argument
680// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000681bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
682 ASTContext &C) const {
683 if (!FD)
684 return false;
685
686 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000687 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000688 Kind != OO_Delete && Kind != OO_Array_Delete)
689 return false;
690
Anton Yartsev8b662702013-03-28 16:10:38 +0000691 // Skip all operator new/delete methods.
692 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000693 return false;
694
695 // Return true if tested operator is a standard placement nothrow operator.
696 if (FD->getNumParams() == 2) {
697 QualType T = FD->getParamDecl(1)->getType();
698 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
699 return II->getName().equals("nothrow_t");
700 }
701
702 // Skip placement operators.
703 if (FD->getNumParams() != 1 || FD->isVariadic())
704 return false;
705
706 // One of the standard new/new[]/delete/delete[] non-placement operators.
707 return true;
708}
709
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000710llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
711 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
712 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
713 //
714 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
715 //
716 // One of the possible flags is M_ZERO, which means 'give me back an
717 // allocation which is already zeroed', like calloc.
718
719 // 2-argument kmalloc(), as used in the Linux kernel:
720 //
721 // void *kmalloc(size_t size, gfp_t flags);
722 //
723 // Has the similar flag value __GFP_ZERO.
724
725 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
726 // code could be shared.
727
728 ASTContext &Ctx = C.getASTContext();
729 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
730
731 if (!KernelZeroFlagVal.hasValue()) {
732 if (OS == llvm::Triple::FreeBSD)
733 KernelZeroFlagVal = 0x0100;
734 else if (OS == llvm::Triple::NetBSD)
735 KernelZeroFlagVal = 0x0002;
736 else if (OS == llvm::Triple::OpenBSD)
737 KernelZeroFlagVal = 0x0008;
738 else if (OS == llvm::Triple::Linux)
739 // __GFP_ZERO
740 KernelZeroFlagVal = 0x8000;
741 else
742 // FIXME: We need a more general way of getting the M_ZERO value.
743 // See also: O_CREAT in UnixAPIChecker.cpp.
744
745 // Fall back to normal malloc behavior on platforms where we don't
746 // know M_ZERO.
747 return None;
748 }
749
750 // We treat the last argument as the flags argument, and callers fall-back to
751 // normal malloc on a None return. This works for the FreeBSD kernel malloc
752 // as well as Linux kmalloc.
753 if (CE->getNumArgs() < 2)
754 return None;
755
756 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
757 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
758 if (!V.getAs<NonLoc>()) {
759 // The case where 'V' can be a location can only be due to a bad header,
760 // so in this case bail out.
761 return None;
762 }
763
764 NonLoc Flags = V.castAs<NonLoc>();
765 NonLoc ZeroFlag = C.getSValBuilder()
766 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
767 .castAs<NonLoc>();
768 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
769 Flags, ZeroFlag,
770 FlagsEx->getType());
771 if (MaskedFlagsUC.isUnknownOrUndef())
772 return None;
773 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
774
775 // Check if maskedFlags is non-zero.
776 ProgramStateRef TrueState, FalseState;
777 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
778
779 // If M_ZERO is set, treat this like calloc (initialized).
780 if (TrueState && !FalseState) {
781 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
782 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
783 }
784
785 return None;
786}
787
Leslie Zhaie3986c52017-04-26 05:33:14 +0000788SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
789 const Expr *BlockBytes) {
790 SValBuilder &SB = C.getSValBuilder();
791 SVal BlocksVal = C.getSVal(Blocks);
792 SVal BlockBytesVal = C.getSVal(BlockBytes);
793 ProgramStateRef State = C.getState();
794 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
795 SB.getContext().getSizeType());
796 return TotalSize;
797}
798
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000799void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000800 if (C.wasInlined)
801 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000802
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000803 const FunctionDecl *FD = C.getCalleeDecl(CE);
804 if (!FD)
805 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000806
Anna Zaks40a7eb32012-02-22 19:24:52 +0000807 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000808 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000809
810 if (FD->getKind() == Decl::Function) {
811 initIdentifierInfo(C.getASTContext());
812 IdentifierInfo *FunI = FD->getIdentifier();
813
Anna Zaksbbec97c2017-03-09 00:01:01 +0000814 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000815 if (CE->getNumArgs() < 1)
816 return;
817 if (CE->getNumArgs() < 3) {
818 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000819 if (CE->getNumArgs() == 1)
820 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000821 } else if (CE->getNumArgs() == 3) {
822 llvm::Optional<ProgramStateRef> MaybeState =
823 performKernelMalloc(CE, C, State);
824 if (MaybeState.hasValue())
825 State = MaybeState.getValue();
826 else
827 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
828 }
829 } else if (FunI == II_kmalloc) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000830 if (CE->getNumArgs() < 1)
831 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000832 llvm::Optional<ProgramStateRef> MaybeState =
833 performKernelMalloc(CE, C, State);
834 if (MaybeState.hasValue())
835 State = MaybeState.getValue();
836 else
837 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
838 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000839 if (CE->getNumArgs() < 1)
840 return;
841 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000842 State = ProcessZeroAllocation(C, CE, 0, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000843 } else if (FunI == II_realloc || FunI == II_g_realloc ||
844 FunI == II_g_try_realloc) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000845 State = ReallocMemAux(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000846 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000847 } else if (FunI == II_reallocf) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000848 State = ReallocMemAux(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000849 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000850 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000851 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000852 State = ProcessZeroAllocation(C, CE, 0, State);
853 State = ProcessZeroAllocation(C, CE, 1, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000854 } else if (FunI == II_free || FunI == II_g_free) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000855 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaks30d46682016-03-08 01:21:51 +0000856 } else if (FunI == II_strdup || FunI == II_win_strdup ||
857 FunI == II_wcsdup || FunI == II_win_wcsdup) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000858 State = MallocUpdateRefState(C, CE, State);
859 } else if (FunI == II_strndup) {
860 State = MallocUpdateRefState(C, CE, State);
Anna Zaks30d46682016-03-08 01:21:51 +0000861 } else if (FunI == II_alloca || FunI == II_win_alloca) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000862 if (CE->getNumArgs() < 1)
863 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000864 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
865 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000866 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000867 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000868 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000869 // as distinct from new/new[]/delete/delete[] expressions that are
870 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000871 // CXXDeleteExpr.
872 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000873 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000874 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
875 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000876 State = ProcessZeroAllocation(C, CE, 0, State);
877 }
878 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000879 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
880 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000881 State = ProcessZeroAllocation(C, CE, 0, State);
882 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000883 else if (K == OO_Delete || K == OO_Array_Delete)
884 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
885 else
886 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000887 } else if (FunI == II_if_nameindex) {
888 // Should we model this differently? We can allocate a fixed number of
889 // elements with zeros in the last one.
890 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
891 AF_IfNameIndex);
892 } else if (FunI == II_if_freenameindex) {
893 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000894 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
895 if (CE->getNumArgs() < 1)
896 return;
897 SValBuilder &svalBuilder = C.getSValBuilder();
898 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
899 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
900 State = ProcessZeroAllocation(C, CE, 0, State);
901 } else if (FunI == II_g_memdup) {
902 if (CE->getNumArgs() < 2)
903 return;
904 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
905 State = ProcessZeroAllocation(C, CE, 1, State);
Leslie Zhaie3986c52017-04-26 05:33:14 +0000906 } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
907 FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
908 if (CE->getNumArgs() < 2)
909 return;
910 SVal Init = UndefinedVal();
911 if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
912 SValBuilder &SB = C.getSValBuilder();
913 Init = SB.makeZeroVal(SB.getContext().CharTy);
914 }
915 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
916 State = MallocMemAux(C, CE, TotalSize, Init, State);
917 State = ProcessZeroAllocation(C, CE, 0, State);
918 State = ProcessZeroAllocation(C, CE, 1, State);
919 } else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
920 if (CE->getNumArgs() < 3)
921 return;
922 State = ReallocMemAux(C, CE, false, State, true);
923 State = ProcessZeroAllocation(C, CE, 1, State);
924 State = ProcessZeroAllocation(C, CE, 2, State);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000925 }
926 }
927
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000928 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000929 // Check all the attributes, if there are any.
930 // There can be multiple of these attributes.
931 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000932 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
933 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000934 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000935 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000936 break;
937 case OwnershipAttr::Takes:
938 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000939 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000940 break;
941 }
942 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000943 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000944 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000945}
946
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000947// Performs a 0-sized allocations check.
948ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
949 const Expr *E,
950 const unsigned AllocationSizeArg,
951 ProgramStateRef State) const {
952 if (!State)
953 return nullptr;
954
955 const Expr *Arg = nullptr;
956
957 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
958 Arg = CE->getArg(AllocationSizeArg);
959 }
960 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
961 if (NE->isArray())
962 Arg = NE->getArraySize();
963 else
964 return State;
965 }
966 else
967 llvm_unreachable("not a CallExpr or CXXNewExpr");
968
969 assert(Arg);
970
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000971 Optional<DefinedSVal> DefArgVal =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000972 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
973
974 if (!DefArgVal)
975 return State;
976
977 // Check if the allocation size is 0.
978 ProgramStateRef TrueState, FalseState;
979 SValBuilder &SvalBuilder = C.getSValBuilder();
980 DefinedSVal Zero =
981 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
982
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000983 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000984 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
985
986 if (TrueState && !FalseState) {
987 SVal retVal = State->getSVal(E, C.getLocationContext());
988 SymbolRef Sym = retVal.getAsLocSymbol();
989 if (!Sym)
990 return State;
991
992 const RefState *RS = State->get<RegionState>(Sym);
Devin Coughlin81771732015-09-22 22:47:14 +0000993 if (RS) {
994 if (RS->isAllocated())
995 return TrueState->set<RegionState>(Sym,
996 RefState::getAllocatedOfSizeZero(RS));
997 else
998 return State;
999 } else {
1000 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1001 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1002 // tracked. Add zero-reallocated Sym to the state to catch references
1003 // to zero-allocated memory.
1004 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1005 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001006 }
1007
1008 // Assume the value is non-zero going forward.
1009 assert(FalseState);
1010 return FalseState;
1011}
1012
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001013static QualType getDeepPointeeType(QualType T) {
1014 QualType Result = T, PointeeType = T->getPointeeType();
1015 while (!PointeeType.isNull()) {
1016 Result = PointeeType;
1017 PointeeType = PointeeType->getPointeeType();
1018 }
1019 return Result;
1020}
1021
1022static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1023
1024 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1025 if (!ConstructE)
1026 return false;
1027
1028 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1029 return false;
1030
1031 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1032
1033 // Iterate over the constructor parameters.
David Majnemer59f77922016-06-24 04:05:48 +00001034 for (const auto *CtorParam : CtorD->parameters()) {
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001035
1036 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1037 if (CtorParamPointeeT.isNull())
1038 continue;
1039
1040 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1041
1042 if (CtorParamPointeeT->getAsCXXRecordDecl())
1043 return true;
1044 }
1045
1046 return false;
1047}
1048
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001049void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001050 CheckerContext &C) const {
1051
1052 if (NE->getNumPlacementArgs())
1053 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1054 E = NE->placement_arg_end(); I != E; ++I)
1055 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1056 checkUseAfterFree(Sym, C, *I);
1057
Anton Yartsev13df0362013-03-25 01:35:45 +00001058 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1059 return;
1060
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001061 ParentMap &PM = C.getLocationContext()->getParentMap();
1062 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1063 return;
1064
Anton Yartsev13df0362013-03-25 01:35:45 +00001065 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001066 // The return value from operator new is bound to a specified initialization
1067 // value (if any) and we don't want to loose this value. So we call
1068 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +00001069 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001070 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Anton Yartsev05789592013-03-28 17:05:19 +00001071 : AF_CXXNew);
Gabor Horvath73040272016-09-19 20:39:52 +00001072 State = addExtentSize(C, NE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001073 State = ProcessZeroAllocation(C, NE, 0, State);
Anton Yartsev13df0362013-03-25 01:35:45 +00001074 C.addTransition(State);
1075}
1076
Gabor Horvath73040272016-09-19 20:39:52 +00001077// Sets the extent value of the MemRegion allocated by
1078// new expression NE to its size in Bytes.
1079//
1080ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1081 const CXXNewExpr *NE,
1082 ProgramStateRef State) {
1083 if (!State)
1084 return nullptr;
1085 SValBuilder &svalBuilder = C.getSValBuilder();
1086 SVal ElementCount;
1087 const LocationContext *LCtx = C.getLocationContext();
1088 const SubRegion *Region;
1089 if (NE->isArray()) {
1090 const Expr *SizeExpr = NE->getArraySize();
1091 ElementCount = State->getSVal(SizeExpr, C.getLocationContext());
1092 // Store the extent size for the (symbolic)region
1093 // containing the elements.
1094 Region = (State->getSVal(NE, LCtx))
1095 .getAsRegion()
1096 ->getAs<SubRegion>()
1097 ->getSuperRegion()
1098 ->getAs<SubRegion>();
1099 } else {
1100 ElementCount = svalBuilder.makeIntVal(1, true);
1101 Region = (State->getSVal(NE, LCtx)).getAsRegion()->getAs<SubRegion>();
1102 }
1103 assert(Region);
1104
1105 // Set the region's extent equal to the Size in Bytes.
1106 QualType ElementType = NE->getAllocatedType();
1107 ASTContext &AstContext = C.getASTContext();
1108 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1109
Devin Coughline3b75de2016-12-16 18:41:40 +00001110 if (ElementCount.getAs<NonLoc>()) {
Gabor Horvath73040272016-09-19 20:39:52 +00001111 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1112 // size in Bytes = ElementCount*TypeSize
1113 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1114 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1115 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1116 svalBuilder.getArrayIndexType());
1117 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1118 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1119 State = State->assume(extentMatchesSize, true);
1120 }
1121 return State;
1122}
1123
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001124void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001125 CheckerContext &C) const {
1126
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001127 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +00001128 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1129 checkUseAfterFree(Sym, C, DE->getArgument());
1130
Anton Yartsev13df0362013-03-25 01:35:45 +00001131 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1132 return;
1133
1134 ProgramStateRef State = C.getState();
1135 bool ReleasedAllocated;
1136 State = FreeMemAux(C, DE->getArgument(), DE, State,
1137 /*Hold*/false, ReleasedAllocated);
1138
1139 C.addTransition(State);
1140}
1141
Jordan Rose613f3c02013-03-09 00:59:10 +00001142static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1143 // If the first selector piece is one of the names below, assume that the
1144 // object takes ownership of the memory, promising to eventually deallocate it
1145 // with free().
1146 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1147 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1148 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
Alexander Kornienko9c104902015-12-28 13:06:58 +00001149 return FirstSlot == "dataWithBytesNoCopy" ||
1150 FirstSlot == "initWithBytesNoCopy" ||
1151 FirstSlot == "initWithCharactersNoCopy";
Anna Zaks0d6989b2012-06-22 02:04:31 +00001152}
1153
Jordan Rose613f3c02013-03-09 00:59:10 +00001154static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1155 Selector S = Call.getSelector();
1156
1157 // FIXME: We should not rely on fully-constrained symbols being folded.
1158 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1159 if (S.getNameForSlot(i).equals("freeWhenDone"))
1160 return !Call.getArgSVal(i).isZeroConstant();
1161
1162 return None;
1163}
1164
Anna Zaks67291b92012-11-13 03:18:01 +00001165void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1166 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001167 if (C.wasInlined)
1168 return;
1169
Jordan Rose613f3c02013-03-09 00:59:10 +00001170 if (!isKnownDeallocObjCMethodName(Call))
1171 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001172
Jordan Rose613f3c02013-03-09 00:59:10 +00001173 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1174 if (!*FreeWhenDone)
1175 return;
1176
1177 bool ReleasedAllocatedMemory;
1178 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1179 Call.getOriginExpr(), C.getState(),
1180 /*Hold=*/true, ReleasedAllocatedMemory,
1181 /*RetNullOnFailure=*/true);
1182
1183 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001184}
1185
Richard Smith852e9ce2013-11-27 01:46:48 +00001186ProgramStateRef
1187MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001188 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001189 ProgramStateRef State) const {
1190 if (!State)
1191 return nullptr;
1192
Richard Smith852e9ce2013-11-27 01:46:48 +00001193 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001194 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001195
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001196 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001197 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001198 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001199 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001200 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1201}
1202
1203ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1204 const CallExpr *CE,
1205 const Expr *SizeEx, SVal Init,
1206 ProgramStateRef State,
1207 AllocationFamily Family) {
1208 if (!State)
1209 return nullptr;
1210
1211 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1212 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001213}
1214
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001215ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001216 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001217 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001218 ProgramStateRef State,
1219 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001220 if (!State)
1221 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001222
Jordan Rosef69e65f2014-09-05 16:33:51 +00001223 // We expect the malloc functions to return a pointer.
1224 if (!Loc::isLocType(CE->getType()))
1225 return nullptr;
1226
Anna Zaks3563fde2012-06-07 03:57:32 +00001227 // Bind the return value to the symbolic value from the heap region.
1228 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1229 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001230 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001231 SValBuilder &svalBuilder = C.getSValBuilder();
1232 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001233 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1234 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001235 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001236
Jordy Rose674bd552010-07-04 00:00:41 +00001237 // Fill the region with the initialization value.
Anna Zaksb5701952017-01-13 00:50:57 +00001238 State = State->bindDefault(RetVal, Init, LCtx);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001239
Jordy Rose674bd552010-07-04 00:00:41 +00001240 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001241 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001242 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001243 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001244 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001245 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001246 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001247 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001248 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001249 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001250 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001251
Anton Yartsev05789592013-03-28 17:05:19 +00001252 State = State->assume(extentMatchesSize, true);
1253 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001254 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001255
Anton Yartsev05789592013-03-28 17:05:19 +00001256 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001257}
1258
1259ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001260 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001261 ProgramStateRef State,
1262 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001263 if (!State)
1264 return nullptr;
1265
Anna Zaks40a7eb32012-02-22 19:24:52 +00001266 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001267 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001268
1269 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001270 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001271 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001272
Ted Kremenek90af9092010-12-02 07:49:45 +00001273 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001274 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001275
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001276 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001277 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001278}
1279
Anna Zaks40a7eb32012-02-22 19:24:52 +00001280ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1281 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001282 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001283 ProgramStateRef State) const {
1284 if (!State)
1285 return nullptr;
1286
Richard Smith852e9ce2013-11-27 01:46:48 +00001287 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001288 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001289
Anna Zaksfe6eb672012-08-24 02:28:20 +00001290 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001291
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001292 for (const auto &Arg : Att->args()) {
1293 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001294 Att->getOwnKind() == OwnershipAttr::Holds,
1295 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001296 if (StateI)
1297 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001298 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001299 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001300}
1301
Ted Kremenek49b1e382012-01-26 21:29:00 +00001302ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001303 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001304 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001305 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001306 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001307 bool &ReleasedAllocated,
1308 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001309 if (!State)
1310 return nullptr;
1311
Anna Zaksb508d292012-04-10 23:41:11 +00001312 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001313 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001314
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001315 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001316 ReleasedAllocated, ReturnsNullOnFailure);
1317}
1318
Anna Zaksa14c1d02012-11-13 19:47:40 +00001319/// Checks if the previous call to free on the given symbol failed - if free
1320/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001321static bool didPreviousFreeFail(ProgramStateRef State,
1322 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001323 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001324 if (Ret) {
1325 assert(*Ret && "We should not store the null return symbol");
1326 ConstraintManager &CMgr = State->getConstraintManager();
1327 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001328 RetStatusSymbol = *Ret;
1329 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001330 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001331 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001332}
1333
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001334AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001335 const Stmt *S) const {
1336 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001337 return AF_None;
1338
Anton Yartseve3377fb2013-04-04 23:46:29 +00001339 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001340 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001341
1342 if (!FD)
1343 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1344
Anton Yartsev05789592013-03-28 17:05:19 +00001345 ASTContext &Ctx = C.getASTContext();
1346
Anna Zaksd79b8402014-10-03 21:48:59 +00001347 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001348 return AF_Malloc;
1349
1350 if (isStandardNewDelete(FD, Ctx)) {
1351 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001352 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001353 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001354 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001355 return AF_CXXNewArray;
1356 }
1357
Anna Zaksd79b8402014-10-03 21:48:59 +00001358 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1359 return AF_IfNameIndex;
1360
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001361 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1362 return AF_Alloca;
1363
Anton Yartsev05789592013-03-28 17:05:19 +00001364 return AF_None;
1365 }
1366
Anton Yartseve3377fb2013-04-04 23:46:29 +00001367 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1368 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1369
1370 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001371 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1372
Anton Yartseve3377fb2013-04-04 23:46:29 +00001373 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001374 return AF_Malloc;
1375
1376 return AF_None;
1377}
1378
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001379bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001380 const Expr *E) const {
1381 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1382 // FIXME: This doesn't handle indirect calls.
1383 const FunctionDecl *FD = CE->getDirectCallee();
1384 if (!FD)
1385 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001386
Anton Yartsev05789592013-03-28 17:05:19 +00001387 os << *FD;
1388 if (!FD->isOverloadedOperator())
1389 os << "()";
1390 return true;
1391 }
1392
1393 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1394 if (Msg->isInstanceMessage())
1395 os << "-";
1396 else
1397 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001398 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001399 return true;
1400 }
1401
1402 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001403 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001404 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1405 << "'";
1406 return true;
1407 }
1408
1409 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001410 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001411 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1412 << "'";
1413 return true;
1414 }
1415
1416 return false;
1417}
1418
1419void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1420 const Expr *E) const {
1421 AllocationFamily Family = getAllocationFamily(C, E);
1422
1423 switch(Family) {
1424 case AF_Malloc: os << "malloc()"; return;
1425 case AF_CXXNew: os << "'new'"; return;
1426 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001427 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001428 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001429 case AF_None: llvm_unreachable("not a deallocation expression");
1430 }
1431}
1432
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001433void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001434 AllocationFamily Family) const {
1435 switch(Family) {
1436 case AF_Malloc: os << "free()"; return;
1437 case AF_CXXNew: os << "'delete'"; return;
1438 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001439 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001440 case AF_Alloca:
1441 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001442 }
1443}
1444
Anna Zaks0d6989b2012-06-22 02:04:31 +00001445ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1446 const Expr *ArgExpr,
1447 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001448 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001449 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001450 bool &ReleasedAllocated,
1451 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001452
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001453 if (!State)
1454 return nullptr;
1455
Anna Zaks67291b92012-11-13 03:18:01 +00001456 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001457 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001458 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001459 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001460
1461 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001462 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001463 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001464
Anna Zaksad01ef52012-02-14 00:26:13 +00001465 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001466 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001467 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001468 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001469 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001470
Jordy Rose3597b212010-06-07 19:32:37 +00001471 // Unknown values could easily be okay
1472 // Undefined values are handled elsewhere
1473 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001474 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001475
Jordy Rose3597b212010-06-07 19:32:37 +00001476 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001477
Jordy Rose3597b212010-06-07 19:32:37 +00001478 // Nonlocs can't be freed, of course.
1479 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1480 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001481 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001482 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001483 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001484
Jordy Rose3597b212010-06-07 19:32:37 +00001485 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001486
Jordy Rose3597b212010-06-07 19:32:37 +00001487 // Blocks might show up as heap data, but should not be free()d
1488 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001489 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001490 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001491 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001492
Jordy Rose3597b212010-06-07 19:32:37 +00001493 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001494
1495 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001496 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001497 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1498 // FIXME: at the time this code was written, malloc() regions were
1499 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1500 // This means that there isn't actually anything from HeapSpaceRegion
1501 // that should be freed, even though we allow it here.
1502 // Of course, free() can work on memory allocated outside the current
1503 // function, so UnknownSpaceRegion is always a possibility.
1504 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001505
1506 if (isa<AllocaRegion>(R))
1507 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1508 else
1509 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1510
Craig Topper0dbb7832014-05-27 02:45:47 +00001511 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001512 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001513
1514 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001515 // Various cases could lead to non-symbol values here.
1516 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001517 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001518 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001519
Anna Zaksc89ad072013-02-07 23:05:47 +00001520 SymbolRef SymBase = SrBase->getSymbol();
1521 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001522 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001523
Anton Yartseve3377fb2013-04-04 23:46:29 +00001524 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001525
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001526 // Memory returned by alloca() shouldn't be freed.
1527 if (RsBase->getAllocationFamily() == AF_Alloca) {
1528 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1529 return nullptr;
1530 }
1531
Anna Zaks93a21a82013-04-09 00:30:28 +00001532 // Check for double free first.
1533 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001534 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1535 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1536 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001537 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001538
Anna Zaks93a21a82013-04-09 00:30:28 +00001539 // If the pointer is allocated or escaped, but we are now trying to free it,
1540 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001541 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001542 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001543
1544 // Check if an expected deallocation function matches the real one.
1545 bool DeallocMatchesAlloc =
1546 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1547 if (!DeallocMatchesAlloc) {
1548 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001549 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001550 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001551 }
1552
1553 // Check if the memory location being freed is the actual location
1554 // allocated, or an offset.
1555 RegionOffset Offset = R->getAsOffset();
1556 if (Offset.isValid() &&
1557 !Offset.hasSymbolicOffset() &&
1558 Offset.getOffset() != 0) {
1559 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001560 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001561 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001562 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001563 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001564 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001565 }
1566
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001567 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001568 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001569
Anna Zaksa14c1d02012-11-13 19:47:40 +00001570 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001571 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001572
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001573 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001574 // failed.
1575 if (ReturnsNullOnFailure) {
1576 SVal RetVal = C.getSVal(ParentExpr);
1577 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1578 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001579 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1580 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001581 }
1582 }
1583
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001584 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1585 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001586 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001587 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001588 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001589 RefState::getRelinquished(Family,
1590 ParentExpr));
1591
1592 return State->set<RegionState>(SymBase,
1593 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001594}
1595
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001596Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001597MallocChecker::getCheckIfTracked(AllocationFamily Family,
1598 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001599 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001600 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001601 case AF_Alloca:
1602 case AF_IfNameIndex: {
1603 if (ChecksEnabled[CK_MallocChecker])
1604 return CK_MallocChecker;
1605
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001606 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001607 }
1608 case AF_CXXNew:
1609 case AF_CXXNewArray: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001610 if (IsALeakCheck) {
1611 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1612 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001613 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001614 else {
1615 if (ChecksEnabled[CK_NewDeleteChecker])
1616 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001617 }
1618 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001619 }
1620 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001621 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001622 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001623 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001624 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001625}
1626
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001627Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001628MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001629 const Stmt *AllocDeallocStmt,
1630 bool IsALeakCheck) const {
1631 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1632 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001633}
1634
1635Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001636MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1637 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001638 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1639 return CK_MallocChecker;
1640
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001641 const RefState *RS = C.getState()->get<RegionState>(Sym);
1642 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001643 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001644}
1645
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001646bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001647 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001648 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001649 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001650 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001651 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001652 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001653 else
1654 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001655
Jordy Rose3597b212010-06-07 19:32:37 +00001656 return true;
1657}
1658
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001659bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001660 const MemRegion *MR) {
1661 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +00001662 case MemRegion::FunctionCodeRegionKind: {
1663 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001664 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001665 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001666 else
1667 os << "the address of a function";
1668 return true;
1669 }
Artem Dergachev73f018e2016-01-13 13:49:29 +00001670 case MemRegion::BlockCodeRegionKind:
Jordy Rose3597b212010-06-07 19:32:37 +00001671 os << "block text";
1672 return true;
1673 case MemRegion::BlockDataRegionKind:
1674 // FIXME: where the block came from?
1675 os << "a block";
1676 return true;
1677 default: {
1678 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001679
Anna Zaks8158ef02012-01-04 23:54:01 +00001680 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001681 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1682 const VarDecl *VD;
1683 if (VR)
1684 VD = VR->getDecl();
1685 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001686 VD = nullptr;
1687
Jordy Rose3597b212010-06-07 19:32:37 +00001688 if (VD)
1689 os << "the address of the local variable '" << VD->getName() << "'";
1690 else
1691 os << "the address of a local stack variable";
1692 return true;
1693 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001694
1695 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001696 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1697 const VarDecl *VD;
1698 if (VR)
1699 VD = VR->getDecl();
1700 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001701 VD = nullptr;
1702
Jordy Rose3597b212010-06-07 19:32:37 +00001703 if (VD)
1704 os << "the address of the parameter '" << VD->getName() << "'";
1705 else
1706 os << "the address of a parameter";
1707 return true;
1708 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001709
1710 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001711 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1712 const VarDecl *VD;
1713 if (VR)
1714 VD = VR->getDecl();
1715 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001716 VD = nullptr;
1717
Jordy Rose3597b212010-06-07 19:32:37 +00001718 if (VD) {
1719 if (VD->isStaticLocal())
1720 os << "the address of the static variable '" << VD->getName() << "'";
1721 else
1722 os << "the address of the global variable '" << VD->getName() << "'";
1723 } else
1724 os << "the address of a global variable";
1725 return true;
1726 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001727
1728 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001729 }
1730 }
1731}
1732
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001733void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1734 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001735 const Expr *DeallocExpr) const {
1736
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001737 if (!ChecksEnabled[CK_MallocChecker] &&
1738 !ChecksEnabled[CK_NewDeleteChecker])
1739 return;
1740
1741 Optional<MallocChecker::CheckKind> CheckKind =
1742 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001743 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001744 return;
1745
Devin Coughline39bd402015-09-16 22:03:05 +00001746 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001747 if (!BT_BadFree[*CheckKind])
1748 BT_BadFree[*CheckKind].reset(
1749 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1750
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001751 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001752 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001753
Jordy Rose3597b212010-06-07 19:32:37 +00001754 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001755 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1756 MR = ER->getSuperRegion();
1757
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001758 os << "Argument to ";
1759 if (!printAllocDeallocName(os, C, DeallocExpr))
1760 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001761
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001762 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001763 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001764 : SummarizeValue(os, ArgVal);
1765 if (Summarized)
1766 os << ", which is not memory allocated by ";
1767 else
1768 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001769
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001770 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001771
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001772 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001773 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001774 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001775 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001776 }
1777}
1778
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001779void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001780 SourceRange Range) const {
1781
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001782 Optional<MallocChecker::CheckKind> CheckKind;
1783
1784 if (ChecksEnabled[CK_MallocChecker])
1785 CheckKind = CK_MallocChecker;
1786 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1787 CheckKind = CK_MismatchedDeallocatorChecker;
1788 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001789 return;
1790
Devin Coughline39bd402015-09-16 22:03:05 +00001791 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001792 if (!BT_FreeAlloca[*CheckKind])
1793 BT_FreeAlloca[*CheckKind].reset(
1794 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1795
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001796 auto R = llvm::make_unique<BugReport>(
1797 *BT_FreeAlloca[*CheckKind],
1798 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001799 R->markInteresting(ArgVal.getAsRegion());
1800 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001801 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001802 }
1803}
1804
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001805void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001806 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001807 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001808 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001809 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001810 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001811
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001812 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001813 return;
1814
Devin Coughline39bd402015-09-16 22:03:05 +00001815 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001816 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001817 BT_MismatchedDealloc.reset(
1818 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1819 "Bad deallocator", "Memory Error"));
1820
Anton Yartsev05789592013-03-28 17:05:19 +00001821 SmallString<100> buf;
1822 llvm::raw_svector_ostream os(buf);
1823
1824 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1825 SmallString<20> AllocBuf;
1826 llvm::raw_svector_ostream AllocOs(AllocBuf);
1827 SmallString<20> DeallocBuf;
1828 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1829
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001830 if (OwnershipTransferred) {
1831 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1832 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001833 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001834 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001835
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001836 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001837
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001838 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1839 os << " allocated by " << AllocOs.str();
1840 } else {
1841 os << "Memory";
1842 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1843 os << " allocated by " << AllocOs.str();
1844
1845 os << " should be deallocated by ";
1846 printExpectedDeallocName(os, RS->getAllocationFamily());
1847
1848 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1849 os << ", not " << DeallocOs.str();
1850 }
Anton Yartsev05789592013-03-28 17:05:19 +00001851
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001852 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001853 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001854 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001855 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001856 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001857 }
1858}
1859
Anna Zaksc89ad072013-02-07 23:05:47 +00001860void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001861 SourceRange Range, const Expr *DeallocExpr,
1862 const Expr *AllocExpr) const {
1863
Anton Yartsev05789592013-03-28 17:05:19 +00001864
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001865 if (!ChecksEnabled[CK_MallocChecker] &&
1866 !ChecksEnabled[CK_NewDeleteChecker])
1867 return;
1868
1869 Optional<MallocChecker::CheckKind> CheckKind =
1870 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001871 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001872 return;
1873
Devin Coughline39bd402015-09-16 22:03:05 +00001874 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001875 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001876 return;
1877
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001878 if (!BT_OffsetFree[*CheckKind])
1879 BT_OffsetFree[*CheckKind].reset(
1880 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001881
1882 SmallString<100> buf;
1883 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001884 SmallString<20> AllocNameBuf;
1885 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001886
1887 const MemRegion *MR = ArgVal.getAsRegion();
1888 assert(MR && "Only MemRegion based symbols can have offset free errors");
1889
1890 RegionOffset Offset = MR->getAsOffset();
1891 assert((Offset.isValid() &&
1892 !Offset.hasSymbolicOffset() &&
1893 Offset.getOffset() != 0) &&
1894 "Only symbols with a valid offset can have offset free errors");
1895
1896 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1897
Anton Yartsev05789592013-03-28 17:05:19 +00001898 os << "Argument to ";
1899 if (!printAllocDeallocName(os, C, DeallocExpr))
1900 os << "deallocator";
1901 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001902 << offsetBytes
1903 << " "
1904 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001905 << " from the start of ";
1906 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1907 os << "memory allocated by " << AllocNameOs.str();
1908 else
1909 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001910
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001911 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001912 R->markInteresting(MR->getBaseRegion());
1913 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001914 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001915}
1916
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001917void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1918 SymbolRef Sym) const {
1919
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001920 if (!ChecksEnabled[CK_MallocChecker] &&
1921 !ChecksEnabled[CK_NewDeleteChecker])
1922 return;
1923
1924 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001925 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001926 return;
1927
Devin Coughline39bd402015-09-16 22:03:05 +00001928 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001929 if (!BT_UseFree[*CheckKind])
1930 BT_UseFree[*CheckKind].reset(new BugType(
1931 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001932
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001933 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1934 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001935
1936 R->markInteresting(Sym);
1937 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001938 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001939 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001940 }
1941}
1942
1943void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001944 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001945 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001946
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001947 if (!ChecksEnabled[CK_MallocChecker] &&
1948 !ChecksEnabled[CK_NewDeleteChecker])
1949 return;
1950
1951 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001952 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001953 return;
1954
Devin Coughline39bd402015-09-16 22:03:05 +00001955 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001956 if (!BT_DoubleFree[*CheckKind])
1957 BT_DoubleFree[*CheckKind].reset(
1958 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001959
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001960 auto R = llvm::make_unique<BugReport>(
1961 *BT_DoubleFree[*CheckKind],
1962 (Released ? "Attempt to free released memory"
1963 : "Attempt to free non-owned memory"),
1964 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001965 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001966 R->markInteresting(Sym);
1967 if (PrevSym)
1968 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001969 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001970 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001971 }
1972}
1973
Jordan Rose656fdd52014-01-08 18:46:55 +00001974void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1975
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001976 if (!ChecksEnabled[CK_NewDeleteChecker])
1977 return;
1978
1979 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001980 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001981 return;
1982
Devin Coughline39bd402015-09-16 22:03:05 +00001983 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00001984 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001985 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1986 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001987
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001988 auto R = llvm::make_unique<BugReport>(
1989 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00001990
1991 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001992 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001993 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00001994 }
1995}
1996
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001997void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1998 SourceRange Range,
1999 SymbolRef Sym) const {
2000
2001 if (!ChecksEnabled[CK_MallocChecker] &&
2002 !ChecksEnabled[CK_NewDeleteChecker])
2003 return;
2004
2005 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2006
2007 if (!CheckKind.hasValue())
2008 return;
2009
Devin Coughline39bd402015-09-16 22:03:05 +00002010 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002011 if (!BT_UseZerroAllocated[*CheckKind])
2012 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
2013 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
2014
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002015 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2016 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002017
2018 R->addRange(Range);
2019 if (Sym) {
2020 R->markInteresting(Sym);
2021 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2022 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002023 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002024 }
2025}
2026
Leslie Zhaie3986c52017-04-26 05:33:14 +00002027ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2028 const CallExpr *CE,
2029 bool FreesOnFail,
2030 ProgramStateRef State,
2031 bool SuffixWithN) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002032 if (!State)
2033 return nullptr;
2034
Leslie Zhaie3986c52017-04-26 05:33:14 +00002035 if (SuffixWithN && CE->getNumArgs() < 3)
2036 return nullptr;
2037 else if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002038 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002039
Ted Kremenek90af9092010-12-02 07:49:45 +00002040 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00002041 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002042 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00002043 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002044 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00002045 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002046
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002047 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002048
Ted Kremenek90af9092010-12-02 07:49:45 +00002049 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002050 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002051
Leslie Zhaie3986c52017-04-26 05:33:14 +00002052 // Get the size argument.
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002053 const Expr *Arg1 = CE->getArg(1);
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002054
2055 // Get the value of the size argument.
Leslie Zhaie3986c52017-04-26 05:33:14 +00002056 SVal TotalSize = State->getSVal(Arg1, LCtx);
2057 if (SuffixWithN)
2058 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2059 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002060 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002061
2062 // Compare the size argument to 0.
2063 DefinedOrUnknownSVal SizeZero =
Leslie Zhaie3986c52017-04-26 05:33:14 +00002064 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002065 svalBuilder.makeIntValWithPtrWidth(0, false));
2066
Anna Zaksd56c8792012-02-13 18:05:39 +00002067 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002068 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00002069 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002070 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00002071 // We only assume exceptional states if they are definitely true; if the
2072 // state is under-constrained, assume regular realloc behavior.
2073 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2074 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2075
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002076 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002077 // malloc(size).
Leslie Zhaie3986c52017-04-26 05:33:14 +00002078 if (PrtIsNull && !SizeIsZero) {
2079 ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002080 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002081 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002082 }
2083
Anna Zaksd56c8792012-02-13 18:05:39 +00002084 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00002085 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002086
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002087 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00002088 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002089 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002090 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002091 SymbolRef ToPtr = RetVal.getAsSymbol();
2092 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00002093 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00002094
Anna Zaksfe6eb672012-08-24 02:28:20 +00002095 bool ReleasedAllocated = false;
2096
Anna Zaksd56c8792012-02-13 18:05:39 +00002097 // If the size is 0, free the memory.
2098 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00002099 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2100 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00002101 // The semantics of the return value are:
2102 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00002103 // to free() is returned. We just free the input pointer and do not add
2104 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00002105 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00002106 }
2107
2108 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00002109 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002110 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00002111
Leslie Zhaie3986c52017-04-26 05:33:14 +00002112 ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002113 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002114 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00002115 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00002116
Anna Zaks75cfbb62012-09-12 22:57:34 +00002117 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2118 if (FreesOnFail)
2119 Kind = RPIsFreeOnFailure;
2120 else if (!ReleasedAllocated)
2121 Kind = RPDoNotTrackAfterFailure;
2122
Anna Zaksfe6eb672012-08-24 02:28:20 +00002123 // Record the info about the reallocated symbol so that we could properly
2124 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00002125 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00002126 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00002127 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00002128 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002129 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002130 }
Craig Topper0dbb7832014-05-27 02:45:47 +00002131 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00002132}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002133
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002134ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002135 ProgramStateRef State) {
2136 if (!State)
2137 return nullptr;
2138
Anna Zaksb508d292012-04-10 23:41:11 +00002139 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002140 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002141
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002142 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek90af9092010-12-02 07:49:45 +00002143 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002144 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002145
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002146 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002147}
2148
Anna Zaksfc2e1532012-03-21 19:45:08 +00002149LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002150MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2151 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002152 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002153 // Walk the ExplodedGraph backwards and find the first node that referred to
2154 // the tracked symbol.
2155 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002156 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002157
2158 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002159 ProgramStateRef State = N->getState();
2160 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002161 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002162
2163 // Find the most recent expression bound to the symbol in the current
2164 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002165 if (!ReferenceRegion) {
2166 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2167 SVal Val = State->getSVal(MR);
2168 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002169 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002170 // Do not show local variables belonging to a function other than
2171 // where the error is reported.
2172 if (!VR ||
2173 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2174 ReferenceRegion = MR;
2175 }
2176 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002177 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002178
Anna Zaks486a0ff2015-02-05 01:02:53 +00002179 // Allocation node, is the last node in the current or parent context in
2180 // which the symbol was tracked.
2181 const LocationContext *NContext = N->getLocationContext();
2182 if (NContext == LeakContext ||
2183 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002184 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002185 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002186 }
2187
Anna Zaksa043d0c2013-01-08 00:25:29 +00002188 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002189}
2190
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002191void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2192 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002193
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002194 if (!ChecksEnabled[CK_MallocChecker] &&
2195 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002196 return;
2197
Anton Yartsev9907fc92015-03-04 23:18:21 +00002198 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002199 assert(RS && "cannot leak an untracked symbol");
2200 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002201
2202 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002203 return;
2204
Anton Yartsev2487dd62015-03-10 22:24:21 +00002205 Optional<MallocChecker::CheckKind>
2206 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002207
Anton Yartsev2487dd62015-03-10 22:24:21 +00002208 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002209 return;
2210
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002211 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002212 if (!BT_Leak[*CheckKind]) {
2213 BT_Leak[*CheckKind].reset(
2214 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002215 // Leaks should not be reported if they are post-dominated by a sink:
2216 // (1) Sinks are higher importance bugs.
2217 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2218 // with __noreturn functions such as assert() or exit(). We choose not
2219 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002220 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002221 }
2222
Anna Zaksdf901a42012-02-23 21:38:21 +00002223 // Most bug reports are cached at the location where they occurred.
2224 // With leaks, we want to unique them by the location where they were
2225 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002226 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002227 const ExplodedNode *AllocNode = nullptr;
2228 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002229 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002230
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002231 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
Anton Yartsev6e499252013-04-05 02:25:02 +00002232 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002233 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2234 C.getSourceManager(),
2235 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002236
Anna Zaksfc2e1532012-03-21 19:45:08 +00002237 SmallString<200> buf;
2238 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002239 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002240 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002241 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002242 } else {
2243 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002244 }
2245
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002246 auto R = llvm::make_unique<BugReport>(
2247 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2248 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002249 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002250 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002251 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002252}
2253
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002254void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2255 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002256{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002257 if (!SymReaper.hasDeadSymbols())
2258 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002259
Ted Kremenek49b1e382012-01-26 21:29:00 +00002260 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002261 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002262 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002263
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002264 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002265 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2266 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002267 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002268 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002269 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002270 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002271
Zhongxing Xuc7460962009-11-13 07:48:11 +00002272 }
2273 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002274
Anna Zaksd56c8792012-02-13 18:05:39 +00002275 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002276 ReallocPairsTy RP = state->get<ReallocPairs>();
2277 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002278 if (SymReaper.isDead(I->first) ||
2279 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002280 state = state->remove<ReallocPairs>(I->first);
2281 }
2282 }
2283
Anna Zaks67291b92012-11-13 03:18:01 +00002284 // Cleanup the FreeReturnValue Map.
2285 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2286 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2287 if (SymReaper.isDead(I->first) ||
2288 SymReaper.isDead(I->second)) {
2289 state = state->remove<FreeReturnValue>(I->first);
2290 }
2291 }
2292
Anna Zaksdf901a42012-02-23 21:38:21 +00002293 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002294 ExplodedNode *N = C.getPredecessor();
2295 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002296 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002297 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2298 if (N) {
2299 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002300 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002301 reportLeak(*I, N, C);
2302 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002303 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002304 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002305
Anna Zaksdf901a42012-02-23 21:38:21 +00002306 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002307}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002308
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002309void MallocChecker::checkPreCall(const CallEvent &Call,
2310 CheckerContext &C) const {
2311
Jordan Rose656fdd52014-01-08 18:46:55 +00002312 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2313 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2314 if (!Sym || checkDoubleDelete(Sym, C))
2315 return;
2316 }
2317
Anna Zaks46d01602012-05-18 01:16:10 +00002318 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002319 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2320 const FunctionDecl *FD = FC->getDecl();
2321 if (!FD)
2322 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002323
Anna Zaksd79b8402014-10-03 21:48:59 +00002324 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002325 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002326 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2327 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2328 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002329 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002330
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002331 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002332 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002333 return;
2334 }
2335
2336 // Check if the callee of a method is deleted.
2337 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2338 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2339 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2340 return;
2341 }
2342
2343 // Check arguments for being used after free.
2344 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2345 SVal ArgSVal = Call.getArgSVal(I);
2346 if (ArgSVal.getAs<Loc>()) {
2347 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002348 if (!Sym)
2349 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002350 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002351 return;
2352 }
2353 }
2354}
2355
Anna Zaksa1b227b2012-02-08 23:16:56 +00002356void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2357 const Expr *E = S->getRetValue();
2358 if (!E)
2359 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002360
2361 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002362 ProgramStateRef State = C.getState();
2363 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002364 SymbolRef Sym = RetVal.getAsSymbol();
2365 if (!Sym)
2366 // If we are returning a field of the allocated struct or an array element,
2367 // the callee could still free the memory.
2368 // TODO: This logic should be a part of generic symbol escape callback.
2369 if (const MemRegion *MR = RetVal.getAsRegion())
2370 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2371 if (const SymbolicRegion *BMR =
2372 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2373 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002374
Anna Zaks3aa52252012-02-11 21:44:39 +00002375 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002376 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002377 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002378}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002379
Anna Zaks9fe80982012-03-22 00:57:20 +00002380// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002381// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002382// needed.
2383void MallocChecker::checkPostStmt(const BlockExpr *BE,
2384 CheckerContext &C) const {
2385
2386 // Scan the BlockDecRefExprs for any object the retain count checker
2387 // may be tracking.
2388 if (!BE->getBlockDecl()->hasCaptures())
2389 return;
2390
2391 ProgramStateRef state = C.getState();
2392 const BlockDataRegion *R =
2393 cast<BlockDataRegion>(state->getSVal(BE,
2394 C.getLocationContext()).getAsRegion());
2395
2396 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2397 E = R->referenced_vars_end();
2398
2399 if (I == E)
2400 return;
2401
2402 SmallVector<const MemRegion*, 10> Regions;
2403 const LocationContext *LC = C.getLocationContext();
2404 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2405
2406 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002407 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002408 if (VR->getSuperRegion() == R) {
2409 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2410 }
2411 Regions.push_back(VR);
2412 }
2413
2414 state =
2415 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2416 Regions.data() + Regions.size()).getState();
2417 C.addTransition(state);
2418}
2419
Anna Zaks46d01602012-05-18 01:16:10 +00002420bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002421 assert(Sym);
2422 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002423 return (RS && RS->isReleased());
2424}
2425
2426bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2427 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002428
Jordan Rose656fdd52014-01-08 18:46:55 +00002429 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002430 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2431 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002432 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002433
Anna Zaksa1b227b2012-02-08 23:16:56 +00002434 return false;
2435}
2436
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002437void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2438 const Stmt *S) const {
2439 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002440
Devin Coughlin81771732015-09-22 22:47:14 +00002441 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2442 if (RS->isAllocatedOfSizeZero())
2443 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2444 }
2445 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2446 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2447 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002448}
2449
Jordan Rose656fdd52014-01-08 18:46:55 +00002450bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2451
2452 if (isReleased(Sym, C)) {
2453 ReportDoubleDelete(C, Sym);
2454 return true;
2455 }
2456 return false;
2457}
2458
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002459// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002460void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2461 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002462 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002463 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002464 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002465 checkUseZeroAllocated(Sym, C, S);
2466 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002467}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002468
Anna Zaksbb1ef902012-02-11 21:02:35 +00002469// If a symbolic region is assumed to NULL (or another constant), stop tracking
2470// it - assuming that allocation failed on this path.
2471ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2472 SVal Cond,
2473 bool Assumption) const {
2474 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002475 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002476 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002477 ConstraintManager &CMgr = state->getConstraintManager();
2478 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2479 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002480 state = state->remove<RegionState>(I.getKey());
2481 }
2482
Anna Zaksd56c8792012-02-13 18:05:39 +00002483 // Realloc returns 0 when reallocation fails, which means that we should
2484 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002485 ReallocPairsTy RP = state->get<ReallocPairs>();
2486 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002487 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002488 ConstraintManager &CMgr = state->getConstraintManager();
2489 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002490 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002491 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002492
Anna Zaks75cfbb62012-09-12 22:57:34 +00002493 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2494 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2495 if (RS->isReleased()) {
2496 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002497 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002498 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002499 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2500 state = state->remove<RegionState>(ReallocSym);
2501 else
2502 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002503 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002504 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002505 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002506 }
2507
Anna Zaksbb1ef902012-02-11 21:02:35 +00002508 return state;
2509}
2510
Anna Zaks8ebeb642013-06-08 00:29:29 +00002511bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002512 const CallEvent *Call,
2513 ProgramStateRef State,
2514 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002515 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002516 EscapingSymbol = nullptr;
2517
Jordan Rose2a833ca2014-01-15 17:25:15 +00002518 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002519 // TODO: If we want to be more optimistic here, we'll need to make sure that
2520 // regions escape to C++ containers. They seem to do that even now, but for
2521 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002522 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002523 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002524
Jordan Rose742920c2012-07-02 19:27:35 +00002525 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002526 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002527 // If it's not a framework call, or if it takes a callback, assume it
2528 // can free memory.
Anna Zaksfe1eca52015-10-27 20:19:45 +00002529 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002530 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002531
Jordan Rose613f3c02013-03-09 00:59:10 +00002532 // If it's a method we know about, handle it explicitly post-call.
2533 // This should happen before the "freeWhenDone" check below.
2534 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002535 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002536
Jordan Rose613f3c02013-03-09 00:59:10 +00002537 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2538 // about, we can't be sure that the object will use free() to deallocate the
2539 // memory, so we can't model it explicitly. The best we can do is use it to
2540 // decide whether the pointer escapes.
2541 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002542 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002543
Jordan Rose613f3c02013-03-09 00:59:10 +00002544 // If the first selector piece ends with "NoCopy", and there is no
2545 // "freeWhenDone" parameter set to zero, we know ownership is being
2546 // transferred. Again, though, we can't be sure that the object will use
2547 // free() to deallocate the memory, so we can't model it explicitly.
2548 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002549 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002550 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002551
Anna Zaks42908c72012-06-19 05:10:32 +00002552 // If the first selector starts with addPointer, insertPointer,
2553 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2554 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002555 // that the pointers get freed by following the container itself.
2556 if (FirstSlot.startswith("addPointer") ||
2557 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002558 FirstSlot.startswith("replacePointer") ||
2559 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002560 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002561 }
2562
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002563 // We should escape receiver on call to 'init'. This is especially relevant
2564 // to the receiver, as the corresponding symbol is usually not referenced
2565 // after the call.
2566 if (Msg->getMethodFamily() == OMF_init) {
2567 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2568 return true;
2569 }
Anna Zaks737926b2013-05-31 22:39:13 +00002570
Jordan Rose742920c2012-07-02 19:27:35 +00002571 // Otherwise, assume that the method does not free memory.
2572 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002573 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002574 }
2575
Jordan Rose742920c2012-07-02 19:27:35 +00002576 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002577 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002578 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002579 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002580
Jordan Rose742920c2012-07-02 19:27:35 +00002581 ASTContext &ASTC = State->getStateManager().getContext();
2582
2583 // If it's one of the allocation functions we can reason about, we model
2584 // its behavior explicitly.
2585 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002586 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002587
2588 // If it's not a system call, assume it frees memory.
2589 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002590 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002591
2592 // White list the system functions whose arguments escape.
2593 const IdentifierInfo *II = FD->getIdentifier();
2594 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002595 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002596 StringRef FName = II->getName();
2597
Jordan Rose742920c2012-07-02 19:27:35 +00002598 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002599 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002600 if (FName.endswith("NoCopy")) {
2601 // Look for the deallocator argument. We know that the memory ownership
2602 // is not transferred only if the deallocator argument is
2603 // 'kCFAllocatorNull'.
2604 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2605 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2606 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2607 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2608 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002609 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002610 }
2611 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002612 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002613 }
2614
Jordan Rose742920c2012-07-02 19:27:35 +00002615 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002616 // 'closefn' is specified (and if that function does free memory),
2617 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002618 // Currently, we do not inspect the 'closefn' function (PR12101).
2619 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002620 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002621 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002622
2623 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2624 // these leaks might be intentional when setting the buffer for stdio.
2625 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2626 if (FName == "setbuf" || FName =="setbuffer" ||
2627 FName == "setlinebuf" || FName == "setvbuf") {
2628 if (Call->getNumArgs() >= 1) {
2629 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2630 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2631 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2632 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002633 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002634 }
2635 }
2636
2637 // A bunch of other functions which either take ownership of a pointer or
2638 // wrap the result up in a struct or object, meaning it can be freed later.
2639 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2640 // but the Malloc checker cannot differentiate between them. The right way
2641 // of doing this would be to implement a pointer escapes callback.
2642 if (FName == "CGBitmapContextCreate" ||
2643 FName == "CGBitmapContextCreateWithData" ||
2644 FName == "CVPixelBufferCreateWithBytes" ||
2645 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2646 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002647 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002648 }
2649
Anna Zaks03f48332016-01-06 00:32:56 +00002650 if (FName == "postEvent" &&
2651 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2652 return true;
2653 }
2654
2655 if (FName == "postEvent" &&
2656 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2657 return true;
2658 }
2659
Artem Dergachev85c92112016-12-16 12:21:55 +00002660 if (FName == "connectImpl" &&
2661 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2662 return true;
2663 }
2664
Jordan Rose7ab01822012-07-02 19:27:51 +00002665 // Handle cases where we know a buffer's /address/ can escape.
2666 // Note that the above checks handle some special cases where we know that
2667 // even though the address escapes, it's still our responsibility to free the
2668 // buffer.
2669 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002670 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002671
2672 // Otherwise, assume that the function does not free memory.
2673 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002674 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002675}
2676
Anna Zaks333481b2013-03-28 23:15:29 +00002677static bool retTrue(const RefState *RS) {
2678 return true;
2679}
2680
2681static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2682 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2683 RS->getAllocationFamily() == AF_CXXNew);
2684}
2685
Anna Zaksdc154152012-12-20 00:38:25 +00002686ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2687 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002688 const CallEvent *Call,
2689 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002690 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2691}
2692
2693ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2694 const InvalidatedSymbols &Escaped,
2695 const CallEvent *Call,
2696 PointerEscapeKind Kind) const {
2697 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2698 &checkIfNewOrNewArrayFamily);
2699}
2700
2701ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2702 const InvalidatedSymbols &Escaped,
2703 const CallEvent *Call,
2704 PointerEscapeKind Kind,
2705 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002706 // If we know that the call does not free memory, or we want to process the
2707 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002708 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002709 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002710 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2711 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002712 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002713 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002714 }
Anna Zaks3d348342012-02-14 21:55:24 +00002715
Anna Zaksdc154152012-12-20 00:38:25 +00002716 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002717 E = Escaped.end();
2718 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002719 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002720
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002721 if (EscapingSymbol && EscapingSymbol != sym)
2722 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002723
Anna Zaks0d6989b2012-06-22 02:04:31 +00002724 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002725 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2726 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002727 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002728 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2729 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002730 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002731 }
Anna Zaks3d348342012-02-14 21:55:24 +00002732 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002733}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002734
Jordy Rosebf38f202012-03-18 07:43:35 +00002735static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2736 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002737 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2738 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002739
Jordan Rose0c153cb2012-11-02 01:54:06 +00002740 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002741 I != E; ++I) {
2742 SymbolRef sym = I.getKey();
2743 if (!currMap.lookup(sym))
2744 return sym;
2745 }
2746
Craig Topper0dbb7832014-05-27 02:45:47 +00002747 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002748}
2749
David Blaikie0a0c2752017-01-05 17:26:53 +00002750std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2751 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2752 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002753 ProgramStateRef state = N->getState();
2754 ProgramStateRef statePrev = PrevN->getState();
2755
2756 const RefState *RS = state->get<RegionState>(Sym);
2757 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002758 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002759 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002760
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002761 const Stmt *S = PathDiagnosticLocation::getStmt(N);
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002762 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002763 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002764
Jordan Rose681cce92012-07-10 22:07:42 +00002765 // FIXME: We will eventually need to handle non-statement-based events
2766 // (__attribute__((cleanup))).
2767
Anna Zaks2b5bb972012-02-09 06:25:51 +00002768 // Find out if this is an interesting point and what is the kind.
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002769 const char *Msg = nullptr;
2770 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002771 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002772 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002773 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002774 StackHint = new StackHintGeneratorForSymbol(Sym,
2775 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002776 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002777 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002778 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002779 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002780 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002781 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002782 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002783 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002784 Mode = ReallocationFailed;
2785 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002786 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002787 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002788
Jordy Rose21ff76e2012-03-24 03:15:09 +00002789 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2790 // Is it possible to fail two reallocs WITHOUT testing in between?
2791 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2792 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002793 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002794 FailedReallocSymbol = sym;
2795 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002796 }
2797
2798 // We are in a special mode if a reallocation failed later in the path.
2799 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002800 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002801
Jordy Rose21ff76e2012-03-24 03:15:09 +00002802 // Is this is the first appearance of the reallocated symbol?
2803 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002804 // We're at the reallocation point.
2805 Msg = "Attempt to reallocate memory";
2806 StackHint = new StackHintGeneratorForSymbol(Sym,
2807 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002808 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002809 Mode = Normal;
2810 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002811 }
2812
Anna Zaks2b5bb972012-02-09 06:25:51 +00002813 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002814 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002815 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002816
2817 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002818 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002819 N->getLocationContext());
David Blaikie0a0c2752017-01-05 17:26:53 +00002820 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002821}
2822
Anna Zaks263b7e02012-05-02 00:05:20 +00002823void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2824 const char *NL, const char *Sep) const {
2825
2826 RegionStateTy RS = State->get<RegionState>();
2827
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002828 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002829 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002830 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002831 const RefState *RefS = State->get<RegionState>(I.getKey());
2832 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002833 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002834 if (!CheckKind.hasValue())
2835 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002836
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002837 I.getKey()->dumpToStream(Out);
2838 Out << " : ";
2839 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002840 if (CheckKind.hasValue())
2841 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002842 Out << NL;
2843 }
2844 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002845}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002846
Anna Zakse4cfcd42013-04-16 00:22:55 +00002847void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2848 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002849 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002850 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2851 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002852 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2853 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2854 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002855 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00002856 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002857 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002858 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002859}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002860
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002861#define REGISTER_CHECKER(name) \
2862 void ento::register##name(CheckerManager &mgr) { \
2863 registerCStringCheckerBasic(mgr); \
2864 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002865 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2866 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002867 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2868 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2869 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002870
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002871REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002872REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002873REGISTER_CHECKER(MismatchedDeallocatorChecker)