blob: ca4be178c8593a7d6b9dfd4c5214df06f044bc0c [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"
Artem Dergachevb6a513d2017-05-03 11:47:13 +000022#include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000023#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000024#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000025#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000027#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
28#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000029#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000030#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000032#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000033#include <climits>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000034#include <utility>
Anna Zaks199e8e52012-02-22 03:14:20 +000035
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000036using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000037using namespace ento;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000038
39namespace {
40
Anton Yartsev05789592013-03-28 17:05:19 +000041// Used to check correspondence between allocators and deallocators.
42enum AllocationFamily {
43 AF_None,
44 AF_Malloc,
45 AF_CXXNew,
Anna Zaksd79b8402014-10-03 21:48:59 +000046 AF_CXXNewArray,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +000047 AF_IfNameIndex,
48 AF_Alloca
Anton Yartsev05789592013-03-28 17:05:19 +000049};
50
Zhongxing Xu1239de12009-12-11 00:55:44 +000051class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000052 enum Kind { // Reference to allocated memory.
53 Allocated,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000054 // Reference to zero-allocated memory.
55 AllocatedOfSizeZero,
Anna Zaks9050ffd2012-06-20 20:57:46 +000056 // Reference to released/freed memory.
57 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000058 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000059 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000060 Relinquished,
61 // We are no longer guaranteed to have observed all manipulations
62 // of this pointer/memory. For example, it could have been
63 // passed as a parameter to an opaque function.
64 Escaped
65 };
Anton Yartsev05789592013-03-28 17:05:19 +000066
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000067 const Stmt *S;
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000068 unsigned K : 3; // Kind enum, but stored as a bitfield.
Ted Kremenek3a0678e2015-09-08 03:50:52 +000069 unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
Anton Yartsev05789592013-03-28 17:05:19 +000070 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000071
Ted Kremenek3a0678e2015-09-08 03:50:52 +000072 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000073 : S(s), K(k), Family(family) {
74 assert(family != AF_None);
75 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000076public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000077 bool isAllocated() const { return K == Allocated; }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000078 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000079 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000080 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000081 bool isEscaped() const { return K == Escaped; }
82 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000083 return (AllocationFamily)Family;
84 }
Anna Zaksd56c8792012-02-13 18:05:39 +000085 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000086
87 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000088 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000089 }
90
Anton Yartsev05789592013-03-28 17:05:19 +000091 static RefState getAllocated(unsigned family, const Stmt *s) {
92 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000093 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000094 static RefState getAllocatedOfSizeZero(const RefState *RS) {
95 return RefState(AllocatedOfSizeZero, RS->getStmt(),
96 RS->getAllocationFamily());
97 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +000098 static RefState getReleased(unsigned family, const Stmt *s) {
Anton Yartsev05789592013-03-28 17:05:19 +000099 return RefState(Released, s, family);
100 }
101 static RefState getRelinquished(unsigned family, const Stmt *s) {
102 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +0000103 }
Anna Zaks93a21a82013-04-09 00:30:28 +0000104 static RefState getEscaped(const RefState *RS) {
105 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
106 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000107
108 void Profile(llvm::FoldingSetNodeID &ID) const {
109 ID.AddInteger(K);
110 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +0000111 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000112 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000113
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000114 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000115 switch (static_cast<Kind>(K)) {
116#define CASE(ID) case ID: OS << #ID; break;
117 CASE(Allocated)
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000118 CASE(AllocatedOfSizeZero)
Jordan Rose6adadb92014-01-23 03:59:01 +0000119 CASE(Released)
120 CASE(Relinquished)
121 CASE(Escaped)
122 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000123 }
124
Alp Tokeref6b0072014-01-04 13:47:14 +0000125 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000126};
127
Anna Zaks75cfbb62012-09-12 22:57:34 +0000128enum ReallocPairKind {
129 RPToBeFreedAfterFailure,
130 // The symbol has been freed when reallocation failed.
131 RPIsFreeOnFailure,
132 // The symbol does not need to be freed after reallocation fails.
133 RPDoNotTrackAfterFailure
134};
135
Anna Zaksfe6eb672012-08-24 02:28:20 +0000136/// \class ReallocPair
137/// \brief Stores information about the symbol being reallocated by a call to
138/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000139struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000140 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000141 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000142 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000143
Anna Zaks75cfbb62012-09-12 22:57:34 +0000144 ReallocPair(SymbolRef S, ReallocPairKind K) :
145 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000146 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000147 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000148 ID.AddPointer(ReallocatedSym);
149 }
150 bool operator==(const ReallocPair &X) const {
151 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000152 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000153 }
154};
155
Anna Zaksa043d0c2013-01-08 00:25:29 +0000156typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000157
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000158class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000159 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000160 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000161 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000162 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000163 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000164 check::PostStmt<CXXNewExpr>,
165 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000166 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000167 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000168 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000169 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000170{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000171public:
Craig Topper0dbb7832014-05-27 02:45:47 +0000172 MallocChecker()
Anna Zaks30d46682016-03-08 01:21:51 +0000173 : II_alloca(nullptr), II_win_alloca(nullptr), II_malloc(nullptr),
174 II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
175 II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
176 II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr),
177 II_if_nameindex(nullptr), II_if_freenameindex(nullptr),
Anna Zaksbbec97c2017-03-09 00:01:01 +0000178 II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr),
179 II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr),
180 II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr),
Leslie Zhaie3986c52017-04-26 05:33:14 +0000181 II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr),
182 II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr),
183 II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr),
184 II_g_try_realloc_n(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000185
186 /// In pessimistic mode, the checker assumes that it does not know which
187 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000188 enum CheckKind {
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000189 CK_MallocChecker,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000190 CK_NewDeleteChecker,
191 CK_NewDeleteLeaksChecker,
192 CK_MismatchedDeallocatorChecker,
193 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000194 };
195
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000196 enum class MemoryOperationKind {
Anna Zaksd79b8402014-10-03 21:48:59 +0000197 MOK_Allocate,
198 MOK_Free,
199 MOK_Any
200 };
201
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000202 DefaultBool IsOptimistic;
203
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000204 DefaultBool ChecksEnabled[CK_NumCheckKinds];
205 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000206
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000207 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000208 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000209 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
210 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000211 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000212 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000213 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000214 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000215 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000216 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000217 void checkLocation(SVal l, bool isLoad, const Stmt *S,
218 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000219
220 ProgramStateRef checkPointerEscape(ProgramStateRef State,
221 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000222 const CallEvent *Call,
223 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000224 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
225 const InvalidatedSymbols &Escaped,
226 const CallEvent *Call,
227 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000228
Anna Zaks263b7e02012-05-02 00:05:20 +0000229 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000230 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000231
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000232private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000233 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
234 mutable std::unique_ptr<BugType> BT_DoubleDelete;
235 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
236 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
237 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000238 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000239 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
240 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000241 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
Anna Zaks30d46682016-03-08 01:21:51 +0000242 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
243 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
244 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
245 *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
Anna Zaksbbec97c2017-03-09 00:01:01 +0000246 *II_win_wcsdup, *II_g_malloc, *II_g_malloc0,
247 *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0,
Leslie Zhaie3986c52017-04-26 05:33:14 +0000248 *II_g_try_realloc, *II_g_free, *II_g_memdup,
249 *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n,
250 *II_g_try_malloc_n, *II_g_try_malloc0_n,
251 *II_g_try_realloc_n;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000252 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000253
Anna Zaks3d348342012-02-14 21:55:24 +0000254 void initIdentifierInfo(ASTContext &C) const;
255
Anton Yartsev05789592013-03-28 17:05:19 +0000256 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000257 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000258
259 /// \brief Print names of allocators and deallocators.
260 ///
261 /// \returns true on success.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000262 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000263 const Expr *E) const;
264
265 /// \brief Print expected name of an allocator based on the deallocator's
266 /// family derived from the DeallocExpr.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000267 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000268 const Expr *DeallocExpr) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000269 /// \brief Print expected name of a deallocator based on the allocator's
Anton Yartsev05789592013-03-28 17:05:19 +0000270 /// family.
271 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
272
Jordan Rose613f3c02013-03-09 00:59:10 +0000273 ///@{
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000274 /// Check if this is one of the functions which can allocate/reallocate memory
Anna Zaks3d348342012-02-14 21:55:24 +0000275 /// pointed to by one of its arguments.
276 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000277 bool isCMemFunction(const FunctionDecl *FD,
278 ASTContext &C,
279 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000280 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000281 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000282 ///@}
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000283
284 /// \brief Perform a zero-allocation check.
285 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
286 const unsigned AllocationSizeArg,
287 ProgramStateRef State) const;
288
Richard Smith852e9ce2013-11-27 01:46:48 +0000289 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
290 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000291 const OwnershipAttr* Att,
292 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000293 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000294 const Expr *SizeEx, SVal Init,
295 ProgramStateRef State,
296 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000297 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000298 SVal SizeEx, SVal Init,
299 ProgramStateRef State,
300 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000301
Gabor Horvath73040272016-09-19 20:39:52 +0000302 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
303 ProgramStateRef State);
304
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000305 // Check if this malloc() for special flags. At present that means M_ZERO or
306 // __GFP_ZERO (in which case, treat it like calloc).
307 llvm::Optional<ProgramStateRef>
308 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
309 const ProgramStateRef &State) const;
310
Anna Zaks40a7eb32012-02-22 19:24:52 +0000311 /// Update the RefState to reflect the new memory allocation.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000312 static ProgramStateRef
Anton Yartsev05789592013-03-28 17:05:19 +0000313 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
314 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000315
316 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000317 const OwnershipAttr* Att,
318 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000319 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000320 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000321 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000322 bool &ReleasedAllocated,
323 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000324 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
325 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000326 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000327 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000328 bool &ReleasedAllocated,
329 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000330
Leslie Zhaie3986c52017-04-26 05:33:14 +0000331 ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE,
332 bool FreesMemOnFailure,
333 ProgramStateRef State,
334 bool SuffixWithN = false) const;
335 static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
336 const Expr *BlockBytes);
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000337 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
338 ProgramStateRef State);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000339
Anna Zaks46d01602012-05-18 01:16:10 +0000340 ///\brief Check if the memory associated with this symbol was released.
341 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
342
Anton Yartsev13df0362013-03-25 01:35:45 +0000343 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000344
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000345 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000346 const Stmt *S) const;
347
Jordan Rose656fdd52014-01-08 18:46:55 +0000348 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
349
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000350 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000351 /// "interesting" and should be modeled explicitly.
352 ///
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000353 /// \param [out] EscapingSymbol A function might not free memory in general,
Anna Zaks8ebeb642013-06-08 00:29:29 +0000354 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000355 /// returned and the single escaping symbol is returned through the out
356 /// parameter.
357 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000358 /// We assume that pointers do not escape through calls to system functions
359 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000360 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000361 ProgramStateRef State,
362 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000363
Anna Zaks333481b2013-03-28 23:15:29 +0000364 // Implementation of the checkPointerEscape callabcks.
365 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
366 const InvalidatedSymbols &Escaped,
367 const CallEvent *Call,
368 PointerEscapeKind Kind,
369 bool(*CheckRefState)(const RefState*)) const;
370
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000371 ///@{
372 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000373 /// Sets CheckKind to the kind of the checker responsible for this
374 /// family/call/symbol.
Anton Yartsev2487dd62015-03-10 22:24:21 +0000375 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
376 bool IsALeakCheck = false) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000377 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000378 const Stmt *AllocDeallocStmt,
379 bool IsALeakCheck = false) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000380 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000381 bool IsALeakCheck = false) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000382 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000383 static bool SummarizeValue(raw_ostream &os, SVal V);
384 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000385 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +0000386 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000387 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
388 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000389 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000390 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000391 SymbolRef Sym, bool OwnershipTransferred) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000392 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
393 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000394 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000395 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
396 SymbolRef Sym) const;
397 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000398 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000399
Jordan Rose656fdd52014-01-08 18:46:55 +0000400 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
401
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000402 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
403 SymbolRef Sym) const;
404
Daniel Marjamakia43a8f52017-05-02 11:46:12 +0000405 void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
406 SourceRange Range, const Expr *FreeExpr) const;
407
Anna Zaksdf901a42012-02-23 21:38:21 +0000408 /// Find the location of the allocation for Sym on the path leading to the
409 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000410 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
411 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000412
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000413 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
414
Anna Zaks2b5bb972012-02-09 06:25:51 +0000415 /// The bug visitor which allows us to print extra diagnostics along the
416 /// BugReport path. For example, showing the allocation site of the leaked
417 /// region.
David Blaikie6951e3e2015-08-13 22:58:37 +0000418 class MallocBugVisitor final
419 : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000420 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000421 enum NotificationMode {
422 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000423 ReallocationFailed
424 };
425
Anna Zaks2b5bb972012-02-09 06:25:51 +0000426 // The allocated region symbol tracked by the main analysis.
427 SymbolRef Sym;
428
Anna Zaks62cce9e2012-05-10 01:37:40 +0000429 // The mode we are in, i.e. what kind of diagnostics will be emitted.
430 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000431
Anna Zaks62cce9e2012-05-10 01:37:40 +0000432 // A symbol from when the primary region should have been reallocated.
433 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000434
Anna Zaks62cce9e2012-05-10 01:37:40 +0000435 bool IsLeak;
436
437 public:
438 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000439 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000440
Craig Topperfb6b25b2014-03-15 04:29:04 +0000441 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000442 static int X = 0;
443 ID.AddPointer(&X);
444 ID.AddPointer(Sym);
445 }
446
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000447 inline bool isAllocated(const RefState *S, const RefState *SPrev,
448 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000449 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000450 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000451 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
452 (!SPrev || !(SPrev->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000453 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000454 }
455
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000456 inline bool isReleased(const RefState *S, const RefState *SPrev,
457 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000458 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000459 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000460 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
461 }
462
Anna Zaks0d6989b2012-06-22 02:04:31 +0000463 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
464 const Stmt *Stmt) {
465 // Did not track -> relinquished. Other state (allocated) -> relinquished.
466 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
467 isa<ObjCPropertyRefExpr>(Stmt)) &&
468 (S && S->isRelinquished()) &&
469 (!SPrev || !SPrev->isRelinquished()));
470 }
471
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000472 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
473 const Stmt *Stmt) {
474 // If the expression is not a call, and the state change is
475 // released -> allocated, it must be the realloc return value
476 // check. If we have to handle more cases here, it might be cleaner just
477 // to track this extra bit in the state itself.
478 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000479 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
480 (SPrev && !(SPrev->isAllocated() ||
481 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000482 }
483
David Blaikie0a0c2752017-01-05 17:26:53 +0000484 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
485 const ExplodedNode *PrevN,
486 BugReporterContext &BRC,
487 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000488
David Blaikied15481c2014-08-29 18:18:43 +0000489 std::unique_ptr<PathDiagnosticPiece>
490 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
491 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000492 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000493 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000494
495 PathDiagnosticLocation L =
496 PathDiagnosticLocation::createEndOfPath(EndPathNode,
497 BRC.getSourceManager());
498 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000499 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
500 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000501 }
502
Anna Zakscba4f292012-03-16 23:24:20 +0000503 private:
504 class StackHintGeneratorForReallocationFailed
505 : public StackHintGeneratorForSymbol {
506 public:
507 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
508 : StackHintGeneratorForSymbol(S, M) {}
509
Craig Topperfb6b25b2014-03-15 04:29:04 +0000510 std::string getMessageForArg(const Expr *ArgE,
511 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000512 // Printed parameters start at 1, not 0.
513 ++ArgIndex;
514
Anna Zakscba4f292012-03-16 23:24:20 +0000515 SmallString<200> buf;
516 llvm::raw_svector_ostream os(buf);
517
Jordan Rosec102b352012-09-22 01:24:42 +0000518 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
519 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000520
521 return os.str();
522 }
523
Craig Topperfb6b25b2014-03-15 04:29:04 +0000524 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000525 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000526 }
527 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000528 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000529};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000530} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000531
Jordan Rose0c153cb2012-11-02 01:54:06 +0000532REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
533REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Devin Coughlin81771732015-09-22 22:47:14 +0000534REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000535
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000536// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000537// the free function.
538REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
539
Anna Zaksbb1ef902012-02-11 21:02:35 +0000540namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000541class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000542 ProgramStateRef state;
543public:
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000544 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
Anna Zaksbb1ef902012-02-11 21:02:35 +0000545 ProgramStateRef getState() const { return state; }
546
Craig Topperfb6b25b2014-03-15 04:29:04 +0000547 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000548 state = state->remove<RegionState>(sym);
549 return true;
550 }
551};
552} // end anonymous namespace
553
Anna Zaks3d348342012-02-14 21:55:24 +0000554void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000555 if (II_malloc)
556 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000557 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000558 II_malloc = &Ctx.Idents.get("malloc");
559 II_free = &Ctx.Idents.get("free");
560 II_realloc = &Ctx.Idents.get("realloc");
561 II_reallocf = &Ctx.Idents.get("reallocf");
562 II_calloc = &Ctx.Idents.get("calloc");
563 II_valloc = &Ctx.Idents.get("valloc");
564 II_strdup = &Ctx.Idents.get("strdup");
565 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaks30d46682016-03-08 01:21:51 +0000566 II_wcsdup = &Ctx.Idents.get("wcsdup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000567 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000568 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
569 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaks30d46682016-03-08 01:21:51 +0000570
571 //MSVC uses `_`-prefixed instead, so we check for them too.
572 II_win_strdup = &Ctx.Idents.get("_strdup");
573 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
574 II_win_alloca = &Ctx.Idents.get("_alloca");
Anna Zaksbbec97c2017-03-09 00:01:01 +0000575
576 // Glib
577 II_g_malloc = &Ctx.Idents.get("g_malloc");
578 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
579 II_g_realloc = &Ctx.Idents.get("g_realloc");
580 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
581 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
582 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
583 II_g_free = &Ctx.Idents.get("g_free");
584 II_g_memdup = &Ctx.Idents.get("g_memdup");
Leslie Zhaie3986c52017-04-26 05:33:14 +0000585 II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
586 II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
587 II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
588 II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
589 II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
590 II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000591}
592
Anna Zaks3d348342012-02-14 21:55:24 +0000593bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000594 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000595 return true;
596
Anna Zaksd79b8402014-10-03 21:48:59 +0000597 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000598 return true;
599
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000600 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
601 return true;
602
Anton Yartsev13df0362013-03-25 01:35:45 +0000603 if (isStandardNewDelete(FD, C))
604 return true;
605
Anna Zaks46d01602012-05-18 01:16:10 +0000606 return false;
607}
608
Anna Zaksd79b8402014-10-03 21:48:59 +0000609bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
610 ASTContext &C,
611 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000612 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000613 if (!FD)
614 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000615
Anna Zaksd79b8402014-10-03 21:48:59 +0000616 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
617 MemKind == MemoryOperationKind::MOK_Free);
618 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
619 MemKind == MemoryOperationKind::MOK_Allocate);
620
Jordan Rose6cd16c52012-07-10 23:13:01 +0000621 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000622 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000623 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000624
Anna Zaksd79b8402014-10-03 21:48:59 +0000625 if (Family == AF_Malloc && CheckFree) {
Anna Zaksbbec97c2017-03-09 00:01:01 +0000626 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
627 FunI == II_g_free)
Anna Zaksd79b8402014-10-03 21:48:59 +0000628 return true;
629 }
630
631 if (Family == AF_Malloc && CheckAlloc) {
632 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
633 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
Anna Zaks30d46682016-03-08 01:21:51 +0000634 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
Anna Zaksbbec97c2017-03-09 00:01:01 +0000635 FunI == II_win_wcsdup || FunI == II_kmalloc ||
636 FunI == II_g_malloc || FunI == II_g_malloc0 ||
637 FunI == II_g_realloc || FunI == II_g_try_malloc ||
638 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
Leslie Zhaie3986c52017-04-26 05:33:14 +0000639 FunI == II_g_memdup || FunI == II_g_malloc_n ||
640 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
641 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
642 FunI == II_g_try_realloc_n)
Anna Zaksd79b8402014-10-03 21:48:59 +0000643 return true;
644 }
645
646 if (Family == AF_IfNameIndex && CheckFree) {
647 if (FunI == II_if_freenameindex)
648 return true;
649 }
650
651 if (Family == AF_IfNameIndex && CheckAlloc) {
652 if (FunI == II_if_nameindex)
653 return true;
654 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000655
656 if (Family == AF_Alloca && CheckAlloc) {
Anna Zaks30d46682016-03-08 01:21:51 +0000657 if (FunI == II_alloca || FunI == II_win_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000658 return true;
659 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000660 }
Anna Zaks3d348342012-02-14 21:55:24 +0000661
Anna Zaksd79b8402014-10-03 21:48:59 +0000662 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000663 return false;
664
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000665 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000666 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
667 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
668 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
669 if (CheckFree)
670 return true;
671 } else if (OwnKind == OwnershipAttr::Returns) {
672 if (CheckAlloc)
673 return true;
674 }
675 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000676 }
Anna Zaks3d348342012-02-14 21:55:24 +0000677
Anna Zaks3d348342012-02-14 21:55:24 +0000678 return false;
679}
680
Anton Yartsev8b662702013-03-28 16:10:38 +0000681// Tells if the callee is one of the following:
682// 1) A global non-placement new/delete operator function.
683// 2) A global placement operator function with the single placement argument
684// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000685bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
686 ASTContext &C) const {
687 if (!FD)
688 return false;
689
690 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000691 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000692 Kind != OO_Delete && Kind != OO_Array_Delete)
693 return false;
694
Anton Yartsev8b662702013-03-28 16:10:38 +0000695 // Skip all operator new/delete methods.
696 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000697 return false;
698
699 // Return true if tested operator is a standard placement nothrow operator.
700 if (FD->getNumParams() == 2) {
701 QualType T = FD->getParamDecl(1)->getType();
702 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
703 return II->getName().equals("nothrow_t");
704 }
705
706 // Skip placement operators.
707 if (FD->getNumParams() != 1 || FD->isVariadic())
708 return false;
709
710 // One of the standard new/new[]/delete/delete[] non-placement operators.
711 return true;
712}
713
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000714llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
715 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
716 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
717 //
718 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
719 //
720 // One of the possible flags is M_ZERO, which means 'give me back an
721 // allocation which is already zeroed', like calloc.
722
723 // 2-argument kmalloc(), as used in the Linux kernel:
724 //
725 // void *kmalloc(size_t size, gfp_t flags);
726 //
727 // Has the similar flag value __GFP_ZERO.
728
729 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
730 // code could be shared.
731
732 ASTContext &Ctx = C.getASTContext();
733 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
734
735 if (!KernelZeroFlagVal.hasValue()) {
736 if (OS == llvm::Triple::FreeBSD)
737 KernelZeroFlagVal = 0x0100;
738 else if (OS == llvm::Triple::NetBSD)
739 KernelZeroFlagVal = 0x0002;
740 else if (OS == llvm::Triple::OpenBSD)
741 KernelZeroFlagVal = 0x0008;
742 else if (OS == llvm::Triple::Linux)
743 // __GFP_ZERO
744 KernelZeroFlagVal = 0x8000;
745 else
746 // FIXME: We need a more general way of getting the M_ZERO value.
747 // See also: O_CREAT in UnixAPIChecker.cpp.
748
749 // Fall back to normal malloc behavior on platforms where we don't
750 // know M_ZERO.
751 return None;
752 }
753
754 // We treat the last argument as the flags argument, and callers fall-back to
755 // normal malloc on a None return. This works for the FreeBSD kernel malloc
756 // as well as Linux kmalloc.
757 if (CE->getNumArgs() < 2)
758 return None;
759
760 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
George Karpenkovd703ec92018-01-17 20:27:29 +0000761 const SVal V = C.getSVal(FlagsEx);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000762 if (!V.getAs<NonLoc>()) {
763 // The case where 'V' can be a location can only be due to a bad header,
764 // so in this case bail out.
765 return None;
766 }
767
768 NonLoc Flags = V.castAs<NonLoc>();
769 NonLoc ZeroFlag = C.getSValBuilder()
770 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
771 .castAs<NonLoc>();
772 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
773 Flags, ZeroFlag,
774 FlagsEx->getType());
775 if (MaskedFlagsUC.isUnknownOrUndef())
776 return None;
777 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
778
779 // Check if maskedFlags is non-zero.
780 ProgramStateRef TrueState, FalseState;
781 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
782
783 // If M_ZERO is set, treat this like calloc (initialized).
784 if (TrueState && !FalseState) {
785 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
786 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
787 }
788
789 return None;
790}
791
Leslie Zhaie3986c52017-04-26 05:33:14 +0000792SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
793 const Expr *BlockBytes) {
794 SValBuilder &SB = C.getSValBuilder();
795 SVal BlocksVal = C.getSVal(Blocks);
796 SVal BlockBytesVal = C.getSVal(BlockBytes);
797 ProgramStateRef State = C.getState();
798 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
799 SB.getContext().getSizeType());
800 return TotalSize;
801}
802
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000803void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000804 if (C.wasInlined)
805 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000806
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000807 const FunctionDecl *FD = C.getCalleeDecl(CE);
808 if (!FD)
809 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000810
Anna Zaks40a7eb32012-02-22 19:24:52 +0000811 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000812 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000813
814 if (FD->getKind() == Decl::Function) {
815 initIdentifierInfo(C.getASTContext());
816 IdentifierInfo *FunI = FD->getIdentifier();
817
Anna Zaksbbec97c2017-03-09 00:01:01 +0000818 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000819 if (CE->getNumArgs() < 1)
820 return;
821 if (CE->getNumArgs() < 3) {
822 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000823 if (CE->getNumArgs() == 1)
824 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000825 } else if (CE->getNumArgs() == 3) {
826 llvm::Optional<ProgramStateRef> MaybeState =
827 performKernelMalloc(CE, C, State);
828 if (MaybeState.hasValue())
829 State = MaybeState.getValue();
830 else
831 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
832 }
833 } else if (FunI == II_kmalloc) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000834 if (CE->getNumArgs() < 1)
835 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000836 llvm::Optional<ProgramStateRef> MaybeState =
837 performKernelMalloc(CE, C, State);
838 if (MaybeState.hasValue())
839 State = MaybeState.getValue();
840 else
841 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
842 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000843 if (CE->getNumArgs() < 1)
844 return;
845 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000846 State = ProcessZeroAllocation(C, CE, 0, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000847 } else if (FunI == II_realloc || FunI == II_g_realloc ||
848 FunI == II_g_try_realloc) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000849 State = ReallocMemAux(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000850 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000851 } else if (FunI == II_reallocf) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000852 State = ReallocMemAux(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000853 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000854 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000855 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000856 State = ProcessZeroAllocation(C, CE, 0, State);
857 State = ProcessZeroAllocation(C, CE, 1, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000858 } else if (FunI == II_free || FunI == II_g_free) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000859 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaks30d46682016-03-08 01:21:51 +0000860 } else if (FunI == II_strdup || FunI == II_win_strdup ||
861 FunI == II_wcsdup || FunI == II_win_wcsdup) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000862 State = MallocUpdateRefState(C, CE, State);
863 } else if (FunI == II_strndup) {
864 State = MallocUpdateRefState(C, CE, State);
Anna Zaks30d46682016-03-08 01:21:51 +0000865 } else if (FunI == II_alloca || FunI == II_win_alloca) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000866 if (CE->getNumArgs() < 1)
867 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000868 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
869 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000870 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000871 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000872 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000873 // as distinct from new/new[]/delete/delete[] expressions that are
874 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000875 // CXXDeleteExpr.
876 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000877 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000878 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
879 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000880 State = ProcessZeroAllocation(C, CE, 0, State);
881 }
882 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000883 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
884 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000885 State = ProcessZeroAllocation(C, CE, 0, State);
886 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000887 else if (K == OO_Delete || K == OO_Array_Delete)
888 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
889 else
890 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000891 } else if (FunI == II_if_nameindex) {
892 // Should we model this differently? We can allocate a fixed number of
893 // elements with zeros in the last one.
894 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
895 AF_IfNameIndex);
896 } else if (FunI == II_if_freenameindex) {
897 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000898 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
899 if (CE->getNumArgs() < 1)
900 return;
901 SValBuilder &svalBuilder = C.getSValBuilder();
902 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
903 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
904 State = ProcessZeroAllocation(C, CE, 0, State);
905 } else if (FunI == II_g_memdup) {
906 if (CE->getNumArgs() < 2)
907 return;
908 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
909 State = ProcessZeroAllocation(C, CE, 1, State);
Leslie Zhaie3986c52017-04-26 05:33:14 +0000910 } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
911 FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
912 if (CE->getNumArgs() < 2)
913 return;
914 SVal Init = UndefinedVal();
915 if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
916 SValBuilder &SB = C.getSValBuilder();
917 Init = SB.makeZeroVal(SB.getContext().CharTy);
918 }
919 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
920 State = MallocMemAux(C, CE, TotalSize, Init, State);
921 State = ProcessZeroAllocation(C, CE, 0, State);
922 State = ProcessZeroAllocation(C, CE, 1, State);
923 } else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
924 if (CE->getNumArgs() < 3)
925 return;
926 State = ReallocMemAux(C, CE, false, State, true);
927 State = ProcessZeroAllocation(C, CE, 1, State);
928 State = ProcessZeroAllocation(C, CE, 2, State);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000929 }
930 }
931
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000932 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000933 // Check all the attributes, if there are any.
934 // There can be multiple of these attributes.
935 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000936 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
937 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000938 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000939 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000940 break;
941 case OwnershipAttr::Takes:
942 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000943 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000944 break;
945 }
946 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000947 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000948 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000949}
950
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000951// Performs a 0-sized allocations check.
952ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
953 const Expr *E,
954 const unsigned AllocationSizeArg,
955 ProgramStateRef State) const {
956 if (!State)
957 return nullptr;
958
959 const Expr *Arg = nullptr;
960
961 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
962 Arg = CE->getArg(AllocationSizeArg);
963 }
964 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
965 if (NE->isArray())
966 Arg = NE->getArraySize();
967 else
968 return State;
969 }
970 else
971 llvm_unreachable("not a CallExpr or CXXNewExpr");
972
973 assert(Arg);
974
George Karpenkovd703ec92018-01-17 20:27:29 +0000975 Optional<DefinedSVal> DefArgVal = C.getSVal(Arg).getAs<DefinedSVal>();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000976
977 if (!DefArgVal)
978 return State;
979
980 // Check if the allocation size is 0.
981 ProgramStateRef TrueState, FalseState;
982 SValBuilder &SvalBuilder = C.getSValBuilder();
983 DefinedSVal Zero =
984 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
985
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000986 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000987 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
988
989 if (TrueState && !FalseState) {
George Karpenkovd703ec92018-01-17 20:27:29 +0000990 SVal retVal = C.getSVal(E);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000991 SymbolRef Sym = retVal.getAsLocSymbol();
992 if (!Sym)
993 return State;
994
995 const RefState *RS = State->get<RegionState>(Sym);
Devin Coughlin81771732015-09-22 22:47:14 +0000996 if (RS) {
997 if (RS->isAllocated())
998 return TrueState->set<RegionState>(Sym,
999 RefState::getAllocatedOfSizeZero(RS));
1000 else
1001 return State;
1002 } else {
1003 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1004 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1005 // tracked. Add zero-reallocated Sym to the state to catch references
1006 // to zero-allocated memory.
1007 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1008 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001009 }
1010
1011 // Assume the value is non-zero going forward.
1012 assert(FalseState);
1013 return FalseState;
1014}
1015
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001016static QualType getDeepPointeeType(QualType T) {
1017 QualType Result = T, PointeeType = T->getPointeeType();
1018 while (!PointeeType.isNull()) {
1019 Result = PointeeType;
1020 PointeeType = PointeeType->getPointeeType();
1021 }
1022 return Result;
1023}
1024
1025static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1026
1027 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1028 if (!ConstructE)
1029 return false;
1030
1031 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1032 return false;
1033
1034 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1035
1036 // Iterate over the constructor parameters.
David Majnemer59f77922016-06-24 04:05:48 +00001037 for (const auto *CtorParam : CtorD->parameters()) {
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001038
1039 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1040 if (CtorParamPointeeT.isNull())
1041 continue;
1042
1043 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1044
1045 if (CtorParamPointeeT->getAsCXXRecordDecl())
1046 return true;
1047 }
1048
1049 return false;
1050}
1051
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001052void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001053 CheckerContext &C) const {
1054
1055 if (NE->getNumPlacementArgs())
1056 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1057 E = NE->placement_arg_end(); I != E; ++I)
1058 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1059 checkUseAfterFree(Sym, C, *I);
1060
Anton Yartsev13df0362013-03-25 01:35:45 +00001061 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1062 return;
1063
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001064 ParentMap &PM = C.getLocationContext()->getParentMap();
1065 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1066 return;
1067
Anton Yartsev13df0362013-03-25 01:35:45 +00001068 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001069 // The return value from operator new is bound to a specified initialization
1070 // value (if any) and we don't want to loose this value. So we call
1071 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +00001072 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001073 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Anton Yartsev05789592013-03-28 17:05:19 +00001074 : AF_CXXNew);
Gabor Horvath73040272016-09-19 20:39:52 +00001075 State = addExtentSize(C, NE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001076 State = ProcessZeroAllocation(C, NE, 0, State);
Anton Yartsev13df0362013-03-25 01:35:45 +00001077 C.addTransition(State);
1078}
1079
Gabor Horvath73040272016-09-19 20:39:52 +00001080// Sets the extent value of the MemRegion allocated by
1081// new expression NE to its size in Bytes.
1082//
1083ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1084 const CXXNewExpr *NE,
1085 ProgramStateRef State) {
1086 if (!State)
1087 return nullptr;
1088 SValBuilder &svalBuilder = C.getSValBuilder();
1089 SVal ElementCount;
1090 const LocationContext *LCtx = C.getLocationContext();
1091 const SubRegion *Region;
1092 if (NE->isArray()) {
1093 const Expr *SizeExpr = NE->getArraySize();
George Karpenkovd703ec92018-01-17 20:27:29 +00001094 ElementCount = C.getSVal(SizeExpr);
Gabor Horvath73040272016-09-19 20:39:52 +00001095 // Store the extent size for the (symbolic)region
1096 // containing the elements.
1097 Region = (State->getSVal(NE, LCtx))
1098 .getAsRegion()
1099 ->getAs<SubRegion>()
1100 ->getSuperRegion()
1101 ->getAs<SubRegion>();
1102 } else {
1103 ElementCount = svalBuilder.makeIntVal(1, true);
1104 Region = (State->getSVal(NE, LCtx)).getAsRegion()->getAs<SubRegion>();
1105 }
1106 assert(Region);
1107
1108 // Set the region's extent equal to the Size in Bytes.
1109 QualType ElementType = NE->getAllocatedType();
1110 ASTContext &AstContext = C.getASTContext();
1111 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1112
Devin Coughline3b75de2016-12-16 18:41:40 +00001113 if (ElementCount.getAs<NonLoc>()) {
Gabor Horvath73040272016-09-19 20:39:52 +00001114 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1115 // size in Bytes = ElementCount*TypeSize
1116 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1117 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1118 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1119 svalBuilder.getArrayIndexType());
1120 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1121 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1122 State = State->assume(extentMatchesSize, true);
1123 }
1124 return State;
1125}
1126
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001127void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001128 CheckerContext &C) const {
1129
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001130 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +00001131 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1132 checkUseAfterFree(Sym, C, DE->getArgument());
1133
Anton Yartsev13df0362013-03-25 01:35:45 +00001134 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1135 return;
1136
1137 ProgramStateRef State = C.getState();
1138 bool ReleasedAllocated;
1139 State = FreeMemAux(C, DE->getArgument(), DE, State,
1140 /*Hold*/false, ReleasedAllocated);
1141
1142 C.addTransition(State);
1143}
1144
Jordan Rose613f3c02013-03-09 00:59:10 +00001145static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1146 // If the first selector piece is one of the names below, assume that the
1147 // object takes ownership of the memory, promising to eventually deallocate it
1148 // with free().
1149 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1150 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1151 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
Alexander Kornienko9c104902015-12-28 13:06:58 +00001152 return FirstSlot == "dataWithBytesNoCopy" ||
1153 FirstSlot == "initWithBytesNoCopy" ||
1154 FirstSlot == "initWithCharactersNoCopy";
Anna Zaks0d6989b2012-06-22 02:04:31 +00001155}
1156
Jordan Rose613f3c02013-03-09 00:59:10 +00001157static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1158 Selector S = Call.getSelector();
1159
1160 // FIXME: We should not rely on fully-constrained symbols being folded.
1161 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1162 if (S.getNameForSlot(i).equals("freeWhenDone"))
1163 return !Call.getArgSVal(i).isZeroConstant();
1164
1165 return None;
1166}
1167
Anna Zaks67291b92012-11-13 03:18:01 +00001168void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1169 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001170 if (C.wasInlined)
1171 return;
1172
Jordan Rose613f3c02013-03-09 00:59:10 +00001173 if (!isKnownDeallocObjCMethodName(Call))
1174 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001175
Jordan Rose613f3c02013-03-09 00:59:10 +00001176 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1177 if (!*FreeWhenDone)
1178 return;
1179
1180 bool ReleasedAllocatedMemory;
1181 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1182 Call.getOriginExpr(), C.getState(),
1183 /*Hold=*/true, ReleasedAllocatedMemory,
1184 /*RetNullOnFailure=*/true);
1185
1186 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001187}
1188
Richard Smith852e9ce2013-11-27 01:46:48 +00001189ProgramStateRef
1190MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001191 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001192 ProgramStateRef State) const {
1193 if (!State)
1194 return nullptr;
1195
Richard Smith852e9ce2013-11-27 01:46:48 +00001196 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001197 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001198
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001199 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001200 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001201 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001202 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001203 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1204}
1205
1206ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1207 const CallExpr *CE,
1208 const Expr *SizeEx, SVal Init,
1209 ProgramStateRef State,
1210 AllocationFamily Family) {
1211 if (!State)
1212 return nullptr;
1213
George Karpenkovd703ec92018-01-17 20:27:29 +00001214 return MallocMemAux(C, CE, C.getSVal(SizeEx), Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001215}
1216
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001217ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001218 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001219 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001220 ProgramStateRef State,
1221 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001222 if (!State)
1223 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001224
Jordan Rosef69e65f2014-09-05 16:33:51 +00001225 // We expect the malloc functions to return a pointer.
1226 if (!Loc::isLocType(CE->getType()))
1227 return nullptr;
1228
Anna Zaks3563fde2012-06-07 03:57:32 +00001229 // Bind the return value to the symbolic value from the heap region.
1230 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1231 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001232 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001233 SValBuilder &svalBuilder = C.getSValBuilder();
1234 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001235 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1236 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001237 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001238
Jordy Rose674bd552010-07-04 00:00:41 +00001239 // Fill the region with the initialization value.
Anna Zaksb5701952017-01-13 00:50:57 +00001240 State = State->bindDefault(RetVal, Init, LCtx);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001241
Jordy Rose674bd552010-07-04 00:00:41 +00001242 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001243 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001244 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001245 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001246 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001247 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001248 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001249 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001250 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001251 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001252 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001253
Anton Yartsev05789592013-03-28 17:05:19 +00001254 State = State->assume(extentMatchesSize, true);
1255 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001256 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001257
Anton Yartsev05789592013-03-28 17:05:19 +00001258 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001259}
1260
1261ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001262 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001263 ProgramStateRef State,
1264 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001265 if (!State)
1266 return nullptr;
1267
Anna Zaks40a7eb32012-02-22 19:24:52 +00001268 // Get the return value.
George Karpenkovd703ec92018-01-17 20:27:29 +00001269 SVal retVal = C.getSVal(E);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001270
1271 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001272 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001273 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001274
Ted Kremenek90af9092010-12-02 07:49:45 +00001275 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001276 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001277
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001278 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001279 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001280}
1281
Anna Zaks40a7eb32012-02-22 19:24:52 +00001282ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1283 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001284 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001285 ProgramStateRef State) const {
1286 if (!State)
1287 return nullptr;
1288
Richard Smith852e9ce2013-11-27 01:46:48 +00001289 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001290 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001291
Anna Zaksfe6eb672012-08-24 02:28:20 +00001292 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001293
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001294 for (const auto &Arg : Att->args()) {
1295 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001296 Att->getOwnKind() == OwnershipAttr::Holds,
1297 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001298 if (StateI)
1299 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001300 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001301 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001302}
1303
Ted Kremenek49b1e382012-01-26 21:29:00 +00001304ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001305 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001306 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001307 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001308 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001309 bool &ReleasedAllocated,
1310 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001311 if (!State)
1312 return nullptr;
1313
Anna Zaksb508d292012-04-10 23:41:11 +00001314 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001315 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001316
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001317 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001318 ReleasedAllocated, ReturnsNullOnFailure);
1319}
1320
Anna Zaksa14c1d02012-11-13 19:47:40 +00001321/// Checks if the previous call to free on the given symbol failed - if free
1322/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001323static bool didPreviousFreeFail(ProgramStateRef State,
1324 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001325 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001326 if (Ret) {
1327 assert(*Ret && "We should not store the null return symbol");
1328 ConstraintManager &CMgr = State->getConstraintManager();
1329 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001330 RetStatusSymbol = *Ret;
1331 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001332 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001333 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001334}
1335
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001336AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001337 const Stmt *S) const {
1338 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001339 return AF_None;
1340
Anton Yartseve3377fb2013-04-04 23:46:29 +00001341 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001342 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001343
1344 if (!FD)
1345 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1346
Anton Yartsev05789592013-03-28 17:05:19 +00001347 ASTContext &Ctx = C.getASTContext();
1348
Anna Zaksd79b8402014-10-03 21:48:59 +00001349 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001350 return AF_Malloc;
1351
1352 if (isStandardNewDelete(FD, Ctx)) {
1353 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001354 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001355 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001356 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001357 return AF_CXXNewArray;
1358 }
1359
Anna Zaksd79b8402014-10-03 21:48:59 +00001360 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1361 return AF_IfNameIndex;
1362
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001363 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1364 return AF_Alloca;
1365
Anton Yartsev05789592013-03-28 17:05:19 +00001366 return AF_None;
1367 }
1368
Anton Yartseve3377fb2013-04-04 23:46:29 +00001369 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1370 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1371
1372 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001373 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1374
Anton Yartseve3377fb2013-04-04 23:46:29 +00001375 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001376 return AF_Malloc;
1377
1378 return AF_None;
1379}
1380
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001381bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001382 const Expr *E) const {
1383 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1384 // FIXME: This doesn't handle indirect calls.
1385 const FunctionDecl *FD = CE->getDirectCallee();
1386 if (!FD)
1387 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001388
Anton Yartsev05789592013-03-28 17:05:19 +00001389 os << *FD;
1390 if (!FD->isOverloadedOperator())
1391 os << "()";
1392 return true;
1393 }
1394
1395 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1396 if (Msg->isInstanceMessage())
1397 os << "-";
1398 else
1399 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001400 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001401 return true;
1402 }
1403
1404 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001405 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001406 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1407 << "'";
1408 return true;
1409 }
1410
1411 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001412 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001413 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1414 << "'";
1415 return true;
1416 }
1417
1418 return false;
1419}
1420
1421void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1422 const Expr *E) const {
1423 AllocationFamily Family = getAllocationFamily(C, E);
1424
1425 switch(Family) {
1426 case AF_Malloc: os << "malloc()"; return;
1427 case AF_CXXNew: os << "'new'"; return;
1428 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001429 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001430 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001431 case AF_None: llvm_unreachable("not a deallocation expression");
1432 }
1433}
1434
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001435void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001436 AllocationFamily Family) const {
1437 switch(Family) {
1438 case AF_Malloc: os << "free()"; return;
1439 case AF_CXXNew: os << "'delete'"; return;
1440 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001441 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001442 case AF_Alloca:
1443 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001444 }
1445}
1446
Anna Zaks0d6989b2012-06-22 02:04:31 +00001447ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1448 const Expr *ArgExpr,
1449 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001450 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001451 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001452 bool &ReleasedAllocated,
1453 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001454
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001455 if (!State)
1456 return nullptr;
1457
George Karpenkovd703ec92018-01-17 20:27:29 +00001458 SVal ArgVal = C.getSVal(ArgExpr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001459 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001460 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001461 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001462
1463 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001464 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001465 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001466
Anna Zaksad01ef52012-02-14 00:26:13 +00001467 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001468 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001469 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001470 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001471 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001472
Jordy Rose3597b212010-06-07 19:32:37 +00001473 // Unknown values could easily be okay
1474 // Undefined values are handled elsewhere
1475 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001476 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001477
Jordy Rose3597b212010-06-07 19:32:37 +00001478 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001479
Jordy Rose3597b212010-06-07 19:32:37 +00001480 // Nonlocs can't be freed, of course.
1481 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1482 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001483 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001484 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001485 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001486
Jordy Rose3597b212010-06-07 19:32:37 +00001487 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001488
Jordy Rose3597b212010-06-07 19:32:37 +00001489 // Blocks might show up as heap data, but should not be free()d
1490 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001491 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001492 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001493 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001494
Jordy Rose3597b212010-06-07 19:32:37 +00001495 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001496
1497 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001498 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001499 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1500 // FIXME: at the time this code was written, malloc() regions were
1501 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1502 // This means that there isn't actually anything from HeapSpaceRegion
1503 // that should be freed, even though we allow it here.
1504 // Of course, free() can work on memory allocated outside the current
1505 // function, so UnknownSpaceRegion is always a possibility.
1506 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001507
1508 if (isa<AllocaRegion>(R))
1509 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1510 else
1511 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1512
Craig Topper0dbb7832014-05-27 02:45:47 +00001513 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001514 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001515
1516 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001517 // Various cases could lead to non-symbol values here.
1518 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001519 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001520 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001521
Anna Zaksc89ad072013-02-07 23:05:47 +00001522 SymbolRef SymBase = SrBase->getSymbol();
1523 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001524 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001525
Anton Yartseve3377fb2013-04-04 23:46:29 +00001526 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001527
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001528 // Memory returned by alloca() shouldn't be freed.
1529 if (RsBase->getAllocationFamily() == AF_Alloca) {
1530 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1531 return nullptr;
1532 }
1533
Anna Zaks93a21a82013-04-09 00:30:28 +00001534 // Check for double free first.
1535 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001536 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1537 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1538 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001539 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001540
Anna Zaks93a21a82013-04-09 00:30:28 +00001541 // If the pointer is allocated or escaped, but we are now trying to free it,
1542 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001543 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001544 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001545
1546 // Check if an expected deallocation function matches the real one.
1547 bool DeallocMatchesAlloc =
1548 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1549 if (!DeallocMatchesAlloc) {
1550 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001551 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001552 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001553 }
1554
1555 // Check if the memory location being freed is the actual location
1556 // allocated, or an offset.
1557 RegionOffset Offset = R->getAsOffset();
1558 if (Offset.isValid() &&
1559 !Offset.hasSymbolicOffset() &&
1560 Offset.getOffset() != 0) {
1561 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001562 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001563 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001564 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001565 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001566 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001567 }
1568
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00001569 if (SymBase->getType()->isFunctionPointerType()) {
1570 ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1571 return nullptr;
1572 }
1573
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001574 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001575 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001576
Anna Zaksa14c1d02012-11-13 19:47:40 +00001577 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001578 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001579
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001580 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001581 // failed.
1582 if (ReturnsNullOnFailure) {
1583 SVal RetVal = C.getSVal(ParentExpr);
1584 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1585 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001586 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1587 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001588 }
1589 }
1590
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001591 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1592 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001593 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001594 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001595 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001596 RefState::getRelinquished(Family,
1597 ParentExpr));
1598
1599 return State->set<RegionState>(SymBase,
1600 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001601}
1602
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001603Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001604MallocChecker::getCheckIfTracked(AllocationFamily Family,
1605 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001606 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001607 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001608 case AF_Alloca:
1609 case AF_IfNameIndex: {
1610 if (ChecksEnabled[CK_MallocChecker])
1611 return CK_MallocChecker;
1612
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001613 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001614 }
1615 case AF_CXXNew:
1616 case AF_CXXNewArray: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001617 if (IsALeakCheck) {
1618 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1619 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001620 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001621 else {
1622 if (ChecksEnabled[CK_NewDeleteChecker])
1623 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001624 }
1625 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001626 }
1627 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001628 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001629 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001630 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001631 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001632}
1633
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001634Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001635MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001636 const Stmt *AllocDeallocStmt,
1637 bool IsALeakCheck) const {
1638 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1639 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001640}
1641
1642Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001643MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1644 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001645 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1646 return CK_MallocChecker;
1647
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001648 const RefState *RS = C.getState()->get<RegionState>(Sym);
1649 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001650 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001651}
1652
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001653bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001654 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001655 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001656 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001657 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001658 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001659 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001660 else
1661 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001662
Jordy Rose3597b212010-06-07 19:32:37 +00001663 return true;
1664}
1665
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001666bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001667 const MemRegion *MR) {
1668 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +00001669 case MemRegion::FunctionCodeRegionKind: {
1670 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001671 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001672 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001673 else
1674 os << "the address of a function";
1675 return true;
1676 }
Artem Dergachev73f018e2016-01-13 13:49:29 +00001677 case MemRegion::BlockCodeRegionKind:
Jordy Rose3597b212010-06-07 19:32:37 +00001678 os << "block text";
1679 return true;
1680 case MemRegion::BlockDataRegionKind:
1681 // FIXME: where the block came from?
1682 os << "a block";
1683 return true;
1684 default: {
1685 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001686
Anna Zaks8158ef02012-01-04 23:54:01 +00001687 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001688 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1689 const VarDecl *VD;
1690 if (VR)
1691 VD = VR->getDecl();
1692 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001693 VD = nullptr;
1694
Jordy Rose3597b212010-06-07 19:32:37 +00001695 if (VD)
1696 os << "the address of the local variable '" << VD->getName() << "'";
1697 else
1698 os << "the address of a local stack variable";
1699 return true;
1700 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001701
1702 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001703 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1704 const VarDecl *VD;
1705 if (VR)
1706 VD = VR->getDecl();
1707 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001708 VD = nullptr;
1709
Jordy Rose3597b212010-06-07 19:32:37 +00001710 if (VD)
1711 os << "the address of the parameter '" << VD->getName() << "'";
1712 else
1713 os << "the address of a parameter";
1714 return true;
1715 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001716
1717 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001718 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1719 const VarDecl *VD;
1720 if (VR)
1721 VD = VR->getDecl();
1722 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001723 VD = nullptr;
1724
Jordy Rose3597b212010-06-07 19:32:37 +00001725 if (VD) {
1726 if (VD->isStaticLocal())
1727 os << "the address of the static variable '" << VD->getName() << "'";
1728 else
1729 os << "the address of the global variable '" << VD->getName() << "'";
1730 } else
1731 os << "the address of a global variable";
1732 return true;
1733 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001734
1735 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001736 }
1737 }
1738}
1739
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001740void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1741 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001742 const Expr *DeallocExpr) const {
1743
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001744 if (!ChecksEnabled[CK_MallocChecker] &&
1745 !ChecksEnabled[CK_NewDeleteChecker])
1746 return;
1747
1748 Optional<MallocChecker::CheckKind> CheckKind =
1749 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001750 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001751 return;
1752
Devin Coughline39bd402015-09-16 22:03:05 +00001753 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001754 if (!BT_BadFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001755 BT_BadFree[*CheckKind].reset(new BugType(
1756 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001757
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001758 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001759 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001760
Jordy Rose3597b212010-06-07 19:32:37 +00001761 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001762 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1763 MR = ER->getSuperRegion();
1764
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001765 os << "Argument to ";
1766 if (!printAllocDeallocName(os, C, DeallocExpr))
1767 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001768
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001769 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001770 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001771 : SummarizeValue(os, ArgVal);
1772 if (Summarized)
1773 os << ", which is not memory allocated by ";
1774 else
1775 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001776
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001777 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001778
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001779 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001780 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001781 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001782 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001783 }
1784}
1785
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001786void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001787 SourceRange Range) const {
1788
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001789 Optional<MallocChecker::CheckKind> CheckKind;
1790
1791 if (ChecksEnabled[CK_MallocChecker])
1792 CheckKind = CK_MallocChecker;
1793 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1794 CheckKind = CK_MismatchedDeallocatorChecker;
1795 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001796 return;
1797
Devin Coughline39bd402015-09-16 22:03:05 +00001798 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001799 if (!BT_FreeAlloca[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001800 BT_FreeAlloca[*CheckKind].reset(new BugType(
1801 CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001802
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001803 auto R = llvm::make_unique<BugReport>(
1804 *BT_FreeAlloca[*CheckKind],
1805 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001806 R->markInteresting(ArgVal.getAsRegion());
1807 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001808 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001809 }
1810}
1811
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001812void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001813 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001814 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001815 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001816 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001817 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001818
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001819 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001820 return;
1821
Devin Coughline39bd402015-09-16 22:03:05 +00001822 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001823 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001824 BT_MismatchedDealloc.reset(
1825 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001826 "Bad deallocator", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001827
Anton Yartsev05789592013-03-28 17:05:19 +00001828 SmallString<100> buf;
1829 llvm::raw_svector_ostream os(buf);
1830
1831 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1832 SmallString<20> AllocBuf;
1833 llvm::raw_svector_ostream AllocOs(AllocBuf);
1834 SmallString<20> DeallocBuf;
1835 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1836
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001837 if (OwnershipTransferred) {
1838 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1839 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001840 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001841 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001842
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001843 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001844
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001845 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1846 os << " allocated by " << AllocOs.str();
1847 } else {
1848 os << "Memory";
1849 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1850 os << " allocated by " << AllocOs.str();
1851
1852 os << " should be deallocated by ";
1853 printExpectedDeallocName(os, RS->getAllocationFamily());
1854
1855 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1856 os << ", not " << DeallocOs.str();
1857 }
Anton Yartsev05789592013-03-28 17:05:19 +00001858
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001859 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001860 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001861 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001862 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001863 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001864 }
1865}
1866
Anna Zaksc89ad072013-02-07 23:05:47 +00001867void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001868 SourceRange Range, const Expr *DeallocExpr,
1869 const Expr *AllocExpr) const {
1870
Anton Yartsev05789592013-03-28 17:05:19 +00001871
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001872 if (!ChecksEnabled[CK_MallocChecker] &&
1873 !ChecksEnabled[CK_NewDeleteChecker])
1874 return;
1875
1876 Optional<MallocChecker::CheckKind> CheckKind =
1877 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001878 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001879 return;
1880
Devin Coughline39bd402015-09-16 22:03:05 +00001881 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001882 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001883 return;
1884
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001885 if (!BT_OffsetFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001886 BT_OffsetFree[*CheckKind].reset(new BugType(
1887 CheckNames[*CheckKind], "Offset free", categories::MemoryError));
Anna Zaksc89ad072013-02-07 23:05:47 +00001888
1889 SmallString<100> buf;
1890 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001891 SmallString<20> AllocNameBuf;
1892 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001893
1894 const MemRegion *MR = ArgVal.getAsRegion();
1895 assert(MR && "Only MemRegion based symbols can have offset free errors");
1896
1897 RegionOffset Offset = MR->getAsOffset();
1898 assert((Offset.isValid() &&
1899 !Offset.hasSymbolicOffset() &&
1900 Offset.getOffset() != 0) &&
1901 "Only symbols with a valid offset can have offset free errors");
1902
1903 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1904
Anton Yartsev05789592013-03-28 17:05:19 +00001905 os << "Argument to ";
1906 if (!printAllocDeallocName(os, C, DeallocExpr))
1907 os << "deallocator";
1908 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001909 << offsetBytes
1910 << " "
1911 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001912 << " from the start of ";
1913 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1914 os << "memory allocated by " << AllocNameOs.str();
1915 else
1916 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001917
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001918 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001919 R->markInteresting(MR->getBaseRegion());
1920 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001921 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001922}
1923
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001924void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1925 SymbolRef Sym) const {
1926
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001927 if (!ChecksEnabled[CK_MallocChecker] &&
1928 !ChecksEnabled[CK_NewDeleteChecker])
1929 return;
1930
1931 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001932 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001933 return;
1934
Devin Coughline39bd402015-09-16 22:03:05 +00001935 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001936 if (!BT_UseFree[*CheckKind])
1937 BT_UseFree[*CheckKind].reset(new BugType(
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001938 CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001939
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001940 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1941 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001942
1943 R->markInteresting(Sym);
1944 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001945 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001946 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001947 }
1948}
1949
1950void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001951 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001952 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001953
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001954 if (!ChecksEnabled[CK_MallocChecker] &&
1955 !ChecksEnabled[CK_NewDeleteChecker])
1956 return;
1957
1958 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001959 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001960 return;
1961
Devin Coughline39bd402015-09-16 22:03:05 +00001962 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001963 if (!BT_DoubleFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001964 BT_DoubleFree[*CheckKind].reset(new BugType(
1965 CheckNames[*CheckKind], "Double free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001966
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001967 auto R = llvm::make_unique<BugReport>(
1968 *BT_DoubleFree[*CheckKind],
1969 (Released ? "Attempt to free released memory"
1970 : "Attempt to free non-owned memory"),
1971 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001972 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001973 R->markInteresting(Sym);
1974 if (PrevSym)
1975 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001976 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001977 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001978 }
1979}
1980
Jordan Rose656fdd52014-01-08 18:46:55 +00001981void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1982
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001983 if (!ChecksEnabled[CK_NewDeleteChecker])
1984 return;
1985
1986 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001987 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001988 return;
1989
Devin Coughline39bd402015-09-16 22:03:05 +00001990 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00001991 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001992 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001993 "Double delete",
1994 categories::MemoryError));
Jordan Rose656fdd52014-01-08 18:46:55 +00001995
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001996 auto R = llvm::make_unique<BugReport>(
1997 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00001998
1999 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002000 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002001 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00002002 }
2003}
2004
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002005void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2006 SourceRange Range,
2007 SymbolRef Sym) const {
2008
2009 if (!ChecksEnabled[CK_MallocChecker] &&
2010 !ChecksEnabled[CK_NewDeleteChecker])
2011 return;
2012
2013 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2014
2015 if (!CheckKind.hasValue())
2016 return;
2017
Devin Coughline39bd402015-09-16 22:03:05 +00002018 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002019 if (!BT_UseZerroAllocated[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002020 BT_UseZerroAllocated[*CheckKind].reset(
2021 new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2022 categories::MemoryError));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002023
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002024 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2025 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002026
2027 R->addRange(Range);
2028 if (Sym) {
2029 R->markInteresting(Sym);
2030 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2031 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002032 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002033 }
2034}
2035
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002036void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2037 SourceRange Range,
2038 const Expr *FreeExpr) const {
2039 if (!ChecksEnabled[CK_MallocChecker])
2040 return;
2041
2042 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2043 if (!CheckKind.hasValue())
2044 return;
2045
2046 if (ExplodedNode *N = C.generateErrorNode()) {
2047 if (!BT_BadFree[*CheckKind])
2048 BT_BadFree[*CheckKind].reset(
2049 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
2050
2051 SmallString<100> Buf;
2052 llvm::raw_svector_ostream Os(Buf);
2053
2054 const MemRegion *MR = ArgVal.getAsRegion();
2055 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2056 MR = ER->getSuperRegion();
2057
2058 Os << "Argument to ";
2059 if (!printAllocDeallocName(Os, C, FreeExpr))
2060 Os << "deallocator";
2061
2062 Os << " is a function pointer";
2063
2064 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2065 R->markInteresting(MR);
2066 R->addRange(Range);
2067 C.emitReport(std::move(R));
2068 }
2069}
2070
Leslie Zhaie3986c52017-04-26 05:33:14 +00002071ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2072 const CallExpr *CE,
2073 bool FreesOnFail,
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002074 ProgramStateRef State,
Leslie Zhaie3986c52017-04-26 05:33:14 +00002075 bool SuffixWithN) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002076 if (!State)
2077 return nullptr;
2078
Leslie Zhaie3986c52017-04-26 05:33:14 +00002079 if (SuffixWithN && CE->getNumArgs() < 3)
2080 return nullptr;
2081 else if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002082 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002083
Ted Kremenek90af9092010-12-02 07:49:45 +00002084 const Expr *arg0Expr = CE->getArg(0);
George Karpenkovd703ec92018-01-17 20:27:29 +00002085 SVal Arg0Val = C.getSVal(arg0Expr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00002086 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002087 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00002088 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002089
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002090 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002091
Ted Kremenek90af9092010-12-02 07:49:45 +00002092 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002093 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002094
Leslie Zhaie3986c52017-04-26 05:33:14 +00002095 // Get the size argument.
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002096 const Expr *Arg1 = CE->getArg(1);
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002097
2098 // Get the value of the size argument.
George Karpenkovd703ec92018-01-17 20:27:29 +00002099 SVal TotalSize = C.getSVal(Arg1);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002100 if (SuffixWithN)
2101 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2102 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002103 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002104
2105 // Compare the size argument to 0.
2106 DefinedOrUnknownSVal SizeZero =
Leslie Zhaie3986c52017-04-26 05:33:14 +00002107 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002108 svalBuilder.makeIntValWithPtrWidth(0, false));
2109
Anna Zaksd56c8792012-02-13 18:05:39 +00002110 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002111 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00002112 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002113 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00002114 // We only assume exceptional states if they are definitely true; if the
2115 // state is under-constrained, assume regular realloc behavior.
2116 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2117 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2118
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002119 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002120 // malloc(size).
Leslie Zhaie3986c52017-04-26 05:33:14 +00002121 if (PrtIsNull && !SizeIsZero) {
2122 ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002123 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002124 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002125 }
2126
Anna Zaksd56c8792012-02-13 18:05:39 +00002127 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00002128 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002129
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002130 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00002131 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002132 SymbolRef FromPtr = arg0Val.getAsSymbol();
George Karpenkovd703ec92018-01-17 20:27:29 +00002133 SVal RetVal = C.getSVal(CE);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002134 SymbolRef ToPtr = RetVal.getAsSymbol();
2135 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00002136 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00002137
Anna Zaksfe6eb672012-08-24 02:28:20 +00002138 bool ReleasedAllocated = false;
2139
Anna Zaksd56c8792012-02-13 18:05:39 +00002140 // If the size is 0, free the memory.
2141 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00002142 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2143 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00002144 // The semantics of the return value are:
2145 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00002146 // to free() is returned. We just free the input pointer and do not add
2147 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00002148 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00002149 }
2150
2151 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00002152 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002153 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00002154
Leslie Zhaie3986c52017-04-26 05:33:14 +00002155 ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002156 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002157 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00002158 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00002159
Anna Zaks75cfbb62012-09-12 22:57:34 +00002160 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2161 if (FreesOnFail)
2162 Kind = RPIsFreeOnFailure;
2163 else if (!ReleasedAllocated)
2164 Kind = RPDoNotTrackAfterFailure;
2165
Anna Zaksfe6eb672012-08-24 02:28:20 +00002166 // Record the info about the reallocated symbol so that we could properly
2167 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00002168 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00002169 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00002170 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00002171 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002172 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002173 }
Craig Topper0dbb7832014-05-27 02:45:47 +00002174 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00002175}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002176
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002177ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002178 ProgramStateRef State) {
2179 if (!State)
2180 return nullptr;
2181
Anna Zaksb508d292012-04-10 23:41:11 +00002182 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002183 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002184
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002185 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek90af9092010-12-02 07:49:45 +00002186 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002187 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002188
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002189 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002190}
2191
Anna Zaksfc2e1532012-03-21 19:45:08 +00002192LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002193MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2194 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002195 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002196 // Walk the ExplodedGraph backwards and find the first node that referred to
2197 // the tracked symbol.
2198 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002199 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002200
2201 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002202 ProgramStateRef State = N->getState();
2203 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002204 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002205
2206 // Find the most recent expression bound to the symbol in the current
2207 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002208 if (!ReferenceRegion) {
2209 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2210 SVal Val = State->getSVal(MR);
2211 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002212 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002213 // Do not show local variables belonging to a function other than
2214 // where the error is reported.
2215 if (!VR ||
2216 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2217 ReferenceRegion = MR;
2218 }
2219 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002220 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002221
Anna Zaks486a0ff2015-02-05 01:02:53 +00002222 // Allocation node, is the last node in the current or parent context in
2223 // which the symbol was tracked.
2224 const LocationContext *NContext = N->getLocationContext();
2225 if (NContext == LeakContext ||
2226 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002227 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002228 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002229 }
2230
Anna Zaksa043d0c2013-01-08 00:25:29 +00002231 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002232}
2233
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002234void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2235 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002236
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002237 if (!ChecksEnabled[CK_MallocChecker] &&
2238 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002239 return;
2240
Anton Yartsev9907fc92015-03-04 23:18:21 +00002241 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002242 assert(RS && "cannot leak an untracked symbol");
2243 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002244
2245 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002246 return;
2247
Anton Yartsev2487dd62015-03-10 22:24:21 +00002248 Optional<MallocChecker::CheckKind>
2249 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002250
Anton Yartsev2487dd62015-03-10 22:24:21 +00002251 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002252 return;
2253
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002254 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002255 if (!BT_Leak[*CheckKind]) {
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002256 BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2257 categories::MemoryError));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002258 // Leaks should not be reported if they are post-dominated by a sink:
2259 // (1) Sinks are higher importance bugs.
2260 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2261 // with __noreturn functions such as assert() or exit(). We choose not
2262 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002263 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002264 }
2265
Anna Zaksdf901a42012-02-23 21:38:21 +00002266 // Most bug reports are cached at the location where they occurred.
2267 // With leaks, we want to unique them by the location where they were
2268 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002269 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002270 const ExplodedNode *AllocNode = nullptr;
2271 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002272 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002273
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002274 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
Anton Yartsev6e499252013-04-05 02:25:02 +00002275 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002276 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2277 C.getSourceManager(),
2278 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002279
Anna Zaksfc2e1532012-03-21 19:45:08 +00002280 SmallString<200> buf;
2281 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002282 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002283 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002284 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002285 } else {
2286 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002287 }
2288
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002289 auto R = llvm::make_unique<BugReport>(
2290 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2291 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002292 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002293 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002294 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002295}
2296
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002297void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2298 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002299{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002300 if (!SymReaper.hasDeadSymbols())
2301 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002302
Ted Kremenek49b1e382012-01-26 21:29:00 +00002303 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002304 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002305 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002306
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002307 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002308 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2309 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002310 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002311 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002312 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002313 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002314
Zhongxing Xuc7460962009-11-13 07:48:11 +00002315 }
2316 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002317
Anna Zaksd56c8792012-02-13 18:05:39 +00002318 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002319 ReallocPairsTy RP = state->get<ReallocPairs>();
2320 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002321 if (SymReaper.isDead(I->first) ||
2322 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002323 state = state->remove<ReallocPairs>(I->first);
2324 }
2325 }
2326
Anna Zaks67291b92012-11-13 03:18:01 +00002327 // Cleanup the FreeReturnValue Map.
2328 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2329 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2330 if (SymReaper.isDead(I->first) ||
2331 SymReaper.isDead(I->second)) {
2332 state = state->remove<FreeReturnValue>(I->first);
2333 }
2334 }
2335
Anna Zaksdf901a42012-02-23 21:38:21 +00002336 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002337 ExplodedNode *N = C.getPredecessor();
2338 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002339 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002340 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2341 if (N) {
2342 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002343 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002344 reportLeak(*I, N, C);
2345 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002346 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002347 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002348
Anna Zaksdf901a42012-02-23 21:38:21 +00002349 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002350}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002351
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002352void MallocChecker::checkPreCall(const CallEvent &Call,
2353 CheckerContext &C) const {
2354
Jordan Rose656fdd52014-01-08 18:46:55 +00002355 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2356 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2357 if (!Sym || checkDoubleDelete(Sym, C))
2358 return;
2359 }
2360
Anna Zaks46d01602012-05-18 01:16:10 +00002361 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002362 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2363 const FunctionDecl *FD = FC->getDecl();
2364 if (!FD)
2365 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002366
Anna Zaksd79b8402014-10-03 21:48:59 +00002367 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002368 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002369 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2370 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2371 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002372 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002373
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002374 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002375 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002376 return;
2377 }
2378
2379 // Check if the callee of a method is deleted.
2380 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2381 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2382 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2383 return;
2384 }
2385
2386 // Check arguments for being used after free.
2387 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2388 SVal ArgSVal = Call.getArgSVal(I);
2389 if (ArgSVal.getAs<Loc>()) {
2390 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002391 if (!Sym)
2392 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002393 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002394 return;
2395 }
2396 }
2397}
2398
Anna Zaksa1b227b2012-02-08 23:16:56 +00002399void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2400 const Expr *E = S->getRetValue();
2401 if (!E)
2402 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002403
2404 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002405 ProgramStateRef State = C.getState();
George Karpenkovd703ec92018-01-17 20:27:29 +00002406 SVal RetVal = C.getSVal(E);
Anna Zaks4ca45b12012-02-22 02:36:01 +00002407 SymbolRef Sym = RetVal.getAsSymbol();
2408 if (!Sym)
2409 // If we are returning a field of the allocated struct or an array element,
2410 // the callee could still free the memory.
2411 // TODO: This logic should be a part of generic symbol escape callback.
2412 if (const MemRegion *MR = RetVal.getAsRegion())
2413 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2414 if (const SymbolicRegion *BMR =
2415 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2416 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002417
Anna Zaks3aa52252012-02-11 21:44:39 +00002418 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002419 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002420 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002421}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002422
Anna Zaks9fe80982012-03-22 00:57:20 +00002423// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002424// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002425// needed.
2426void MallocChecker::checkPostStmt(const BlockExpr *BE,
2427 CheckerContext &C) const {
2428
2429 // Scan the BlockDecRefExprs for any object the retain count checker
2430 // may be tracking.
2431 if (!BE->getBlockDecl()->hasCaptures())
2432 return;
2433
2434 ProgramStateRef state = C.getState();
2435 const BlockDataRegion *R =
George Karpenkovd703ec92018-01-17 20:27:29 +00002436 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
Anna Zaks9fe80982012-03-22 00:57:20 +00002437
2438 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2439 E = R->referenced_vars_end();
2440
2441 if (I == E)
2442 return;
2443
2444 SmallVector<const MemRegion*, 10> Regions;
2445 const LocationContext *LC = C.getLocationContext();
2446 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2447
2448 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002449 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002450 if (VR->getSuperRegion() == R) {
2451 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2452 }
2453 Regions.push_back(VR);
2454 }
2455
2456 state =
2457 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2458 Regions.data() + Regions.size()).getState();
2459 C.addTransition(state);
2460}
2461
Anna Zaks46d01602012-05-18 01:16:10 +00002462bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002463 assert(Sym);
2464 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002465 return (RS && RS->isReleased());
2466}
2467
2468bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2469 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002470
Jordan Rose656fdd52014-01-08 18:46:55 +00002471 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002472 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2473 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002474 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002475
Anna Zaksa1b227b2012-02-08 23:16:56 +00002476 return false;
2477}
2478
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002479void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2480 const Stmt *S) const {
2481 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002482
Devin Coughlin81771732015-09-22 22:47:14 +00002483 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2484 if (RS->isAllocatedOfSizeZero())
2485 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2486 }
2487 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2488 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2489 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002490}
2491
Jordan Rose656fdd52014-01-08 18:46:55 +00002492bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2493
2494 if (isReleased(Sym, C)) {
2495 ReportDoubleDelete(C, Sym);
2496 return true;
2497 }
2498 return false;
2499}
2500
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002501// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002502void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2503 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002504 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002505 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002506 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002507 checkUseZeroAllocated(Sym, C, S);
2508 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002509}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002510
Anna Zaksbb1ef902012-02-11 21:02:35 +00002511// If a symbolic region is assumed to NULL (or another constant), stop tracking
2512// it - assuming that allocation failed on this path.
2513ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2514 SVal Cond,
2515 bool Assumption) const {
2516 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002517 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002518 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002519 ConstraintManager &CMgr = state->getConstraintManager();
2520 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2521 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002522 state = state->remove<RegionState>(I.getKey());
2523 }
2524
Anna Zaksd56c8792012-02-13 18:05:39 +00002525 // Realloc returns 0 when reallocation fails, which means that we should
2526 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002527 ReallocPairsTy RP = state->get<ReallocPairs>();
2528 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002529 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002530 ConstraintManager &CMgr = state->getConstraintManager();
2531 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002532 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002533 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002534
Anna Zaks75cfbb62012-09-12 22:57:34 +00002535 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2536 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2537 if (RS->isReleased()) {
2538 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002539 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002540 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002541 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2542 state = state->remove<RegionState>(ReallocSym);
2543 else
2544 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002545 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002546 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002547 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002548 }
2549
Anna Zaksbb1ef902012-02-11 21:02:35 +00002550 return state;
2551}
2552
Anna Zaks8ebeb642013-06-08 00:29:29 +00002553bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002554 const CallEvent *Call,
2555 ProgramStateRef State,
2556 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002557 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002558 EscapingSymbol = nullptr;
2559
Jordan Rose2a833ca2014-01-15 17:25:15 +00002560 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002561 // TODO: If we want to be more optimistic here, we'll need to make sure that
2562 // regions escape to C++ containers. They seem to do that even now, but for
2563 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002564 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002565 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002566
Jordan Rose742920c2012-07-02 19:27:35 +00002567 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002568 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002569 // If it's not a framework call, or if it takes a callback, assume it
2570 // can free memory.
Anna Zaksfe1eca52015-10-27 20:19:45 +00002571 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002572 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002573
Jordan Rose613f3c02013-03-09 00:59:10 +00002574 // If it's a method we know about, handle it explicitly post-call.
2575 // This should happen before the "freeWhenDone" check below.
2576 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002577 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002578
Jordan Rose613f3c02013-03-09 00:59:10 +00002579 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2580 // about, we can't be sure that the object will use free() to deallocate the
2581 // memory, so we can't model it explicitly. The best we can do is use it to
2582 // decide whether the pointer escapes.
2583 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002584 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002585
Jordan Rose613f3c02013-03-09 00:59:10 +00002586 // If the first selector piece ends with "NoCopy", and there is no
2587 // "freeWhenDone" parameter set to zero, we know ownership is being
2588 // transferred. Again, though, we can't be sure that the object will use
2589 // free() to deallocate the memory, so we can't model it explicitly.
2590 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002591 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002592 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002593
Anna Zaks42908c72012-06-19 05:10:32 +00002594 // If the first selector starts with addPointer, insertPointer,
2595 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2596 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002597 // that the pointers get freed by following the container itself.
2598 if (FirstSlot.startswith("addPointer") ||
2599 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002600 FirstSlot.startswith("replacePointer") ||
2601 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002602 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002603 }
2604
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002605 // We should escape receiver on call to 'init'. This is especially relevant
2606 // to the receiver, as the corresponding symbol is usually not referenced
2607 // after the call.
2608 if (Msg->getMethodFamily() == OMF_init) {
2609 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2610 return true;
2611 }
Anna Zaks737926b2013-05-31 22:39:13 +00002612
Jordan Rose742920c2012-07-02 19:27:35 +00002613 // Otherwise, assume that the method does not free memory.
2614 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002615 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002616 }
2617
Jordan Rose742920c2012-07-02 19:27:35 +00002618 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002619 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002620 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002621 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002622
Jordan Rose742920c2012-07-02 19:27:35 +00002623 ASTContext &ASTC = State->getStateManager().getContext();
2624
2625 // If it's one of the allocation functions we can reason about, we model
2626 // its behavior explicitly.
2627 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002628 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002629
2630 // If it's not a system call, assume it frees memory.
2631 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002632 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002633
2634 // White list the system functions whose arguments escape.
2635 const IdentifierInfo *II = FD->getIdentifier();
2636 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002637 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002638 StringRef FName = II->getName();
2639
Jordan Rose742920c2012-07-02 19:27:35 +00002640 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002641 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002642 if (FName.endswith("NoCopy")) {
2643 // Look for the deallocator argument. We know that the memory ownership
2644 // is not transferred only if the deallocator argument is
2645 // 'kCFAllocatorNull'.
2646 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2647 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2648 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2649 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2650 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002651 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002652 }
2653 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002654 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002655 }
2656
Jordan Rose742920c2012-07-02 19:27:35 +00002657 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002658 // 'closefn' is specified (and if that function does free memory),
2659 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002660 // Currently, we do not inspect the 'closefn' function (PR12101).
2661 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002662 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002663 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002664
2665 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2666 // these leaks might be intentional when setting the buffer for stdio.
2667 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2668 if (FName == "setbuf" || FName =="setbuffer" ||
2669 FName == "setlinebuf" || FName == "setvbuf") {
2670 if (Call->getNumArgs() >= 1) {
2671 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2672 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2673 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2674 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002675 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002676 }
2677 }
2678
2679 // A bunch of other functions which either take ownership of a pointer or
2680 // wrap the result up in a struct or object, meaning it can be freed later.
2681 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2682 // but the Malloc checker cannot differentiate between them. The right way
2683 // of doing this would be to implement a pointer escapes callback.
2684 if (FName == "CGBitmapContextCreate" ||
2685 FName == "CGBitmapContextCreateWithData" ||
2686 FName == "CVPixelBufferCreateWithBytes" ||
2687 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2688 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002689 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002690 }
2691
Anna Zaks03f48332016-01-06 00:32:56 +00002692 if (FName == "postEvent" &&
2693 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2694 return true;
2695 }
2696
2697 if (FName == "postEvent" &&
2698 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2699 return true;
2700 }
2701
Artem Dergachev85c92112016-12-16 12:21:55 +00002702 if (FName == "connectImpl" &&
2703 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2704 return true;
2705 }
2706
Jordan Rose7ab01822012-07-02 19:27:51 +00002707 // Handle cases where we know a buffer's /address/ can escape.
2708 // Note that the above checks handle some special cases where we know that
2709 // even though the address escapes, it's still our responsibility to free the
2710 // buffer.
2711 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002712 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002713
2714 // Otherwise, assume that the function does not free memory.
2715 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002716 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002717}
2718
Anna Zaks333481b2013-03-28 23:15:29 +00002719static bool retTrue(const RefState *RS) {
2720 return true;
2721}
2722
2723static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2724 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2725 RS->getAllocationFamily() == AF_CXXNew);
2726}
2727
Anna Zaksdc154152012-12-20 00:38:25 +00002728ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2729 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002730 const CallEvent *Call,
2731 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002732 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2733}
2734
2735ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2736 const InvalidatedSymbols &Escaped,
2737 const CallEvent *Call,
2738 PointerEscapeKind Kind) const {
2739 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2740 &checkIfNewOrNewArrayFamily);
2741}
2742
2743ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2744 const InvalidatedSymbols &Escaped,
2745 const CallEvent *Call,
2746 PointerEscapeKind Kind,
2747 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002748 // If we know that the call does not free memory, or we want to process the
2749 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002750 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002751 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002752 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2753 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002754 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002755 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002756 }
Anna Zaks3d348342012-02-14 21:55:24 +00002757
Anna Zaksdc154152012-12-20 00:38:25 +00002758 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002759 E = Escaped.end();
2760 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002761 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002762
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002763 if (EscapingSymbol && EscapingSymbol != sym)
2764 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002765
Anna Zaks0d6989b2012-06-22 02:04:31 +00002766 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002767 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2768 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002769 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002770 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2771 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002772 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002773 }
Anna Zaks3d348342012-02-14 21:55:24 +00002774 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002775}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002776
Jordy Rosebf38f202012-03-18 07:43:35 +00002777static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2778 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002779 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2780 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002781
Jordan Rose0c153cb2012-11-02 01:54:06 +00002782 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002783 I != E; ++I) {
2784 SymbolRef sym = I.getKey();
2785 if (!currMap.lookup(sym))
2786 return sym;
2787 }
2788
Craig Topper0dbb7832014-05-27 02:45:47 +00002789 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002790}
2791
David Blaikie0a0c2752017-01-05 17:26:53 +00002792std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2793 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2794 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002795 ProgramStateRef state = N->getState();
2796 ProgramStateRef statePrev = PrevN->getState();
2797
2798 const RefState *RS = state->get<RegionState>(Sym);
2799 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002800 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002801 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002802
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002803 const Stmt *S = PathDiagnosticLocation::getStmt(N);
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002804 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002805 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002806
Jordan Rose681cce92012-07-10 22:07:42 +00002807 // FIXME: We will eventually need to handle non-statement-based events
2808 // (__attribute__((cleanup))).
2809
Anna Zaks2b5bb972012-02-09 06:25:51 +00002810 // Find out if this is an interesting point and what is the kind.
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002811 const char *Msg = nullptr;
2812 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002813 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002814 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002815 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002816 StackHint = new StackHintGeneratorForSymbol(Sym,
2817 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002818 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002819 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002820 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002821 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002822 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002823 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002824 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002825 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002826 Mode = ReallocationFailed;
2827 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002828 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002829 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002830
Jordy Rose21ff76e2012-03-24 03:15:09 +00002831 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2832 // Is it possible to fail two reallocs WITHOUT testing in between?
2833 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2834 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002835 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002836 FailedReallocSymbol = sym;
2837 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002838 }
2839
2840 // We are in a special mode if a reallocation failed later in the path.
2841 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002842 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002843
Jordy Rose21ff76e2012-03-24 03:15:09 +00002844 // Is this is the first appearance of the reallocated symbol?
2845 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002846 // We're at the reallocation point.
2847 Msg = "Attempt to reallocate memory";
2848 StackHint = new StackHintGeneratorForSymbol(Sym,
2849 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002850 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002851 Mode = Normal;
2852 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002853 }
2854
Anna Zaks2b5bb972012-02-09 06:25:51 +00002855 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002856 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002857 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002858
2859 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002860 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002861 N->getLocationContext());
David Blaikie0a0c2752017-01-05 17:26:53 +00002862 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002863}
2864
Anna Zaks263b7e02012-05-02 00:05:20 +00002865void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2866 const char *NL, const char *Sep) const {
2867
2868 RegionStateTy RS = State->get<RegionState>();
2869
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002870 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002871 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002872 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002873 const RefState *RefS = State->get<RegionState>(I.getKey());
2874 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002875 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002876 if (!CheckKind.hasValue())
2877 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002878
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002879 I.getKey()->dumpToStream(Out);
2880 Out << " : ";
2881 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002882 if (CheckKind.hasValue())
2883 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002884 Out << NL;
2885 }
2886 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002887}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002888
Anna Zakse4cfcd42013-04-16 00:22:55 +00002889void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2890 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002891 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002892 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2893 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002894 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2895 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2896 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002897 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00002898 // checker.
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00002899 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002900 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00002901 // FIXME: This does not set the correct name, but without this workaround
2902 // no name will be set at all.
2903 checker->CheckNames[MallocChecker::CK_NewDeleteChecker] =
2904 mgr.getCurrentCheckName();
2905 }
Anna Zakse4cfcd42013-04-16 00:22:55 +00002906}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002907
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002908#define REGISTER_CHECKER(name) \
2909 void ento::register##name(CheckerManager &mgr) { \
2910 registerCStringCheckerBasic(mgr); \
2911 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002912 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2913 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002914 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2915 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2916 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002917
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002918REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002919REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002920REGISTER_CHECKER(MismatchedDeallocatorChecker)