blob: 378728dc6131017d9aefca090d9b0d2853d6ab24 [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>,
Artem Dergachev13b20262018-01-17 23:46:13 +0000165 check::NewAllocator,
Anton Yartsev13df0362013-03-25 01:35:45 +0000166 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000167 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000168 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000169 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000170 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000171{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000172public:
Craig Topper0dbb7832014-05-27 02:45:47 +0000173 MallocChecker()
Anna Zaks30d46682016-03-08 01:21:51 +0000174 : II_alloca(nullptr), II_win_alloca(nullptr), II_malloc(nullptr),
175 II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
176 II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
177 II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr),
178 II_if_nameindex(nullptr), II_if_freenameindex(nullptr),
Anna Zaksbbec97c2017-03-09 00:01:01 +0000179 II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr),
180 II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr),
181 II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr),
Leslie Zhaie3986c52017-04-26 05:33:14 +0000182 II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr),
183 II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr),
184 II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr),
185 II_g_try_realloc_n(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000186
187 /// In pessimistic mode, the checker assumes that it does not know which
188 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000189 enum CheckKind {
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000190 CK_MallocChecker,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000191 CK_NewDeleteChecker,
192 CK_NewDeleteLeaksChecker,
193 CK_MismatchedDeallocatorChecker,
194 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000195 };
196
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000197 enum class MemoryOperationKind {
Anna Zaksd79b8402014-10-03 21:48:59 +0000198 MOK_Allocate,
199 MOK_Free,
200 MOK_Any
201 };
202
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000203 DefaultBool IsOptimistic;
204
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000205 DefaultBool ChecksEnabled[CK_NumCheckKinds];
206 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000207
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000208 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000209 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000210 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
Artem Dergachev13b20262018-01-17 23:46:13 +0000211 void checkNewAllocator(const CXXNewExpr *NE, SVal Target,
212 CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000213 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000214 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000215 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000216 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000217 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000218 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000219 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000220 void checkLocation(SVal l, bool isLoad, const Stmt *S,
221 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000222
223 ProgramStateRef checkPointerEscape(ProgramStateRef State,
224 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000225 const CallEvent *Call,
226 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000227 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
228 const InvalidatedSymbols &Escaped,
229 const CallEvent *Call,
230 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000231
Anna Zaks263b7e02012-05-02 00:05:20 +0000232 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000233 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000234
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000235private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000236 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
237 mutable std::unique_ptr<BugType> BT_DoubleDelete;
238 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
239 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
240 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000241 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000242 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
243 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000244 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
Anna Zaks30d46682016-03-08 01:21:51 +0000245 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
246 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
247 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
248 *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
Anna Zaksbbec97c2017-03-09 00:01:01 +0000249 *II_win_wcsdup, *II_g_malloc, *II_g_malloc0,
250 *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0,
Leslie Zhaie3986c52017-04-26 05:33:14 +0000251 *II_g_try_realloc, *II_g_free, *II_g_memdup,
252 *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n,
253 *II_g_try_malloc_n, *II_g_try_malloc0_n,
254 *II_g_try_realloc_n;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000255 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000256
Anna Zaks3d348342012-02-14 21:55:24 +0000257 void initIdentifierInfo(ASTContext &C) const;
258
Anton Yartsev05789592013-03-28 17:05:19 +0000259 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000260 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000261
262 /// \brief Print names of allocators and deallocators.
263 ///
264 /// \returns true on success.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000265 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000266 const Expr *E) const;
267
268 /// \brief Print expected name of an allocator based on the deallocator's
269 /// family derived from the DeallocExpr.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000270 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000271 const Expr *DeallocExpr) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000272 /// \brief Print expected name of a deallocator based on the allocator's
Anton Yartsev05789592013-03-28 17:05:19 +0000273 /// family.
274 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
275
Jordan Rose613f3c02013-03-09 00:59:10 +0000276 ///@{
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000277 /// Check if this is one of the functions which can allocate/reallocate memory
Anna Zaks3d348342012-02-14 21:55:24 +0000278 /// pointed to by one of its arguments.
279 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000280 bool isCMemFunction(const FunctionDecl *FD,
281 ASTContext &C,
282 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000283 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000284 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000285 ///@}
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000286
Artem Dergachev13b20262018-01-17 23:46:13 +0000287 /// \brief Process C++ operator new()'s allocation, which is the part of C++
288 /// new-expression that goes before the constructor.
289 void processNewAllocation(const CXXNewExpr *NE, CheckerContext &C,
290 SVal Target) const;
291
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000292 /// \brief Perform a zero-allocation check.
Artem Dergachev13b20262018-01-17 23:46:13 +0000293 /// The optional \p RetVal parameter specifies the newly allocated pointer
294 /// value; if unspecified, the value of expression \p E is used.
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000295 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
296 const unsigned AllocationSizeArg,
Artem Dergachev13b20262018-01-17 23:46:13 +0000297 ProgramStateRef State,
298 Optional<SVal> RetVal = None) const;
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000299
Richard Smith852e9ce2013-11-27 01:46:48 +0000300 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
301 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000302 const OwnershipAttr* Att,
303 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000304 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000305 const Expr *SizeEx, SVal Init,
306 ProgramStateRef State,
307 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000308 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000309 SVal SizeEx, SVal Init,
310 ProgramStateRef State,
311 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000312
Gabor Horvath73040272016-09-19 20:39:52 +0000313 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
Artem Dergachev13b20262018-01-17 23:46:13 +0000314 ProgramStateRef State, SVal Target);
Gabor Horvath73040272016-09-19 20:39:52 +0000315
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000316 // Check if this malloc() for special flags. At present that means M_ZERO or
317 // __GFP_ZERO (in which case, treat it like calloc).
318 llvm::Optional<ProgramStateRef>
319 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
320 const ProgramStateRef &State) const;
321
Anna Zaks40a7eb32012-02-22 19:24:52 +0000322 /// Update the RefState to reflect the new memory allocation.
Artem Dergachev13b20262018-01-17 23:46:13 +0000323 /// The optional \p RetVal parameter specifies the newly allocated pointer
324 /// value; if unspecified, the value of expression \p E is used.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000325 static ProgramStateRef
Anton Yartsev05789592013-03-28 17:05:19 +0000326 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
Artem Dergachev13b20262018-01-17 23:46:13 +0000327 AllocationFamily Family = AF_Malloc,
328 Optional<SVal> RetVal = None);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000329
330 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000331 const OwnershipAttr* Att,
332 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000333 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000334 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000335 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000336 bool &ReleasedAllocated,
337 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000338 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
339 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000340 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000341 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000342 bool &ReleasedAllocated,
343 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000344
Leslie Zhaie3986c52017-04-26 05:33:14 +0000345 ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE,
346 bool FreesMemOnFailure,
347 ProgramStateRef State,
348 bool SuffixWithN = false) const;
349 static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
350 const Expr *BlockBytes);
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000351 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
352 ProgramStateRef State);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000353
Anna Zaks46d01602012-05-18 01:16:10 +0000354 ///\brief Check if the memory associated with this symbol was released.
355 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
356
Anton Yartsev13df0362013-03-25 01:35:45 +0000357 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000358
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000359 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000360 const Stmt *S) const;
361
Jordan Rose656fdd52014-01-08 18:46:55 +0000362 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
363
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000364 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000365 /// "interesting" and should be modeled explicitly.
366 ///
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000367 /// \param [out] EscapingSymbol A function might not free memory in general,
Anna Zaks8ebeb642013-06-08 00:29:29 +0000368 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000369 /// returned and the single escaping symbol is returned through the out
370 /// parameter.
371 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000372 /// We assume that pointers do not escape through calls to system functions
373 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000374 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000375 ProgramStateRef State,
376 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000377
Anna Zaks333481b2013-03-28 23:15:29 +0000378 // Implementation of the checkPointerEscape callabcks.
379 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
380 const InvalidatedSymbols &Escaped,
381 const CallEvent *Call,
382 PointerEscapeKind Kind,
383 bool(*CheckRefState)(const RefState*)) const;
384
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000385 ///@{
386 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000387 /// Sets CheckKind to the kind of the checker responsible for this
388 /// family/call/symbol.
Anton Yartsev2487dd62015-03-10 22:24:21 +0000389 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
390 bool IsALeakCheck = false) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000391 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000392 const Stmt *AllocDeallocStmt,
393 bool IsALeakCheck = false) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000394 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000395 bool IsALeakCheck = false) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000396 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000397 static bool SummarizeValue(raw_ostream &os, SVal V);
398 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000399 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +0000400 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000401 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
402 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000403 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000404 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000405 SymbolRef Sym, bool OwnershipTransferred) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000406 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
407 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000408 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000409 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
410 SymbolRef Sym) const;
411 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000412 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000413
Jordan Rose656fdd52014-01-08 18:46:55 +0000414 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
415
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000416 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
417 SymbolRef Sym) const;
418
Daniel Marjamakia43a8f52017-05-02 11:46:12 +0000419 void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
420 SourceRange Range, const Expr *FreeExpr) const;
421
Anna Zaksdf901a42012-02-23 21:38:21 +0000422 /// Find the location of the allocation for Sym on the path leading to the
423 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000424 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
425 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000426
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000427 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
428
Anna Zaks2b5bb972012-02-09 06:25:51 +0000429 /// The bug visitor which allows us to print extra diagnostics along the
430 /// BugReport path. For example, showing the allocation site of the leaked
431 /// region.
David Blaikie6951e3e2015-08-13 22:58:37 +0000432 class MallocBugVisitor final
433 : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000434 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000435 enum NotificationMode {
436 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000437 ReallocationFailed
438 };
439
Anna Zaks2b5bb972012-02-09 06:25:51 +0000440 // The allocated region symbol tracked by the main analysis.
441 SymbolRef Sym;
442
Anna Zaks62cce9e2012-05-10 01:37:40 +0000443 // The mode we are in, i.e. what kind of diagnostics will be emitted.
444 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000445
Anna Zaks62cce9e2012-05-10 01:37:40 +0000446 // A symbol from when the primary region should have been reallocated.
447 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000448
Anna Zaks62cce9e2012-05-10 01:37:40 +0000449 bool IsLeak;
450
451 public:
452 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000453 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000454
Craig Topperfb6b25b2014-03-15 04:29:04 +0000455 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000456 static int X = 0;
457 ID.AddPointer(&X);
458 ID.AddPointer(Sym);
459 }
460
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000461 inline bool isAllocated(const RefState *S, const RefState *SPrev,
462 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000463 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000464 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000465 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
466 (!SPrev || !(SPrev->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000467 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000468 }
469
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000470 inline bool isReleased(const RefState *S, const RefState *SPrev,
471 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000472 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000473 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000474 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
475 }
476
Anna Zaks0d6989b2012-06-22 02:04:31 +0000477 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
478 const Stmt *Stmt) {
479 // Did not track -> relinquished. Other state (allocated) -> relinquished.
480 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
481 isa<ObjCPropertyRefExpr>(Stmt)) &&
482 (S && S->isRelinquished()) &&
483 (!SPrev || !SPrev->isRelinquished()));
484 }
485
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000486 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
487 const Stmt *Stmt) {
488 // If the expression is not a call, and the state change is
489 // released -> allocated, it must be the realloc return value
490 // check. If we have to handle more cases here, it might be cleaner just
491 // to track this extra bit in the state itself.
492 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000493 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
494 (SPrev && !(SPrev->isAllocated() ||
495 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000496 }
497
David Blaikie0a0c2752017-01-05 17:26:53 +0000498 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
499 const ExplodedNode *PrevN,
500 BugReporterContext &BRC,
501 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000502
David Blaikied15481c2014-08-29 18:18:43 +0000503 std::unique_ptr<PathDiagnosticPiece>
504 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
505 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000506 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000507 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000508
509 PathDiagnosticLocation L =
510 PathDiagnosticLocation::createEndOfPath(EndPathNode,
511 BRC.getSourceManager());
512 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000513 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
514 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000515 }
516
Anna Zakscba4f292012-03-16 23:24:20 +0000517 private:
518 class StackHintGeneratorForReallocationFailed
519 : public StackHintGeneratorForSymbol {
520 public:
521 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
522 : StackHintGeneratorForSymbol(S, M) {}
523
Craig Topperfb6b25b2014-03-15 04:29:04 +0000524 std::string getMessageForArg(const Expr *ArgE,
525 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000526 // Printed parameters start at 1, not 0.
527 ++ArgIndex;
528
Anna Zakscba4f292012-03-16 23:24:20 +0000529 SmallString<200> buf;
530 llvm::raw_svector_ostream os(buf);
531
Jordan Rosec102b352012-09-22 01:24:42 +0000532 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
533 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000534
535 return os.str();
536 }
537
Craig Topperfb6b25b2014-03-15 04:29:04 +0000538 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000539 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000540 }
541 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000542 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000543};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000544} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000545
Jordan Rose0c153cb2012-11-02 01:54:06 +0000546REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
547REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Devin Coughlin81771732015-09-22 22:47:14 +0000548REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000549
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000550// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000551// the free function.
552REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
553
Anna Zaksbb1ef902012-02-11 21:02:35 +0000554namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000555class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000556 ProgramStateRef state;
557public:
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000558 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
Anna Zaksbb1ef902012-02-11 21:02:35 +0000559 ProgramStateRef getState() const { return state; }
560
Craig Topperfb6b25b2014-03-15 04:29:04 +0000561 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000562 state = state->remove<RegionState>(sym);
563 return true;
564 }
565};
566} // end anonymous namespace
567
Anna Zaks3d348342012-02-14 21:55:24 +0000568void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000569 if (II_malloc)
570 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000571 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000572 II_malloc = &Ctx.Idents.get("malloc");
573 II_free = &Ctx.Idents.get("free");
574 II_realloc = &Ctx.Idents.get("realloc");
575 II_reallocf = &Ctx.Idents.get("reallocf");
576 II_calloc = &Ctx.Idents.get("calloc");
577 II_valloc = &Ctx.Idents.get("valloc");
578 II_strdup = &Ctx.Idents.get("strdup");
579 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaks30d46682016-03-08 01:21:51 +0000580 II_wcsdup = &Ctx.Idents.get("wcsdup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000581 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000582 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
583 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaks30d46682016-03-08 01:21:51 +0000584
585 //MSVC uses `_`-prefixed instead, so we check for them too.
586 II_win_strdup = &Ctx.Idents.get("_strdup");
587 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
588 II_win_alloca = &Ctx.Idents.get("_alloca");
Anna Zaksbbec97c2017-03-09 00:01:01 +0000589
590 // Glib
591 II_g_malloc = &Ctx.Idents.get("g_malloc");
592 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
593 II_g_realloc = &Ctx.Idents.get("g_realloc");
594 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
595 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
596 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
597 II_g_free = &Ctx.Idents.get("g_free");
598 II_g_memdup = &Ctx.Idents.get("g_memdup");
Leslie Zhaie3986c52017-04-26 05:33:14 +0000599 II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
600 II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
601 II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
602 II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
603 II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
604 II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000605}
606
Anna Zaks3d348342012-02-14 21:55:24 +0000607bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000608 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000609 return true;
610
Anna Zaksd79b8402014-10-03 21:48:59 +0000611 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000612 return true;
613
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000614 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
615 return true;
616
Anton Yartsev13df0362013-03-25 01:35:45 +0000617 if (isStandardNewDelete(FD, C))
618 return true;
619
Anna Zaks46d01602012-05-18 01:16:10 +0000620 return false;
621}
622
Anna Zaksd79b8402014-10-03 21:48:59 +0000623bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
624 ASTContext &C,
625 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000626 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000627 if (!FD)
628 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000629
Anna Zaksd79b8402014-10-03 21:48:59 +0000630 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
631 MemKind == MemoryOperationKind::MOK_Free);
632 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
633 MemKind == MemoryOperationKind::MOK_Allocate);
634
Jordan Rose6cd16c52012-07-10 23:13:01 +0000635 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000636 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000637 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000638
Anna Zaksd79b8402014-10-03 21:48:59 +0000639 if (Family == AF_Malloc && CheckFree) {
Anna Zaksbbec97c2017-03-09 00:01:01 +0000640 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
641 FunI == II_g_free)
Anna Zaksd79b8402014-10-03 21:48:59 +0000642 return true;
643 }
644
645 if (Family == AF_Malloc && CheckAlloc) {
646 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
647 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
Anna Zaks30d46682016-03-08 01:21:51 +0000648 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
Anna Zaksbbec97c2017-03-09 00:01:01 +0000649 FunI == II_win_wcsdup || FunI == II_kmalloc ||
650 FunI == II_g_malloc || FunI == II_g_malloc0 ||
651 FunI == II_g_realloc || FunI == II_g_try_malloc ||
652 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
Leslie Zhaie3986c52017-04-26 05:33:14 +0000653 FunI == II_g_memdup || FunI == II_g_malloc_n ||
654 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
655 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
656 FunI == II_g_try_realloc_n)
Anna Zaksd79b8402014-10-03 21:48:59 +0000657 return true;
658 }
659
660 if (Family == AF_IfNameIndex && CheckFree) {
661 if (FunI == II_if_freenameindex)
662 return true;
663 }
664
665 if (Family == AF_IfNameIndex && CheckAlloc) {
666 if (FunI == II_if_nameindex)
667 return true;
668 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000669
670 if (Family == AF_Alloca && CheckAlloc) {
Anna Zaks30d46682016-03-08 01:21:51 +0000671 if (FunI == II_alloca || FunI == II_win_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000672 return true;
673 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000674 }
Anna Zaks3d348342012-02-14 21:55:24 +0000675
Anna Zaksd79b8402014-10-03 21:48:59 +0000676 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000677 return false;
678
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000679 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000680 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
681 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
682 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
683 if (CheckFree)
684 return true;
685 } else if (OwnKind == OwnershipAttr::Returns) {
686 if (CheckAlloc)
687 return true;
688 }
689 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000690 }
Anna Zaks3d348342012-02-14 21:55:24 +0000691
Anna Zaks3d348342012-02-14 21:55:24 +0000692 return false;
693}
694
Anton Yartsev8b662702013-03-28 16:10:38 +0000695// Tells if the callee is one of the following:
696// 1) A global non-placement new/delete operator function.
697// 2) A global placement operator function with the single placement argument
698// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000699bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
700 ASTContext &C) const {
701 if (!FD)
702 return false;
703
704 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000705 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000706 Kind != OO_Delete && Kind != OO_Array_Delete)
707 return false;
708
Anton Yartsev8b662702013-03-28 16:10:38 +0000709 // Skip all operator new/delete methods.
710 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000711 return false;
712
713 // Return true if tested operator is a standard placement nothrow operator.
714 if (FD->getNumParams() == 2) {
715 QualType T = FD->getParamDecl(1)->getType();
716 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
717 return II->getName().equals("nothrow_t");
718 }
719
720 // Skip placement operators.
721 if (FD->getNumParams() != 1 || FD->isVariadic())
722 return false;
723
724 // One of the standard new/new[]/delete/delete[] non-placement operators.
725 return true;
726}
727
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000728llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
729 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
730 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
731 //
732 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
733 //
734 // One of the possible flags is M_ZERO, which means 'give me back an
735 // allocation which is already zeroed', like calloc.
736
737 // 2-argument kmalloc(), as used in the Linux kernel:
738 //
739 // void *kmalloc(size_t size, gfp_t flags);
740 //
741 // Has the similar flag value __GFP_ZERO.
742
743 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
744 // code could be shared.
745
746 ASTContext &Ctx = C.getASTContext();
747 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
748
749 if (!KernelZeroFlagVal.hasValue()) {
750 if (OS == llvm::Triple::FreeBSD)
751 KernelZeroFlagVal = 0x0100;
752 else if (OS == llvm::Triple::NetBSD)
753 KernelZeroFlagVal = 0x0002;
754 else if (OS == llvm::Triple::OpenBSD)
755 KernelZeroFlagVal = 0x0008;
756 else if (OS == llvm::Triple::Linux)
757 // __GFP_ZERO
758 KernelZeroFlagVal = 0x8000;
759 else
760 // FIXME: We need a more general way of getting the M_ZERO value.
761 // See also: O_CREAT in UnixAPIChecker.cpp.
762
763 // Fall back to normal malloc behavior on platforms where we don't
764 // know M_ZERO.
765 return None;
766 }
767
768 // We treat the last argument as the flags argument, and callers fall-back to
769 // normal malloc on a None return. This works for the FreeBSD kernel malloc
770 // as well as Linux kmalloc.
771 if (CE->getNumArgs() < 2)
772 return None;
773
774 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
George Karpenkovd703ec92018-01-17 20:27:29 +0000775 const SVal V = C.getSVal(FlagsEx);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000776 if (!V.getAs<NonLoc>()) {
777 // The case where 'V' can be a location can only be due to a bad header,
778 // so in this case bail out.
779 return None;
780 }
781
782 NonLoc Flags = V.castAs<NonLoc>();
783 NonLoc ZeroFlag = C.getSValBuilder()
784 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
785 .castAs<NonLoc>();
786 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
787 Flags, ZeroFlag,
788 FlagsEx->getType());
789 if (MaskedFlagsUC.isUnknownOrUndef())
790 return None;
791 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
792
793 // Check if maskedFlags is non-zero.
794 ProgramStateRef TrueState, FalseState;
795 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
796
797 // If M_ZERO is set, treat this like calloc (initialized).
798 if (TrueState && !FalseState) {
799 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
800 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
801 }
802
803 return None;
804}
805
Leslie Zhaie3986c52017-04-26 05:33:14 +0000806SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
807 const Expr *BlockBytes) {
808 SValBuilder &SB = C.getSValBuilder();
809 SVal BlocksVal = C.getSVal(Blocks);
810 SVal BlockBytesVal = C.getSVal(BlockBytes);
811 ProgramStateRef State = C.getState();
812 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
813 SB.getContext().getSizeType());
814 return TotalSize;
815}
816
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000817void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000818 if (C.wasInlined)
819 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000820
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000821 const FunctionDecl *FD = C.getCalleeDecl(CE);
822 if (!FD)
823 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000824
Anna Zaks40a7eb32012-02-22 19:24:52 +0000825 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000826 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000827
828 if (FD->getKind() == Decl::Function) {
829 initIdentifierInfo(C.getASTContext());
830 IdentifierInfo *FunI = FD->getIdentifier();
831
Anna Zaksbbec97c2017-03-09 00:01:01 +0000832 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000833 if (CE->getNumArgs() < 1)
834 return;
835 if (CE->getNumArgs() < 3) {
836 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000837 if (CE->getNumArgs() == 1)
838 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000839 } else if (CE->getNumArgs() == 3) {
840 llvm::Optional<ProgramStateRef> MaybeState =
841 performKernelMalloc(CE, C, State);
842 if (MaybeState.hasValue())
843 State = MaybeState.getValue();
844 else
845 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
846 }
847 } else if (FunI == II_kmalloc) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000848 if (CE->getNumArgs() < 1)
849 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000850 llvm::Optional<ProgramStateRef> MaybeState =
851 performKernelMalloc(CE, C, State);
852 if (MaybeState.hasValue())
853 State = MaybeState.getValue();
854 else
855 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
856 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000857 if (CE->getNumArgs() < 1)
858 return;
859 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000860 State = ProcessZeroAllocation(C, CE, 0, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000861 } else if (FunI == II_realloc || FunI == II_g_realloc ||
862 FunI == II_g_try_realloc) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000863 State = ReallocMemAux(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000864 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000865 } else if (FunI == II_reallocf) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000866 State = ReallocMemAux(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000867 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000868 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000869 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000870 State = ProcessZeroAllocation(C, CE, 0, State);
871 State = ProcessZeroAllocation(C, CE, 1, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000872 } else if (FunI == II_free || FunI == II_g_free) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000873 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaks30d46682016-03-08 01:21:51 +0000874 } else if (FunI == II_strdup || FunI == II_win_strdup ||
875 FunI == II_wcsdup || FunI == II_win_wcsdup) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000876 State = MallocUpdateRefState(C, CE, State);
877 } else if (FunI == II_strndup) {
878 State = MallocUpdateRefState(C, CE, State);
Anna Zaks30d46682016-03-08 01:21:51 +0000879 } else if (FunI == II_alloca || FunI == II_win_alloca) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000880 if (CE->getNumArgs() < 1)
881 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000882 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
883 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000884 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000885 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000886 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000887 // as distinct from new/new[]/delete/delete[] expressions that are
888 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000889 // CXXDeleteExpr.
890 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000891 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000892 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
893 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000894 State = ProcessZeroAllocation(C, CE, 0, State);
895 }
896 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000897 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
898 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000899 State = ProcessZeroAllocation(C, CE, 0, State);
900 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000901 else if (K == OO_Delete || K == OO_Array_Delete)
902 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
903 else
904 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000905 } else if (FunI == II_if_nameindex) {
906 // Should we model this differently? We can allocate a fixed number of
907 // elements with zeros in the last one.
908 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
909 AF_IfNameIndex);
910 } else if (FunI == II_if_freenameindex) {
911 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000912 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
913 if (CE->getNumArgs() < 1)
914 return;
915 SValBuilder &svalBuilder = C.getSValBuilder();
916 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
917 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
918 State = ProcessZeroAllocation(C, CE, 0, State);
919 } else if (FunI == II_g_memdup) {
920 if (CE->getNumArgs() < 2)
921 return;
922 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
923 State = ProcessZeroAllocation(C, CE, 1, State);
Leslie Zhaie3986c52017-04-26 05:33:14 +0000924 } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
925 FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
926 if (CE->getNumArgs() < 2)
927 return;
928 SVal Init = UndefinedVal();
929 if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
930 SValBuilder &SB = C.getSValBuilder();
931 Init = SB.makeZeroVal(SB.getContext().CharTy);
932 }
933 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
934 State = MallocMemAux(C, CE, TotalSize, Init, State);
935 State = ProcessZeroAllocation(C, CE, 0, State);
936 State = ProcessZeroAllocation(C, CE, 1, State);
937 } else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
938 if (CE->getNumArgs() < 3)
939 return;
940 State = ReallocMemAux(C, CE, false, State, true);
941 State = ProcessZeroAllocation(C, CE, 1, State);
942 State = ProcessZeroAllocation(C, CE, 2, State);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000943 }
944 }
945
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000946 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000947 // Check all the attributes, if there are any.
948 // There can be multiple of these attributes.
949 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000950 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
951 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000952 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000953 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000954 break;
955 case OwnershipAttr::Takes:
956 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000957 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000958 break;
959 }
960 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000961 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000962 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000963}
964
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000965// Performs a 0-sized allocations check.
Artem Dergachev13b20262018-01-17 23:46:13 +0000966ProgramStateRef MallocChecker::ProcessZeroAllocation(
967 CheckerContext &C, const Expr *E, const unsigned AllocationSizeArg,
968 ProgramStateRef State, Optional<SVal> RetVal) const {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000969 if (!State)
970 return nullptr;
971
Artem Dergachev13b20262018-01-17 23:46:13 +0000972 if (!RetVal)
973 RetVal = C.getSVal(E);
974
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000975 const Expr *Arg = nullptr;
976
977 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
978 Arg = CE->getArg(AllocationSizeArg);
979 }
980 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
981 if (NE->isArray())
982 Arg = NE->getArraySize();
983 else
984 return State;
985 }
986 else
987 llvm_unreachable("not a CallExpr or CXXNewExpr");
988
989 assert(Arg);
990
George Karpenkovd703ec92018-01-17 20:27:29 +0000991 Optional<DefinedSVal> DefArgVal = C.getSVal(Arg).getAs<DefinedSVal>();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000992
993 if (!DefArgVal)
994 return State;
995
996 // Check if the allocation size is 0.
997 ProgramStateRef TrueState, FalseState;
998 SValBuilder &SvalBuilder = C.getSValBuilder();
999 DefinedSVal Zero =
1000 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1001
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001002 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001003 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1004
1005 if (TrueState && !FalseState) {
Artem Dergachev13b20262018-01-17 23:46:13 +00001006 SymbolRef Sym = RetVal->getAsLocSymbol();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001007 if (!Sym)
1008 return State;
1009
1010 const RefState *RS = State->get<RegionState>(Sym);
Devin Coughlin81771732015-09-22 22:47:14 +00001011 if (RS) {
1012 if (RS->isAllocated())
1013 return TrueState->set<RegionState>(Sym,
1014 RefState::getAllocatedOfSizeZero(RS));
1015 else
1016 return State;
1017 } else {
1018 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1019 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1020 // tracked. Add zero-reallocated Sym to the state to catch references
1021 // to zero-allocated memory.
1022 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1023 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001024 }
1025
1026 // Assume the value is non-zero going forward.
1027 assert(FalseState);
1028 return FalseState;
1029}
1030
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001031static QualType getDeepPointeeType(QualType T) {
1032 QualType Result = T, PointeeType = T->getPointeeType();
1033 while (!PointeeType.isNull()) {
1034 Result = PointeeType;
1035 PointeeType = PointeeType->getPointeeType();
1036 }
1037 return Result;
1038}
1039
1040static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1041
1042 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1043 if (!ConstructE)
1044 return false;
1045
1046 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1047 return false;
1048
1049 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1050
1051 // Iterate over the constructor parameters.
David Majnemer59f77922016-06-24 04:05:48 +00001052 for (const auto *CtorParam : CtorD->parameters()) {
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001053
1054 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1055 if (CtorParamPointeeT.isNull())
1056 continue;
1057
1058 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1059
1060 if (CtorParamPointeeT->getAsCXXRecordDecl())
1061 return true;
1062 }
1063
1064 return false;
1065}
1066
Artem Dergachev13b20262018-01-17 23:46:13 +00001067void MallocChecker::processNewAllocation(const CXXNewExpr *NE,
1068 CheckerContext &C,
1069 SVal Target) const {
Anton Yartsev13df0362013-03-25 01:35:45 +00001070 if (NE->getNumPlacementArgs())
1071 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1072 E = NE->placement_arg_end(); I != E; ++I)
1073 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1074 checkUseAfterFree(Sym, C, *I);
1075
Anton Yartsev13df0362013-03-25 01:35:45 +00001076 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1077 return;
1078
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001079 ParentMap &PM = C.getLocationContext()->getParentMap();
1080 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1081 return;
1082
Anton Yartsev13df0362013-03-25 01:35:45 +00001083 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001084 // The return value from operator new is bound to a specified initialization
1085 // value (if any) and we don't want to loose this value. So we call
1086 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +00001087 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001088 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Artem Dergachev13b20262018-01-17 23:46:13 +00001089 : AF_CXXNew, Target);
1090 State = addExtentSize(C, NE, State, Target);
1091 State = ProcessZeroAllocation(C, NE, 0, State, Target);
Anton Yartsev13df0362013-03-25 01:35:45 +00001092 C.addTransition(State);
1093}
1094
Artem Dergachev13b20262018-01-17 23:46:13 +00001095void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1096 CheckerContext &C) const {
1097 if (!C.getAnalysisManager().getAnalyzerOptions().mayInlineCXXAllocator())
1098 processNewAllocation(NE, C, C.getSVal(NE));
1099}
1100
1101void MallocChecker::checkNewAllocator(const CXXNewExpr *NE, SVal Target,
1102 CheckerContext &C) const {
1103 if (!C.wasInlined)
1104 processNewAllocation(NE, C, Target);
1105}
1106
Gabor Horvath73040272016-09-19 20:39:52 +00001107// Sets the extent value of the MemRegion allocated by
1108// new expression NE to its size in Bytes.
1109//
1110ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1111 const CXXNewExpr *NE,
Artem Dergachev13b20262018-01-17 23:46:13 +00001112 ProgramStateRef State,
1113 SVal Target) {
Gabor Horvath73040272016-09-19 20:39:52 +00001114 if (!State)
1115 return nullptr;
1116 SValBuilder &svalBuilder = C.getSValBuilder();
1117 SVal ElementCount;
Gabor Horvath73040272016-09-19 20:39:52 +00001118 const SubRegion *Region;
1119 if (NE->isArray()) {
1120 const Expr *SizeExpr = NE->getArraySize();
George Karpenkovd703ec92018-01-17 20:27:29 +00001121 ElementCount = C.getSVal(SizeExpr);
Gabor Horvath73040272016-09-19 20:39:52 +00001122 // Store the extent size for the (symbolic)region
1123 // containing the elements.
Artem Dergachev13b20262018-01-17 23:46:13 +00001124 Region = Target.getAsRegion()
Gabor Horvath73040272016-09-19 20:39:52 +00001125 ->getAs<SubRegion>()
Artem Dergachev13b20262018-01-17 23:46:13 +00001126 ->StripCasts()
Gabor Horvath73040272016-09-19 20:39:52 +00001127 ->getAs<SubRegion>();
1128 } else {
1129 ElementCount = svalBuilder.makeIntVal(1, true);
Artem Dergachev13b20262018-01-17 23:46:13 +00001130 Region = Target.getAsRegion()->getAs<SubRegion>();
Gabor Horvath73040272016-09-19 20:39:52 +00001131 }
1132 assert(Region);
1133
1134 // Set the region's extent equal to the Size in Bytes.
1135 QualType ElementType = NE->getAllocatedType();
1136 ASTContext &AstContext = C.getASTContext();
1137 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1138
Devin Coughline3b75de2016-12-16 18:41:40 +00001139 if (ElementCount.getAs<NonLoc>()) {
Gabor Horvath73040272016-09-19 20:39:52 +00001140 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1141 // size in Bytes = ElementCount*TypeSize
1142 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1143 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1144 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1145 svalBuilder.getArrayIndexType());
1146 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1147 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1148 State = State->assume(extentMatchesSize, true);
1149 }
1150 return State;
1151}
1152
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001153void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001154 CheckerContext &C) const {
1155
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001156 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +00001157 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1158 checkUseAfterFree(Sym, C, DE->getArgument());
1159
Anton Yartsev13df0362013-03-25 01:35:45 +00001160 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1161 return;
1162
1163 ProgramStateRef State = C.getState();
1164 bool ReleasedAllocated;
1165 State = FreeMemAux(C, DE->getArgument(), DE, State,
1166 /*Hold*/false, ReleasedAllocated);
1167
1168 C.addTransition(State);
1169}
1170
Jordan Rose613f3c02013-03-09 00:59:10 +00001171static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1172 // If the first selector piece is one of the names below, assume that the
1173 // object takes ownership of the memory, promising to eventually deallocate it
1174 // with free().
1175 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1176 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1177 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
Alexander Kornienko9c104902015-12-28 13:06:58 +00001178 return FirstSlot == "dataWithBytesNoCopy" ||
1179 FirstSlot == "initWithBytesNoCopy" ||
1180 FirstSlot == "initWithCharactersNoCopy";
Anna Zaks0d6989b2012-06-22 02:04:31 +00001181}
1182
Jordan Rose613f3c02013-03-09 00:59:10 +00001183static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1184 Selector S = Call.getSelector();
1185
1186 // FIXME: We should not rely on fully-constrained symbols being folded.
1187 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1188 if (S.getNameForSlot(i).equals("freeWhenDone"))
1189 return !Call.getArgSVal(i).isZeroConstant();
1190
1191 return None;
1192}
1193
Anna Zaks67291b92012-11-13 03:18:01 +00001194void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1195 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001196 if (C.wasInlined)
1197 return;
1198
Jordan Rose613f3c02013-03-09 00:59:10 +00001199 if (!isKnownDeallocObjCMethodName(Call))
1200 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001201
Jordan Rose613f3c02013-03-09 00:59:10 +00001202 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1203 if (!*FreeWhenDone)
1204 return;
1205
1206 bool ReleasedAllocatedMemory;
1207 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1208 Call.getOriginExpr(), C.getState(),
1209 /*Hold=*/true, ReleasedAllocatedMemory,
1210 /*RetNullOnFailure=*/true);
1211
1212 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001213}
1214
Richard Smith852e9ce2013-11-27 01:46:48 +00001215ProgramStateRef
1216MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001217 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001218 ProgramStateRef State) const {
1219 if (!State)
1220 return nullptr;
1221
Richard Smith852e9ce2013-11-27 01:46:48 +00001222 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001223 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001224
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001225 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001226 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001227 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001228 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001229 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1230}
1231
1232ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1233 const CallExpr *CE,
1234 const Expr *SizeEx, SVal Init,
1235 ProgramStateRef State,
1236 AllocationFamily Family) {
1237 if (!State)
1238 return nullptr;
1239
George Karpenkovd703ec92018-01-17 20:27:29 +00001240 return MallocMemAux(C, CE, C.getSVal(SizeEx), Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001241}
1242
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001243ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001244 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001245 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001246 ProgramStateRef State,
1247 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001248 if (!State)
1249 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001250
Jordan Rosef69e65f2014-09-05 16:33:51 +00001251 // We expect the malloc functions to return a pointer.
1252 if (!Loc::isLocType(CE->getType()))
1253 return nullptr;
1254
Anna Zaks3563fde2012-06-07 03:57:32 +00001255 // Bind the return value to the symbolic value from the heap region.
1256 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1257 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001258 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001259 SValBuilder &svalBuilder = C.getSValBuilder();
1260 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001261 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1262 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001263 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001264
Jordy Rose674bd552010-07-04 00:00:41 +00001265 // Fill the region with the initialization value.
Anna Zaksb5701952017-01-13 00:50:57 +00001266 State = State->bindDefault(RetVal, Init, LCtx);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001267
Jordy Rose674bd552010-07-04 00:00:41 +00001268 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001269 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001270 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001271 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001272 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001273 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001274 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001275 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001276 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001277 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001278 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001279
Anton Yartsev05789592013-03-28 17:05:19 +00001280 State = State->assume(extentMatchesSize, true);
1281 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001282 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001283
Anton Yartsev05789592013-03-28 17:05:19 +00001284 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001285}
1286
1287ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001288 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001289 ProgramStateRef State,
Artem Dergachev13b20262018-01-17 23:46:13 +00001290 AllocationFamily Family,
1291 Optional<SVal> RetVal) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001292 if (!State)
1293 return nullptr;
1294
Anna Zaks40a7eb32012-02-22 19:24:52 +00001295 // Get the return value.
Artem Dergachev13b20262018-01-17 23:46:13 +00001296 if (!RetVal)
1297 RetVal = C.getSVal(E);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001298
1299 // We expect the malloc functions to return a pointer.
Artem Dergachev13b20262018-01-17 23:46:13 +00001300 if (!RetVal->getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001301 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001302
Artem Dergachev13b20262018-01-17 23:46:13 +00001303 SymbolRef Sym = RetVal->getAsLocSymbol();
1304 // This is a return value of a function that was not inlined, such as malloc()
1305 // or new(). We've checked that in the caller. Therefore, it must be a symbol.
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001306 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001307
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001308 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001309 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001310}
1311
Anna Zaks40a7eb32012-02-22 19:24:52 +00001312ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1313 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001314 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001315 ProgramStateRef State) const {
1316 if (!State)
1317 return nullptr;
1318
Richard Smith852e9ce2013-11-27 01:46:48 +00001319 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001320 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001321
Anna Zaksfe6eb672012-08-24 02:28:20 +00001322 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001323
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001324 for (const auto &Arg : Att->args()) {
1325 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001326 Att->getOwnKind() == OwnershipAttr::Holds,
1327 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001328 if (StateI)
1329 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001330 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001331 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001332}
1333
Ted Kremenek49b1e382012-01-26 21:29:00 +00001334ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001335 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001336 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001337 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001338 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001339 bool &ReleasedAllocated,
1340 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001341 if (!State)
1342 return nullptr;
1343
Anna Zaksb508d292012-04-10 23:41:11 +00001344 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001345 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001346
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001347 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001348 ReleasedAllocated, ReturnsNullOnFailure);
1349}
1350
Anna Zaksa14c1d02012-11-13 19:47:40 +00001351/// Checks if the previous call to free on the given symbol failed - if free
1352/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001353static bool didPreviousFreeFail(ProgramStateRef State,
1354 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001355 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001356 if (Ret) {
1357 assert(*Ret && "We should not store the null return symbol");
1358 ConstraintManager &CMgr = State->getConstraintManager();
1359 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001360 RetStatusSymbol = *Ret;
1361 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001362 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001363 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001364}
1365
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001366AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001367 const Stmt *S) const {
1368 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001369 return AF_None;
1370
Anton Yartseve3377fb2013-04-04 23:46:29 +00001371 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001372 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001373
1374 if (!FD)
1375 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1376
Anton Yartsev05789592013-03-28 17:05:19 +00001377 ASTContext &Ctx = C.getASTContext();
1378
Anna Zaksd79b8402014-10-03 21:48:59 +00001379 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001380 return AF_Malloc;
1381
1382 if (isStandardNewDelete(FD, Ctx)) {
1383 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001384 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001385 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001386 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001387 return AF_CXXNewArray;
1388 }
1389
Anna Zaksd79b8402014-10-03 21:48:59 +00001390 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1391 return AF_IfNameIndex;
1392
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001393 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1394 return AF_Alloca;
1395
Anton Yartsev05789592013-03-28 17:05:19 +00001396 return AF_None;
1397 }
1398
Anton Yartseve3377fb2013-04-04 23:46:29 +00001399 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1400 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1401
1402 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001403 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1404
Anton Yartseve3377fb2013-04-04 23:46:29 +00001405 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001406 return AF_Malloc;
1407
1408 return AF_None;
1409}
1410
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001411bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001412 const Expr *E) const {
1413 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1414 // FIXME: This doesn't handle indirect calls.
1415 const FunctionDecl *FD = CE->getDirectCallee();
1416 if (!FD)
1417 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001418
Anton Yartsev05789592013-03-28 17:05:19 +00001419 os << *FD;
1420 if (!FD->isOverloadedOperator())
1421 os << "()";
1422 return true;
1423 }
1424
1425 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1426 if (Msg->isInstanceMessage())
1427 os << "-";
1428 else
1429 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001430 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001431 return true;
1432 }
1433
1434 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001435 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001436 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1437 << "'";
1438 return true;
1439 }
1440
1441 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001442 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001443 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1444 << "'";
1445 return true;
1446 }
1447
1448 return false;
1449}
1450
1451void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1452 const Expr *E) const {
1453 AllocationFamily Family = getAllocationFamily(C, E);
1454
1455 switch(Family) {
1456 case AF_Malloc: os << "malloc()"; return;
1457 case AF_CXXNew: os << "'new'"; return;
1458 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001459 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001460 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001461 case AF_None: llvm_unreachable("not a deallocation expression");
1462 }
1463}
1464
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001465void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001466 AllocationFamily Family) const {
1467 switch(Family) {
1468 case AF_Malloc: os << "free()"; return;
1469 case AF_CXXNew: os << "'delete'"; return;
1470 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001471 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001472 case AF_Alloca:
1473 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001474 }
1475}
1476
Anna Zaks0d6989b2012-06-22 02:04:31 +00001477ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1478 const Expr *ArgExpr,
1479 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001480 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001481 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001482 bool &ReleasedAllocated,
1483 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001484
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001485 if (!State)
1486 return nullptr;
1487
George Karpenkovd703ec92018-01-17 20:27:29 +00001488 SVal ArgVal = C.getSVal(ArgExpr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001489 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001490 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001491 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001492
1493 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001494 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001495 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001496
Anna Zaksad01ef52012-02-14 00:26:13 +00001497 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001498 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001499 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001500 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001501 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001502
Jordy Rose3597b212010-06-07 19:32:37 +00001503 // Unknown values could easily be okay
1504 // Undefined values are handled elsewhere
1505 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001506 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001507
Jordy Rose3597b212010-06-07 19:32:37 +00001508 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001509
Jordy Rose3597b212010-06-07 19:32:37 +00001510 // Nonlocs can't be freed, of course.
1511 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1512 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001513 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001514 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001515 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001516
Jordy Rose3597b212010-06-07 19:32:37 +00001517 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001518
Jordy Rose3597b212010-06-07 19:32:37 +00001519 // Blocks might show up as heap data, but should not be free()d
1520 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001521 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001522 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001523 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001524
Jordy Rose3597b212010-06-07 19:32:37 +00001525 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001526
1527 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001528 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001529 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1530 // FIXME: at the time this code was written, malloc() regions were
1531 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1532 // This means that there isn't actually anything from HeapSpaceRegion
1533 // that should be freed, even though we allow it here.
1534 // Of course, free() can work on memory allocated outside the current
1535 // function, so UnknownSpaceRegion is always a possibility.
1536 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001537
1538 if (isa<AllocaRegion>(R))
1539 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1540 else
1541 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1542
Craig Topper0dbb7832014-05-27 02:45:47 +00001543 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001544 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001545
1546 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001547 // Various cases could lead to non-symbol values here.
1548 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001549 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001550 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001551
Anna Zaksc89ad072013-02-07 23:05:47 +00001552 SymbolRef SymBase = SrBase->getSymbol();
1553 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001554 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001555
Anton Yartseve3377fb2013-04-04 23:46:29 +00001556 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001557
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001558 // Memory returned by alloca() shouldn't be freed.
1559 if (RsBase->getAllocationFamily() == AF_Alloca) {
1560 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1561 return nullptr;
1562 }
1563
Anna Zaks93a21a82013-04-09 00:30:28 +00001564 // Check for double free first.
1565 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001566 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1567 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1568 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001569 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001570
Anna Zaks93a21a82013-04-09 00:30:28 +00001571 // If the pointer is allocated or escaped, but we are now trying to free it,
1572 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001573 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001574 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001575
1576 // Check if an expected deallocation function matches the real one.
1577 bool DeallocMatchesAlloc =
1578 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1579 if (!DeallocMatchesAlloc) {
1580 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001581 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001582 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001583 }
1584
1585 // Check if the memory location being freed is the actual location
1586 // allocated, or an offset.
1587 RegionOffset Offset = R->getAsOffset();
1588 if (Offset.isValid() &&
1589 !Offset.hasSymbolicOffset() &&
1590 Offset.getOffset() != 0) {
1591 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001592 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001593 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001594 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001595 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001596 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001597 }
1598
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00001599 if (SymBase->getType()->isFunctionPointerType()) {
1600 ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1601 return nullptr;
1602 }
1603
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001604 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001605 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001606
Anna Zaksa14c1d02012-11-13 19:47:40 +00001607 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001608 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001609
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001610 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001611 // failed.
1612 if (ReturnsNullOnFailure) {
1613 SVal RetVal = C.getSVal(ParentExpr);
1614 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1615 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001616 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1617 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001618 }
1619 }
1620
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001621 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1622 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001623 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001624 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001625 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001626 RefState::getRelinquished(Family,
1627 ParentExpr));
1628
1629 return State->set<RegionState>(SymBase,
1630 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001631}
1632
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001633Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001634MallocChecker::getCheckIfTracked(AllocationFamily Family,
1635 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001636 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001637 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001638 case AF_Alloca:
1639 case AF_IfNameIndex: {
1640 if (ChecksEnabled[CK_MallocChecker])
1641 return CK_MallocChecker;
1642
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001643 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001644 }
1645 case AF_CXXNew:
1646 case AF_CXXNewArray: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001647 if (IsALeakCheck) {
1648 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1649 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001650 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001651 else {
1652 if (ChecksEnabled[CK_NewDeleteChecker])
1653 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001654 }
1655 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001656 }
1657 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001658 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001659 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001660 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001661 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001662}
1663
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001664Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001665MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001666 const Stmt *AllocDeallocStmt,
1667 bool IsALeakCheck) const {
1668 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1669 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001670}
1671
1672Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001673MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1674 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001675 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1676 return CK_MallocChecker;
1677
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001678 const RefState *RS = C.getState()->get<RegionState>(Sym);
1679 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001680 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001681}
1682
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001683bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001684 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001685 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001686 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001687 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001688 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001689 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001690 else
1691 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001692
Jordy Rose3597b212010-06-07 19:32:37 +00001693 return true;
1694}
1695
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001696bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001697 const MemRegion *MR) {
1698 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +00001699 case MemRegion::FunctionCodeRegionKind: {
1700 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001701 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001702 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001703 else
1704 os << "the address of a function";
1705 return true;
1706 }
Artem Dergachev73f018e2016-01-13 13:49:29 +00001707 case MemRegion::BlockCodeRegionKind:
Jordy Rose3597b212010-06-07 19:32:37 +00001708 os << "block text";
1709 return true;
1710 case MemRegion::BlockDataRegionKind:
1711 // FIXME: where the block came from?
1712 os << "a block";
1713 return true;
1714 default: {
1715 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001716
Anna Zaks8158ef02012-01-04 23:54:01 +00001717 if (isa<StackLocalsSpaceRegion>(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 os << "the address of the local variable '" << VD->getName() << "'";
1727 else
1728 os << "the address of a local stack variable";
1729 return true;
1730 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001731
1732 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001733 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1734 const VarDecl *VD;
1735 if (VR)
1736 VD = VR->getDecl();
1737 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001738 VD = nullptr;
1739
Jordy Rose3597b212010-06-07 19:32:37 +00001740 if (VD)
1741 os << "the address of the parameter '" << VD->getName() << "'";
1742 else
1743 os << "the address of a parameter";
1744 return true;
1745 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001746
1747 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001748 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1749 const VarDecl *VD;
1750 if (VR)
1751 VD = VR->getDecl();
1752 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001753 VD = nullptr;
1754
Jordy Rose3597b212010-06-07 19:32:37 +00001755 if (VD) {
1756 if (VD->isStaticLocal())
1757 os << "the address of the static variable '" << VD->getName() << "'";
1758 else
1759 os << "the address of the global variable '" << VD->getName() << "'";
1760 } else
1761 os << "the address of a global variable";
1762 return true;
1763 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001764
1765 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001766 }
1767 }
1768}
1769
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001770void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1771 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001772 const Expr *DeallocExpr) const {
1773
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001774 if (!ChecksEnabled[CK_MallocChecker] &&
1775 !ChecksEnabled[CK_NewDeleteChecker])
1776 return;
1777
1778 Optional<MallocChecker::CheckKind> CheckKind =
1779 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001780 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001781 return;
1782
Devin Coughline39bd402015-09-16 22:03:05 +00001783 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001784 if (!BT_BadFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001785 BT_BadFree[*CheckKind].reset(new BugType(
1786 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001787
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001788 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001789 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001790
Jordy Rose3597b212010-06-07 19:32:37 +00001791 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001792 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1793 MR = ER->getSuperRegion();
1794
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001795 os << "Argument to ";
1796 if (!printAllocDeallocName(os, C, DeallocExpr))
1797 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001798
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001799 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001800 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001801 : SummarizeValue(os, ArgVal);
1802 if (Summarized)
1803 os << ", which is not memory allocated by ";
1804 else
1805 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001806
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001807 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001808
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001809 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001810 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001811 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001812 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001813 }
1814}
1815
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001816void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001817 SourceRange Range) const {
1818
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001819 Optional<MallocChecker::CheckKind> CheckKind;
1820
1821 if (ChecksEnabled[CK_MallocChecker])
1822 CheckKind = CK_MallocChecker;
1823 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1824 CheckKind = CK_MismatchedDeallocatorChecker;
1825 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001826 return;
1827
Devin Coughline39bd402015-09-16 22:03:05 +00001828 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001829 if (!BT_FreeAlloca[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001830 BT_FreeAlloca[*CheckKind].reset(new BugType(
1831 CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001832
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001833 auto R = llvm::make_unique<BugReport>(
1834 *BT_FreeAlloca[*CheckKind],
1835 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001836 R->markInteresting(ArgVal.getAsRegion());
1837 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001838 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001839 }
1840}
1841
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001842void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001843 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001844 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001845 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001846 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001847 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001848
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001849 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001850 return;
1851
Devin Coughline39bd402015-09-16 22:03:05 +00001852 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001853 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001854 BT_MismatchedDealloc.reset(
1855 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001856 "Bad deallocator", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001857
Anton Yartsev05789592013-03-28 17:05:19 +00001858 SmallString<100> buf;
1859 llvm::raw_svector_ostream os(buf);
1860
1861 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1862 SmallString<20> AllocBuf;
1863 llvm::raw_svector_ostream AllocOs(AllocBuf);
1864 SmallString<20> DeallocBuf;
1865 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1866
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001867 if (OwnershipTransferred) {
1868 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1869 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001870 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001871 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001872
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001873 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001874
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001875 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1876 os << " allocated by " << AllocOs.str();
1877 } else {
1878 os << "Memory";
1879 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1880 os << " allocated by " << AllocOs.str();
1881
1882 os << " should be deallocated by ";
1883 printExpectedDeallocName(os, RS->getAllocationFamily());
1884
1885 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1886 os << ", not " << DeallocOs.str();
1887 }
Anton Yartsev05789592013-03-28 17:05:19 +00001888
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001889 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001890 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001891 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001892 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001893 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001894 }
1895}
1896
Anna Zaksc89ad072013-02-07 23:05:47 +00001897void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001898 SourceRange Range, const Expr *DeallocExpr,
1899 const Expr *AllocExpr) const {
1900
Anton Yartsev05789592013-03-28 17:05:19 +00001901
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001902 if (!ChecksEnabled[CK_MallocChecker] &&
1903 !ChecksEnabled[CK_NewDeleteChecker])
1904 return;
1905
1906 Optional<MallocChecker::CheckKind> CheckKind =
1907 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001908 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001909 return;
1910
Devin Coughline39bd402015-09-16 22:03:05 +00001911 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001912 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001913 return;
1914
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001915 if (!BT_OffsetFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001916 BT_OffsetFree[*CheckKind].reset(new BugType(
1917 CheckNames[*CheckKind], "Offset free", categories::MemoryError));
Anna Zaksc89ad072013-02-07 23:05:47 +00001918
1919 SmallString<100> buf;
1920 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001921 SmallString<20> AllocNameBuf;
1922 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001923
1924 const MemRegion *MR = ArgVal.getAsRegion();
1925 assert(MR && "Only MemRegion based symbols can have offset free errors");
1926
1927 RegionOffset Offset = MR->getAsOffset();
1928 assert((Offset.isValid() &&
1929 !Offset.hasSymbolicOffset() &&
1930 Offset.getOffset() != 0) &&
1931 "Only symbols with a valid offset can have offset free errors");
1932
1933 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1934
Anton Yartsev05789592013-03-28 17:05:19 +00001935 os << "Argument to ";
1936 if (!printAllocDeallocName(os, C, DeallocExpr))
1937 os << "deallocator";
1938 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001939 << offsetBytes
1940 << " "
1941 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001942 << " from the start of ";
1943 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1944 os << "memory allocated by " << AllocNameOs.str();
1945 else
1946 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001947
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001948 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001949 R->markInteresting(MR->getBaseRegion());
1950 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001951 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001952}
1953
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001954void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1955 SymbolRef Sym) const {
1956
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001957 if (!ChecksEnabled[CK_MallocChecker] &&
1958 !ChecksEnabled[CK_NewDeleteChecker])
1959 return;
1960
1961 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001962 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001963 return;
1964
Devin Coughline39bd402015-09-16 22:03:05 +00001965 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001966 if (!BT_UseFree[*CheckKind])
1967 BT_UseFree[*CheckKind].reset(new BugType(
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001968 CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001969
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001970 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1971 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001972
1973 R->markInteresting(Sym);
1974 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001975 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001976 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001977 }
1978}
1979
1980void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001981 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001982 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001983
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001984 if (!ChecksEnabled[CK_MallocChecker] &&
1985 !ChecksEnabled[CK_NewDeleteChecker])
1986 return;
1987
1988 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001989 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001990 return;
1991
Devin Coughline39bd402015-09-16 22:03:05 +00001992 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001993 if (!BT_DoubleFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001994 BT_DoubleFree[*CheckKind].reset(new BugType(
1995 CheckNames[*CheckKind], "Double free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001996
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001997 auto R = llvm::make_unique<BugReport>(
1998 *BT_DoubleFree[*CheckKind],
1999 (Released ? "Attempt to free released memory"
2000 : "Attempt to free non-owned memory"),
2001 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002002 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00002003 R->markInteresting(Sym);
2004 if (PrevSym)
2005 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00002006 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002007 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002008 }
2009}
2010
Jordan Rose656fdd52014-01-08 18:46:55 +00002011void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2012
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002013 if (!ChecksEnabled[CK_NewDeleteChecker])
2014 return;
2015
2016 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002017 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00002018 return;
2019
Devin Coughline39bd402015-09-16 22:03:05 +00002020 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00002021 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002022 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002023 "Double delete",
2024 categories::MemoryError));
Jordan Rose656fdd52014-01-08 18:46:55 +00002025
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002026 auto R = llvm::make_unique<BugReport>(
2027 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00002028
2029 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002030 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002031 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00002032 }
2033}
2034
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002035void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2036 SourceRange Range,
2037 SymbolRef Sym) const {
2038
2039 if (!ChecksEnabled[CK_MallocChecker] &&
2040 !ChecksEnabled[CK_NewDeleteChecker])
2041 return;
2042
2043 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2044
2045 if (!CheckKind.hasValue())
2046 return;
2047
Devin Coughline39bd402015-09-16 22:03:05 +00002048 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002049 if (!BT_UseZerroAllocated[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002050 BT_UseZerroAllocated[*CheckKind].reset(
2051 new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2052 categories::MemoryError));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002053
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002054 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2055 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002056
2057 R->addRange(Range);
2058 if (Sym) {
2059 R->markInteresting(Sym);
2060 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2061 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002062 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002063 }
2064}
2065
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002066void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2067 SourceRange Range,
2068 const Expr *FreeExpr) const {
2069 if (!ChecksEnabled[CK_MallocChecker])
2070 return;
2071
2072 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2073 if (!CheckKind.hasValue())
2074 return;
2075
2076 if (ExplodedNode *N = C.generateErrorNode()) {
2077 if (!BT_BadFree[*CheckKind])
Artem Dergachev9849f592018-02-08 23:28:29 +00002078 BT_BadFree[*CheckKind].reset(new BugType(
2079 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002080
2081 SmallString<100> Buf;
2082 llvm::raw_svector_ostream Os(Buf);
2083
2084 const MemRegion *MR = ArgVal.getAsRegion();
2085 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2086 MR = ER->getSuperRegion();
2087
2088 Os << "Argument to ";
2089 if (!printAllocDeallocName(Os, C, FreeExpr))
2090 Os << "deallocator";
2091
2092 Os << " is a function pointer";
2093
2094 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2095 R->markInteresting(MR);
2096 R->addRange(Range);
2097 C.emitReport(std::move(R));
2098 }
2099}
2100
Leslie Zhaie3986c52017-04-26 05:33:14 +00002101ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2102 const CallExpr *CE,
2103 bool FreesOnFail,
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002104 ProgramStateRef State,
Leslie Zhaie3986c52017-04-26 05:33:14 +00002105 bool SuffixWithN) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002106 if (!State)
2107 return nullptr;
2108
Leslie Zhaie3986c52017-04-26 05:33:14 +00002109 if (SuffixWithN && CE->getNumArgs() < 3)
2110 return nullptr;
2111 else if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002112 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002113
Ted Kremenek90af9092010-12-02 07:49:45 +00002114 const Expr *arg0Expr = CE->getArg(0);
George Karpenkovd703ec92018-01-17 20:27:29 +00002115 SVal Arg0Val = C.getSVal(arg0Expr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00002116 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002117 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00002118 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002119
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002120 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002121
Ted Kremenek90af9092010-12-02 07:49:45 +00002122 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002123 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002124
Leslie Zhaie3986c52017-04-26 05:33:14 +00002125 // Get the size argument.
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002126 const Expr *Arg1 = CE->getArg(1);
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002127
2128 // Get the value of the size argument.
George Karpenkovd703ec92018-01-17 20:27:29 +00002129 SVal TotalSize = C.getSVal(Arg1);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002130 if (SuffixWithN)
2131 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2132 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002133 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002134
2135 // Compare the size argument to 0.
2136 DefinedOrUnknownSVal SizeZero =
Leslie Zhaie3986c52017-04-26 05:33:14 +00002137 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002138 svalBuilder.makeIntValWithPtrWidth(0, false));
2139
Anna Zaksd56c8792012-02-13 18:05:39 +00002140 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002141 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00002142 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002143 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00002144 // We only assume exceptional states if they are definitely true; if the
2145 // state is under-constrained, assume regular realloc behavior.
2146 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2147 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2148
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002149 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002150 // malloc(size).
Leslie Zhaie3986c52017-04-26 05:33:14 +00002151 if (PrtIsNull && !SizeIsZero) {
2152 ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002153 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002154 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002155 }
2156
Anna Zaksd56c8792012-02-13 18:05:39 +00002157 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00002158 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002159
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002160 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00002161 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002162 SymbolRef FromPtr = arg0Val.getAsSymbol();
George Karpenkovd703ec92018-01-17 20:27:29 +00002163 SVal RetVal = C.getSVal(CE);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002164 SymbolRef ToPtr = RetVal.getAsSymbol();
2165 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00002166 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00002167
Anna Zaksfe6eb672012-08-24 02:28:20 +00002168 bool ReleasedAllocated = false;
2169
Anna Zaksd56c8792012-02-13 18:05:39 +00002170 // If the size is 0, free the memory.
2171 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00002172 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2173 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00002174 // The semantics of the return value are:
2175 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00002176 // to free() is returned. We just free the input pointer and do not add
2177 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00002178 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00002179 }
2180
2181 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00002182 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002183 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00002184
Leslie Zhaie3986c52017-04-26 05:33:14 +00002185 ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002186 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002187 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00002188 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00002189
Anna Zaks75cfbb62012-09-12 22:57:34 +00002190 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2191 if (FreesOnFail)
2192 Kind = RPIsFreeOnFailure;
2193 else if (!ReleasedAllocated)
2194 Kind = RPDoNotTrackAfterFailure;
2195
Anna Zaksfe6eb672012-08-24 02:28:20 +00002196 // Record the info about the reallocated symbol so that we could properly
2197 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00002198 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00002199 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00002200 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00002201 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002202 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002203 }
Craig Topper0dbb7832014-05-27 02:45:47 +00002204 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00002205}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002206
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002207ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002208 ProgramStateRef State) {
2209 if (!State)
2210 return nullptr;
2211
Anna Zaksb508d292012-04-10 23:41:11 +00002212 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002213 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002214
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002215 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek90af9092010-12-02 07:49:45 +00002216 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002217 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002218
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002219 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002220}
2221
Anna Zaksfc2e1532012-03-21 19:45:08 +00002222LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002223MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2224 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002225 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002226 // Walk the ExplodedGraph backwards and find the first node that referred to
2227 // the tracked symbol.
2228 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002229 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002230
2231 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002232 ProgramStateRef State = N->getState();
2233 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002234 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002235
2236 // Find the most recent expression bound to the symbol in the current
2237 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002238 if (!ReferenceRegion) {
2239 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2240 SVal Val = State->getSVal(MR);
2241 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002242 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002243 // Do not show local variables belonging to a function other than
2244 // where the error is reported.
2245 if (!VR ||
2246 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2247 ReferenceRegion = MR;
2248 }
2249 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002250 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002251
Anna Zaks486a0ff2015-02-05 01:02:53 +00002252 // Allocation node, is the last node in the current or parent context in
2253 // which the symbol was tracked.
2254 const LocationContext *NContext = N->getLocationContext();
2255 if (NContext == LeakContext ||
2256 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002257 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002258 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002259 }
2260
Anna Zaksa043d0c2013-01-08 00:25:29 +00002261 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002262}
2263
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002264void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2265 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002266
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002267 if (!ChecksEnabled[CK_MallocChecker] &&
2268 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002269 return;
2270
Anton Yartsev9907fc92015-03-04 23:18:21 +00002271 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002272 assert(RS && "cannot leak an untracked symbol");
2273 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002274
2275 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002276 return;
2277
Anton Yartsev2487dd62015-03-10 22:24:21 +00002278 Optional<MallocChecker::CheckKind>
2279 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002280
Anton Yartsev2487dd62015-03-10 22:24:21 +00002281 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002282 return;
2283
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002284 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002285 if (!BT_Leak[*CheckKind]) {
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002286 BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2287 categories::MemoryError));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002288 // Leaks should not be reported if they are post-dominated by a sink:
2289 // (1) Sinks are higher importance bugs.
2290 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2291 // with __noreturn functions such as assert() or exit(). We choose not
2292 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002293 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002294 }
2295
Anna Zaksdf901a42012-02-23 21:38:21 +00002296 // Most bug reports are cached at the location where they occurred.
2297 // With leaks, we want to unique them by the location where they were
2298 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002299 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002300 const ExplodedNode *AllocNode = nullptr;
2301 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002302 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002303
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002304 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
Anton Yartsev6e499252013-04-05 02:25:02 +00002305 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002306 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2307 C.getSourceManager(),
2308 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002309
Anna Zaksfc2e1532012-03-21 19:45:08 +00002310 SmallString<200> buf;
2311 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002312 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002313 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002314 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002315 } else {
2316 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002317 }
2318
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002319 auto R = llvm::make_unique<BugReport>(
2320 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2321 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002322 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002323 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002324 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002325}
2326
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002327void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2328 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002329{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002330 if (!SymReaper.hasDeadSymbols())
2331 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002332
Ted Kremenek49b1e382012-01-26 21:29:00 +00002333 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002334 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002335 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002336
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002337 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002338 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2339 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002340 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002341 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002342 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002343 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002344
Zhongxing Xuc7460962009-11-13 07:48:11 +00002345 }
2346 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002347
Anna Zaksd56c8792012-02-13 18:05:39 +00002348 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002349 ReallocPairsTy RP = state->get<ReallocPairs>();
2350 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002351 if (SymReaper.isDead(I->first) ||
2352 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002353 state = state->remove<ReallocPairs>(I->first);
2354 }
2355 }
2356
Anna Zaks67291b92012-11-13 03:18:01 +00002357 // Cleanup the FreeReturnValue Map.
2358 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2359 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2360 if (SymReaper.isDead(I->first) ||
2361 SymReaper.isDead(I->second)) {
2362 state = state->remove<FreeReturnValue>(I->first);
2363 }
2364 }
2365
Anna Zaksdf901a42012-02-23 21:38:21 +00002366 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002367 ExplodedNode *N = C.getPredecessor();
2368 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002369 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002370 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2371 if (N) {
2372 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002373 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002374 reportLeak(*I, N, C);
2375 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002376 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002377 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002378
Anna Zaksdf901a42012-02-23 21:38:21 +00002379 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002380}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002381
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002382void MallocChecker::checkPreCall(const CallEvent &Call,
2383 CheckerContext &C) const {
2384
Jordan Rose656fdd52014-01-08 18:46:55 +00002385 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2386 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2387 if (!Sym || checkDoubleDelete(Sym, C))
2388 return;
2389 }
2390
Anna Zaks46d01602012-05-18 01:16:10 +00002391 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002392 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2393 const FunctionDecl *FD = FC->getDecl();
2394 if (!FD)
2395 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002396
Anna Zaksd79b8402014-10-03 21:48:59 +00002397 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002398 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002399 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2400 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2401 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002402 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002403
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002404 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002405 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002406 return;
2407 }
2408
2409 // Check if the callee of a method is deleted.
2410 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2411 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2412 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2413 return;
2414 }
2415
2416 // Check arguments for being used after free.
2417 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2418 SVal ArgSVal = Call.getArgSVal(I);
2419 if (ArgSVal.getAs<Loc>()) {
2420 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002421 if (!Sym)
2422 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002423 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002424 return;
2425 }
2426 }
2427}
2428
Anna Zaksa1b227b2012-02-08 23:16:56 +00002429void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2430 const Expr *E = S->getRetValue();
2431 if (!E)
2432 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002433
2434 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002435 ProgramStateRef State = C.getState();
George Karpenkovd703ec92018-01-17 20:27:29 +00002436 SVal RetVal = C.getSVal(E);
Anna Zaks4ca45b12012-02-22 02:36:01 +00002437 SymbolRef Sym = RetVal.getAsSymbol();
2438 if (!Sym)
2439 // If we are returning a field of the allocated struct or an array element,
2440 // the callee could still free the memory.
2441 // TODO: This logic should be a part of generic symbol escape callback.
2442 if (const MemRegion *MR = RetVal.getAsRegion())
2443 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2444 if (const SymbolicRegion *BMR =
2445 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2446 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002447
Anna Zaks3aa52252012-02-11 21:44:39 +00002448 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002449 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002450 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002451}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002452
Anna Zaks9fe80982012-03-22 00:57:20 +00002453// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002454// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002455// needed.
2456void MallocChecker::checkPostStmt(const BlockExpr *BE,
2457 CheckerContext &C) const {
2458
2459 // Scan the BlockDecRefExprs for any object the retain count checker
2460 // may be tracking.
2461 if (!BE->getBlockDecl()->hasCaptures())
2462 return;
2463
2464 ProgramStateRef state = C.getState();
2465 const BlockDataRegion *R =
George Karpenkovd703ec92018-01-17 20:27:29 +00002466 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
Anna Zaks9fe80982012-03-22 00:57:20 +00002467
2468 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2469 E = R->referenced_vars_end();
2470
2471 if (I == E)
2472 return;
2473
2474 SmallVector<const MemRegion*, 10> Regions;
2475 const LocationContext *LC = C.getLocationContext();
2476 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2477
2478 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002479 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002480 if (VR->getSuperRegion() == R) {
2481 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2482 }
2483 Regions.push_back(VR);
2484 }
2485
2486 state =
2487 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2488 Regions.data() + Regions.size()).getState();
2489 C.addTransition(state);
2490}
2491
Anna Zaks46d01602012-05-18 01:16:10 +00002492bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002493 assert(Sym);
2494 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002495 return (RS && RS->isReleased());
2496}
2497
2498bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2499 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002500
Jordan Rose656fdd52014-01-08 18:46:55 +00002501 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002502 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2503 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002504 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002505
Anna Zaksa1b227b2012-02-08 23:16:56 +00002506 return false;
2507}
2508
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002509void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2510 const Stmt *S) const {
2511 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002512
Devin Coughlin81771732015-09-22 22:47:14 +00002513 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2514 if (RS->isAllocatedOfSizeZero())
2515 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2516 }
2517 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2518 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2519 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002520}
2521
Jordan Rose656fdd52014-01-08 18:46:55 +00002522bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2523
2524 if (isReleased(Sym, C)) {
2525 ReportDoubleDelete(C, Sym);
2526 return true;
2527 }
2528 return false;
2529}
2530
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002531// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002532void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2533 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002534 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002535 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002536 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002537 checkUseZeroAllocated(Sym, C, S);
2538 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002539}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002540
Anna Zaksbb1ef902012-02-11 21:02:35 +00002541// If a symbolic region is assumed to NULL (or another constant), stop tracking
2542// it - assuming that allocation failed on this path.
2543ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2544 SVal Cond,
2545 bool Assumption) const {
2546 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002547 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002548 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002549 ConstraintManager &CMgr = state->getConstraintManager();
2550 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2551 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002552 state = state->remove<RegionState>(I.getKey());
2553 }
2554
Anna Zaksd56c8792012-02-13 18:05:39 +00002555 // Realloc returns 0 when reallocation fails, which means that we should
2556 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002557 ReallocPairsTy RP = state->get<ReallocPairs>();
2558 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002559 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002560 ConstraintManager &CMgr = state->getConstraintManager();
2561 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002562 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002563 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002564
Anna Zaks75cfbb62012-09-12 22:57:34 +00002565 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2566 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2567 if (RS->isReleased()) {
2568 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002569 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002570 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002571 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2572 state = state->remove<RegionState>(ReallocSym);
2573 else
2574 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002575 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002576 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002577 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002578 }
2579
Anna Zaksbb1ef902012-02-11 21:02:35 +00002580 return state;
2581}
2582
Anna Zaks8ebeb642013-06-08 00:29:29 +00002583bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002584 const CallEvent *Call,
2585 ProgramStateRef State,
2586 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002587 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002588 EscapingSymbol = nullptr;
2589
Jordan Rose2a833ca2014-01-15 17:25:15 +00002590 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002591 // TODO: If we want to be more optimistic here, we'll need to make sure that
2592 // regions escape to C++ containers. They seem to do that even now, but for
2593 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002594 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002595 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002596
Jordan Rose742920c2012-07-02 19:27:35 +00002597 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002598 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002599 // If it's not a framework call, or if it takes a callback, assume it
2600 // can free memory.
Anna Zaksfe1eca52015-10-27 20:19:45 +00002601 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002602 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002603
Jordan Rose613f3c02013-03-09 00:59:10 +00002604 // If it's a method we know about, handle it explicitly post-call.
2605 // This should happen before the "freeWhenDone" check below.
2606 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002607 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002608
Jordan Rose613f3c02013-03-09 00:59:10 +00002609 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2610 // about, we can't be sure that the object will use free() to deallocate the
2611 // memory, so we can't model it explicitly. The best we can do is use it to
2612 // decide whether the pointer escapes.
2613 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002614 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002615
Jordan Rose613f3c02013-03-09 00:59:10 +00002616 // If the first selector piece ends with "NoCopy", and there is no
2617 // "freeWhenDone" parameter set to zero, we know ownership is being
2618 // transferred. Again, though, we can't be sure that the object will use
2619 // free() to deallocate the memory, so we can't model it explicitly.
2620 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002621 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002622 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002623
Anna Zaks42908c72012-06-19 05:10:32 +00002624 // If the first selector starts with addPointer, insertPointer,
2625 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2626 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002627 // that the pointers get freed by following the container itself.
2628 if (FirstSlot.startswith("addPointer") ||
2629 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002630 FirstSlot.startswith("replacePointer") ||
2631 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002632 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002633 }
2634
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002635 // We should escape receiver on call to 'init'. This is especially relevant
2636 // to the receiver, as the corresponding symbol is usually not referenced
2637 // after the call.
2638 if (Msg->getMethodFamily() == OMF_init) {
2639 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2640 return true;
2641 }
Anna Zaks737926b2013-05-31 22:39:13 +00002642
Jordan Rose742920c2012-07-02 19:27:35 +00002643 // Otherwise, assume that the method does not free memory.
2644 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002645 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002646 }
2647
Jordan Rose742920c2012-07-02 19:27:35 +00002648 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002649 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002650 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002651 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002652
Jordan Rose742920c2012-07-02 19:27:35 +00002653 ASTContext &ASTC = State->getStateManager().getContext();
2654
2655 // If it's one of the allocation functions we can reason about, we model
2656 // its behavior explicitly.
2657 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002658 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002659
2660 // If it's not a system call, assume it frees memory.
2661 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002662 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002663
2664 // White list the system functions whose arguments escape.
2665 const IdentifierInfo *II = FD->getIdentifier();
2666 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002667 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002668 StringRef FName = II->getName();
2669
Jordan Rose742920c2012-07-02 19:27:35 +00002670 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002671 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002672 if (FName.endswith("NoCopy")) {
2673 // Look for the deallocator argument. We know that the memory ownership
2674 // is not transferred only if the deallocator argument is
2675 // 'kCFAllocatorNull'.
2676 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2677 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2678 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2679 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2680 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002681 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002682 }
2683 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002684 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002685 }
2686
Jordan Rose742920c2012-07-02 19:27:35 +00002687 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002688 // 'closefn' is specified (and if that function does free memory),
2689 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002690 // Currently, we do not inspect the 'closefn' function (PR12101).
2691 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002692 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002693 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002694
2695 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2696 // these leaks might be intentional when setting the buffer for stdio.
2697 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2698 if (FName == "setbuf" || FName =="setbuffer" ||
2699 FName == "setlinebuf" || FName == "setvbuf") {
2700 if (Call->getNumArgs() >= 1) {
2701 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2702 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2703 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2704 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002705 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002706 }
2707 }
2708
2709 // A bunch of other functions which either take ownership of a pointer or
2710 // wrap the result up in a struct or object, meaning it can be freed later.
2711 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2712 // but the Malloc checker cannot differentiate between them. The right way
2713 // of doing this would be to implement a pointer escapes callback.
2714 if (FName == "CGBitmapContextCreate" ||
2715 FName == "CGBitmapContextCreateWithData" ||
2716 FName == "CVPixelBufferCreateWithBytes" ||
2717 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2718 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002719 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002720 }
2721
Anna Zaks03f48332016-01-06 00:32:56 +00002722 if (FName == "postEvent" &&
2723 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2724 return true;
2725 }
2726
2727 if (FName == "postEvent" &&
2728 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2729 return true;
2730 }
2731
Artem Dergachev85c92112016-12-16 12:21:55 +00002732 if (FName == "connectImpl" &&
2733 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2734 return true;
2735 }
2736
Jordan Rose7ab01822012-07-02 19:27:51 +00002737 // Handle cases where we know a buffer's /address/ can escape.
2738 // Note that the above checks handle some special cases where we know that
2739 // even though the address escapes, it's still our responsibility to free the
2740 // buffer.
2741 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002742 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002743
2744 // Otherwise, assume that the function does not free memory.
2745 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002746 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002747}
2748
Anna Zaks333481b2013-03-28 23:15:29 +00002749static bool retTrue(const RefState *RS) {
2750 return true;
2751}
2752
2753static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2754 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2755 RS->getAllocationFamily() == AF_CXXNew);
2756}
2757
Anna Zaksdc154152012-12-20 00:38:25 +00002758ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2759 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002760 const CallEvent *Call,
2761 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002762 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2763}
2764
2765ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2766 const InvalidatedSymbols &Escaped,
2767 const CallEvent *Call,
2768 PointerEscapeKind Kind) const {
2769 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2770 &checkIfNewOrNewArrayFamily);
2771}
2772
2773ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2774 const InvalidatedSymbols &Escaped,
2775 const CallEvent *Call,
2776 PointerEscapeKind Kind,
2777 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002778 // If we know that the call does not free memory, or we want to process the
2779 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002780 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002781 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002782 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2783 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002784 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002785 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002786 }
Anna Zaks3d348342012-02-14 21:55:24 +00002787
Anna Zaksdc154152012-12-20 00:38:25 +00002788 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002789 E = Escaped.end();
2790 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002791 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002792
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002793 if (EscapingSymbol && EscapingSymbol != sym)
2794 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002795
Anna Zaks0d6989b2012-06-22 02:04:31 +00002796 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002797 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2798 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002799 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002800 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2801 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002802 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002803 }
Anna Zaks3d348342012-02-14 21:55:24 +00002804 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002805}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002806
Jordy Rosebf38f202012-03-18 07:43:35 +00002807static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2808 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002809 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2810 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002811
Jordan Rose0c153cb2012-11-02 01:54:06 +00002812 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002813 I != E; ++I) {
2814 SymbolRef sym = I.getKey();
2815 if (!currMap.lookup(sym))
2816 return sym;
2817 }
2818
Craig Topper0dbb7832014-05-27 02:45:47 +00002819 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002820}
2821
David Blaikie0a0c2752017-01-05 17:26:53 +00002822std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2823 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2824 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002825 ProgramStateRef state = N->getState();
2826 ProgramStateRef statePrev = PrevN->getState();
2827
2828 const RefState *RS = state->get<RegionState>(Sym);
2829 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002830 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002831 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002832
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002833 const Stmt *S = PathDiagnosticLocation::getStmt(N);
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002834 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002835 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002836
Jordan Rose681cce92012-07-10 22:07:42 +00002837 // FIXME: We will eventually need to handle non-statement-based events
2838 // (__attribute__((cleanup))).
2839
Anna Zaks2b5bb972012-02-09 06:25:51 +00002840 // Find out if this is an interesting point and what is the kind.
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002841 const char *Msg = nullptr;
2842 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002843 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002844 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002845 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002846 StackHint = new StackHintGeneratorForSymbol(Sym,
2847 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002848 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002849 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002850 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002851 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002852 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002853 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002854 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002855 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002856 Mode = ReallocationFailed;
2857 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002858 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002859 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002860
Jordy Rose21ff76e2012-03-24 03:15:09 +00002861 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2862 // Is it possible to fail two reallocs WITHOUT testing in between?
2863 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2864 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002865 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002866 FailedReallocSymbol = sym;
2867 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002868 }
2869
2870 // We are in a special mode if a reallocation failed later in the path.
2871 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002872 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002873
Jordy Rose21ff76e2012-03-24 03:15:09 +00002874 // Is this is the first appearance of the reallocated symbol?
2875 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002876 // We're at the reallocation point.
2877 Msg = "Attempt to reallocate memory";
2878 StackHint = new StackHintGeneratorForSymbol(Sym,
2879 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002880 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002881 Mode = Normal;
2882 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002883 }
2884
Anna Zaks2b5bb972012-02-09 06:25:51 +00002885 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002886 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002887 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002888
2889 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002890 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002891 N->getLocationContext());
David Blaikie0a0c2752017-01-05 17:26:53 +00002892 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002893}
2894
Anna Zaks263b7e02012-05-02 00:05:20 +00002895void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2896 const char *NL, const char *Sep) const {
2897
2898 RegionStateTy RS = State->get<RegionState>();
2899
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002900 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002901 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002902 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002903 const RefState *RefS = State->get<RegionState>(I.getKey());
2904 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002905 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002906 if (!CheckKind.hasValue())
2907 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002908
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002909 I.getKey()->dumpToStream(Out);
2910 Out << " : ";
2911 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002912 if (CheckKind.hasValue())
2913 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002914 Out << NL;
2915 }
2916 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002917}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002918
Anna Zakse4cfcd42013-04-16 00:22:55 +00002919void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2920 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002921 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002922 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2923 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002924 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2925 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2926 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002927 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00002928 // checker.
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00002929 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002930 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00002931 // FIXME: This does not set the correct name, but without this workaround
2932 // no name will be set at all.
2933 checker->CheckNames[MallocChecker::CK_NewDeleteChecker] =
2934 mgr.getCurrentCheckName();
2935 }
Anna Zakse4cfcd42013-04-16 00:22:55 +00002936}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002937
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002938#define REGISTER_CHECKER(name) \
2939 void ento::register##name(CheckerManager &mgr) { \
2940 registerCStringCheckerBasic(mgr); \
2941 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002942 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2943 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002944 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2945 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2946 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002947
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002948REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002949REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002950REGISTER_CHECKER(MismatchedDeallocatorChecker)