blob: be3289a395068c7c1336fa9a1a0f97b9ac68c38b [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"
Reka Kovacs18775fc2018-06-09 13:03:49 +000033#include "AllocationState.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000034#include <climits>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000035#include <utility>
Anna Zaks199e8e52012-02-22 03:14:20 +000036
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000037using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000038using namespace ento;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000039
40namespace {
41
Anton Yartsev05789592013-03-28 17:05:19 +000042// Used to check correspondence between allocators and deallocators.
43enum AllocationFamily {
44 AF_None,
45 AF_Malloc,
46 AF_CXXNew,
Anna Zaksd79b8402014-10-03 21:48:59 +000047 AF_CXXNewArray,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +000048 AF_IfNameIndex,
Reka Kovacs18775fc2018-06-09 13:03:49 +000049 AF_Alloca,
50 AF_InternalBuffer
Anton Yartsev05789592013-03-28 17:05:19 +000051};
52
Zhongxing Xu1239de12009-12-11 00:55:44 +000053class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000054 enum Kind { // Reference to allocated memory.
55 Allocated,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000056 // Reference to zero-allocated memory.
57 AllocatedOfSizeZero,
Anna Zaks9050ffd2012-06-20 20:57:46 +000058 // Reference to released/freed memory.
59 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000060 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000061 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000062 Relinquished,
63 // We are no longer guaranteed to have observed all manipulations
64 // of this pointer/memory. For example, it could have been
65 // passed as a parameter to an opaque function.
66 Escaped
67 };
Anton Yartsev05789592013-03-28 17:05:19 +000068
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000069 const Stmt *S;
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000070 unsigned K : 3; // Kind enum, but stored as a bitfield.
Ted Kremenek3a0678e2015-09-08 03:50:52 +000071 unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
Anton Yartsev05789592013-03-28 17:05:19 +000072 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000073
Ted Kremenek3a0678e2015-09-08 03:50:52 +000074 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000075 : S(s), K(k), Family(family) {
76 assert(family != AF_None);
77 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000078public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000079 bool isAllocated() const { return K == Allocated; }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000080 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000081 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000082 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000083 bool isEscaped() const { return K == Escaped; }
84 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000085 return (AllocationFamily)Family;
86 }
Anna Zaksd56c8792012-02-13 18:05:39 +000087 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000088
89 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000090 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000091 }
92
Anton Yartsev05789592013-03-28 17:05:19 +000093 static RefState getAllocated(unsigned family, const Stmt *s) {
94 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000095 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000096 static RefState getAllocatedOfSizeZero(const RefState *RS) {
97 return RefState(AllocatedOfSizeZero, RS->getStmt(),
98 RS->getAllocationFamily());
99 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000100 static RefState getReleased(unsigned family, const Stmt *s) {
Anton Yartsev05789592013-03-28 17:05:19 +0000101 return RefState(Released, s, family);
102 }
103 static RefState getRelinquished(unsigned family, const Stmt *s) {
104 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +0000105 }
Anna Zaks93a21a82013-04-09 00:30:28 +0000106 static RefState getEscaped(const RefState *RS) {
107 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
108 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000109
110 void Profile(llvm::FoldingSetNodeID &ID) const {
111 ID.AddInteger(K);
112 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +0000113 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000114 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000115
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000116 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000117 switch (static_cast<Kind>(K)) {
118#define CASE(ID) case ID: OS << #ID; break;
119 CASE(Allocated)
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000120 CASE(AllocatedOfSizeZero)
Jordan Rose6adadb92014-01-23 03:59:01 +0000121 CASE(Released)
122 CASE(Relinquished)
123 CASE(Escaped)
124 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000125 }
126
Alp Tokeref6b0072014-01-04 13:47:14 +0000127 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000128};
129
Anna Zaks75cfbb62012-09-12 22:57:34 +0000130enum ReallocPairKind {
131 RPToBeFreedAfterFailure,
132 // The symbol has been freed when reallocation failed.
133 RPIsFreeOnFailure,
134 // The symbol does not need to be freed after reallocation fails.
135 RPDoNotTrackAfterFailure
136};
137
Anna Zaksfe6eb672012-08-24 02:28:20 +0000138/// \class ReallocPair
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000139/// Stores information about the symbol being reallocated by a call to
Anna Zaksfe6eb672012-08-24 02:28:20 +0000140/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000141struct ReallocPair {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000142 // The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000143 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000144 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000145
Anna Zaks75cfbb62012-09-12 22:57:34 +0000146 ReallocPair(SymbolRef S, ReallocPairKind K) :
147 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000148 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000149 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000150 ID.AddPointer(ReallocatedSym);
151 }
152 bool operator==(const ReallocPair &X) const {
153 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000154 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000155 }
156};
157
Anna Zaksa043d0c2013-01-08 00:25:29 +0000158typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000159
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000160class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000161 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000162 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000163 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000164 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000165 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000166 check::PostStmt<CXXNewExpr>,
Artem Dergachev13b20262018-01-17 23:46:13 +0000167 check::NewAllocator,
Anton Yartsev13df0362013-03-25 01:35:45 +0000168 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000169 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000170 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000171 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000172 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000173{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000174public:
Craig Topper0dbb7832014-05-27 02:45:47 +0000175 MallocChecker()
Anna Zaks30d46682016-03-08 01:21:51 +0000176 : II_alloca(nullptr), II_win_alloca(nullptr), II_malloc(nullptr),
177 II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
178 II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
179 II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr),
180 II_if_nameindex(nullptr), II_if_freenameindex(nullptr),
Anna Zaksbbec97c2017-03-09 00:01:01 +0000181 II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr),
182 II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr),
183 II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr),
Leslie Zhaie3986c52017-04-26 05:33:14 +0000184 II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr),
185 II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr),
186 II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr),
187 II_g_try_realloc_n(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000188
189 /// In pessimistic mode, the checker assumes that it does not know which
190 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000191 enum CheckKind {
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000192 CK_MallocChecker,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000193 CK_NewDeleteChecker,
194 CK_NewDeleteLeaksChecker,
195 CK_MismatchedDeallocatorChecker,
196 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000197 };
198
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000199 enum class MemoryOperationKind {
Anna Zaksd79b8402014-10-03 21:48:59 +0000200 MOK_Allocate,
201 MOK_Free,
202 MOK_Any
203 };
204
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000205 DefaultBool IsOptimistic;
206
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000207 DefaultBool ChecksEnabled[CK_NumCheckKinds];
208 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000209
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000210 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000211 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000212 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
Artem Dergachev13b20262018-01-17 23:46:13 +0000213 void checkNewAllocator(const CXXNewExpr *NE, SVal Target,
214 CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000215 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000216 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000217 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000218 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000219 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000220 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000221 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000222 void checkLocation(SVal l, bool isLoad, const Stmt *S,
223 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000224
225 ProgramStateRef checkPointerEscape(ProgramStateRef State,
226 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000227 const CallEvent *Call,
228 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000229 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
230 const InvalidatedSymbols &Escaped,
231 const CallEvent *Call,
232 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000233
Anna Zaks263b7e02012-05-02 00:05:20 +0000234 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000235 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000236
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000237private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000238 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
239 mutable std::unique_ptr<BugType> BT_DoubleDelete;
240 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
241 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
242 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000243 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000244 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
245 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000246 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
Anna Zaks30d46682016-03-08 01:21:51 +0000247 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
248 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
249 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
250 *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
Anna Zaksbbec97c2017-03-09 00:01:01 +0000251 *II_win_wcsdup, *II_g_malloc, *II_g_malloc0,
252 *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0,
Leslie Zhaie3986c52017-04-26 05:33:14 +0000253 *II_g_try_realloc, *II_g_free, *II_g_memdup,
254 *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n,
255 *II_g_try_malloc_n, *II_g_try_malloc0_n,
256 *II_g_try_realloc_n;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000257 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000258
Anna Zaks3d348342012-02-14 21:55:24 +0000259 void initIdentifierInfo(ASTContext &C) const;
260
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000261 /// Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000262 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000263
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000264 /// Print names of allocators and deallocators.
Anton Yartsev05789592013-03-28 17:05:19 +0000265 ///
266 /// \returns true on success.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000267 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000268 const Expr *E) const;
269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000270 /// Print expected name of an allocator based on the deallocator's
Anton Yartsev05789592013-03-28 17:05:19 +0000271 /// family derived from the DeallocExpr.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000272 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000273 const Expr *DeallocExpr) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000274 /// Print expected name of a deallocator based on the allocator's
Anton Yartsev05789592013-03-28 17:05:19 +0000275 /// family.
276 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
277
Jordan Rose613f3c02013-03-09 00:59:10 +0000278 ///@{
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000279 /// Check if this is one of the functions which can allocate/reallocate memory
Anna Zaks3d348342012-02-14 21:55:24 +0000280 /// pointed to by one of its arguments.
281 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000282 bool isCMemFunction(const FunctionDecl *FD,
283 ASTContext &C,
284 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000285 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000286 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000287 ///@}
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000288
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000289 /// Process C++ operator new()'s allocation, which is the part of C++
Artem Dergachev13b20262018-01-17 23:46:13 +0000290 /// new-expression that goes before the constructor.
291 void processNewAllocation(const CXXNewExpr *NE, CheckerContext &C,
292 SVal Target) const;
293
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000294 /// Perform a zero-allocation check.
Artem Dergachev13b20262018-01-17 23:46:13 +0000295 /// The optional \p RetVal parameter specifies the newly allocated pointer
296 /// value; if unspecified, the value of expression \p E is used.
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000297 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
298 const unsigned AllocationSizeArg,
Artem Dergachev13b20262018-01-17 23:46:13 +0000299 ProgramStateRef State,
300 Optional<SVal> RetVal = None) const;
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000301
Richard Smith852e9ce2013-11-27 01:46:48 +0000302 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
303 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000304 const OwnershipAttr* Att,
305 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000306 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000307 const Expr *SizeEx, SVal Init,
308 ProgramStateRef State,
309 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000310 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000311 SVal SizeEx, SVal Init,
312 ProgramStateRef State,
313 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000314
Gabor Horvath73040272016-09-19 20:39:52 +0000315 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
Artem Dergachev13b20262018-01-17 23:46:13 +0000316 ProgramStateRef State, SVal Target);
Gabor Horvath73040272016-09-19 20:39:52 +0000317
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000318 // Check if this malloc() for special flags. At present that means M_ZERO or
319 // __GFP_ZERO (in which case, treat it like calloc).
320 llvm::Optional<ProgramStateRef>
321 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
322 const ProgramStateRef &State) const;
323
Anna Zaks40a7eb32012-02-22 19:24:52 +0000324 /// Update the RefState to reflect the new memory allocation.
Artem Dergachev13b20262018-01-17 23:46:13 +0000325 /// The optional \p RetVal parameter specifies the newly allocated pointer
326 /// value; if unspecified, the value of expression \p E is used.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000327 static ProgramStateRef
Anton Yartsev05789592013-03-28 17:05:19 +0000328 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
Artem Dergachev13b20262018-01-17 23:46:13 +0000329 AllocationFamily Family = AF_Malloc,
330 Optional<SVal> RetVal = None);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000331
332 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000333 const OwnershipAttr* Att,
334 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000335 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000336 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000337 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000338 bool &ReleasedAllocated,
339 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000340 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
341 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000342 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000343 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000344 bool &ReleasedAllocated,
345 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000346
Leslie Zhaie3986c52017-04-26 05:33:14 +0000347 ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE,
348 bool FreesMemOnFailure,
349 ProgramStateRef State,
350 bool SuffixWithN = false) const;
351 static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
352 const Expr *BlockBytes);
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000353 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
354 ProgramStateRef State);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000355
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000356 ///Check if the memory associated with this symbol was released.
Anna Zaks46d01602012-05-18 01:16:10 +0000357 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
358
Anton Yartsev13df0362013-03-25 01:35:45 +0000359 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000360
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000361 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000362 const Stmt *S) const;
363
Jordan Rose656fdd52014-01-08 18:46:55 +0000364 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
365
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000366 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000367 /// "interesting" and should be modeled explicitly.
368 ///
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000369 /// \param [out] EscapingSymbol A function might not free memory in general,
Anna Zaks8ebeb642013-06-08 00:29:29 +0000370 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000371 /// returned and the single escaping symbol is returned through the out
372 /// parameter.
373 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000374 /// We assume that pointers do not escape through calls to system functions
375 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000376 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000377 ProgramStateRef State,
378 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000379
Anna Zaks333481b2013-03-28 23:15:29 +0000380 // Implementation of the checkPointerEscape callabcks.
381 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
382 const InvalidatedSymbols &Escaped,
383 const CallEvent *Call,
384 PointerEscapeKind Kind,
385 bool(*CheckRefState)(const RefState*)) const;
386
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000387 ///@{
388 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000389 /// Sets CheckKind to the kind of the checker responsible for this
390 /// family/call/symbol.
Anton Yartsev2487dd62015-03-10 22:24:21 +0000391 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
392 bool IsALeakCheck = false) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000393 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000394 const Stmt *AllocDeallocStmt,
395 bool IsALeakCheck = false) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000396 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000397 bool IsALeakCheck = false) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000398 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000399 static bool SummarizeValue(raw_ostream &os, SVal V);
400 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000401 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +0000402 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000403 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
404 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000405 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000406 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000407 SymbolRef Sym, bool OwnershipTransferred) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000408 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
409 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000410 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000411 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
412 SymbolRef Sym) const;
413 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000414 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000415
Jordan Rose656fdd52014-01-08 18:46:55 +0000416 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
417
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000418 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
419 SymbolRef Sym) const;
420
Daniel Marjamakia43a8f52017-05-02 11:46:12 +0000421 void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
422 SourceRange Range, const Expr *FreeExpr) const;
423
Anna Zaksdf901a42012-02-23 21:38:21 +0000424 /// Find the location of the allocation for Sym on the path leading to the
425 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000426 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
427 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000428
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000429 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
430
Anna Zaks2b5bb972012-02-09 06:25:51 +0000431 /// The bug visitor which allows us to print extra diagnostics along the
432 /// BugReport path. For example, showing the allocation site of the leaked
433 /// region.
George Karpenkov70ec1dd2018-06-26 21:12:08 +0000434 class MallocBugVisitor final : public BugReporterVisitor {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000435 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000436 enum NotificationMode {
437 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000438 ReallocationFailed
439 };
440
Anna Zaks2b5bb972012-02-09 06:25:51 +0000441 // The allocated region symbol tracked by the main analysis.
442 SymbolRef Sym;
443
Anna Zaks62cce9e2012-05-10 01:37:40 +0000444 // The mode we are in, i.e. what kind of diagnostics will be emitted.
445 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000446
Anna Zaks62cce9e2012-05-10 01:37:40 +0000447 // A symbol from when the primary region should have been reallocated.
448 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000449
Artem Dergachev5337efc2018-02-27 21:19:33 +0000450 // A C++ destructor stack frame in which memory was released. Used for
451 // miscellaneous false positive suppression.
452 const StackFrameContext *ReleaseDestructorLC;
453
Anna Zaks62cce9e2012-05-10 01:37:40 +0000454 bool IsLeak;
455
456 public:
457 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Artem Dergachev5337efc2018-02-27 21:19:33 +0000458 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr),
459 ReleaseDestructorLC(nullptr), IsLeak(isLeak) {}
460
461 static void *getTag() {
462 static int Tag = 0;
463 return &Tag;
464 }
Jordy Rose21ff76e2012-03-24 03:15:09 +0000465
Craig Topperfb6b25b2014-03-15 04:29:04 +0000466 void Profile(llvm::FoldingSetNodeID &ID) const override {
Artem Dergachev5337efc2018-02-27 21:19:33 +0000467 ID.AddPointer(getTag());
Anna Zaks2b5bb972012-02-09 06:25:51 +0000468 ID.AddPointer(Sym);
469 }
470
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000471 inline bool isAllocated(const RefState *S, const RefState *SPrev,
472 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000473 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000474 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000475 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
476 (!SPrev || !(SPrev->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000477 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000478 }
479
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000480 inline bool isReleased(const RefState *S, const RefState *SPrev,
481 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000482 // Did not track -> released. Other state (allocated) -> released.
Reka Kovacs8707cd12018-07-07 17:22:45 +0000483 // The statement associated with the release might be missing.
484 bool IsReleased = (S && S->isReleased()) &&
485 (!SPrev || !SPrev->isReleased());
486 assert(!IsReleased ||
487 (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt))) ||
488 (!Stmt && S->getAllocationFamily() == AF_InternalBuffer));
489 return IsReleased;
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000490 }
491
Anna Zaks0d6989b2012-06-22 02:04:31 +0000492 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
493 const Stmt *Stmt) {
494 // Did not track -> relinquished. Other state (allocated) -> relinquished.
495 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
496 isa<ObjCPropertyRefExpr>(Stmt)) &&
497 (S && S->isRelinquished()) &&
498 (!SPrev || !SPrev->isRelinquished()));
499 }
500
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000501 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
502 const Stmt *Stmt) {
503 // If the expression is not a call, and the state change is
504 // released -> allocated, it must be the realloc return value
505 // check. If we have to handle more cases here, it might be cleaner just
506 // to track this extra bit in the state itself.
507 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000508 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
509 (SPrev && !(SPrev->isAllocated() ||
510 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000511 }
512
David Blaikie0a0c2752017-01-05 17:26:53 +0000513 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
514 const ExplodedNode *PrevN,
515 BugReporterContext &BRC,
516 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000517
George Karpenkov70ec1dd2018-06-26 21:12:08 +0000518 std::shared_ptr<PathDiagnosticPiece>
David Blaikied15481c2014-08-29 18:18:43 +0000519 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
520 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000521 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000522 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000523
524 PathDiagnosticLocation L =
525 PathDiagnosticLocation::createEndOfPath(EndPathNode,
526 BRC.getSourceManager());
527 // Do not add the statement itself as a range in case of leak.
George Karpenkov70ec1dd2018-06-26 21:12:08 +0000528 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
David Blaikied15481c2014-08-29 18:18:43 +0000529 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000530 }
531
Anna Zakscba4f292012-03-16 23:24:20 +0000532 private:
533 class StackHintGeneratorForReallocationFailed
534 : public StackHintGeneratorForSymbol {
535 public:
536 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
537 : StackHintGeneratorForSymbol(S, M) {}
538
Craig Topperfb6b25b2014-03-15 04:29:04 +0000539 std::string getMessageForArg(const Expr *ArgE,
540 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000541 // Printed parameters start at 1, not 0.
542 ++ArgIndex;
543
Anna Zakscba4f292012-03-16 23:24:20 +0000544 SmallString<200> buf;
545 llvm::raw_svector_ostream os(buf);
546
Jordan Rosec102b352012-09-22 01:24:42 +0000547 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
548 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000549
550 return os.str();
551 }
552
Craig Topperfb6b25b2014-03-15 04:29:04 +0000553 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000554 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000555 }
556 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000557 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000558};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000559} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000560
Jordan Rose0c153cb2012-11-02 01:54:06 +0000561REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
562REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Devin Coughlin81771732015-09-22 22:47:14 +0000563REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000564
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000565// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000566// the free function.
567REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
568
Anna Zaksbb1ef902012-02-11 21:02:35 +0000569namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000570class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000571 ProgramStateRef state;
572public:
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000573 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
Anna Zaksbb1ef902012-02-11 21:02:35 +0000574 ProgramStateRef getState() const { return state; }
575
Craig Topperfb6b25b2014-03-15 04:29:04 +0000576 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000577 state = state->remove<RegionState>(sym);
578 return true;
579 }
580};
581} // end anonymous namespace
582
Anna Zaks3d348342012-02-14 21:55:24 +0000583void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000584 if (II_malloc)
585 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000586 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000587 II_malloc = &Ctx.Idents.get("malloc");
588 II_free = &Ctx.Idents.get("free");
589 II_realloc = &Ctx.Idents.get("realloc");
590 II_reallocf = &Ctx.Idents.get("reallocf");
591 II_calloc = &Ctx.Idents.get("calloc");
592 II_valloc = &Ctx.Idents.get("valloc");
593 II_strdup = &Ctx.Idents.get("strdup");
594 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaks30d46682016-03-08 01:21:51 +0000595 II_wcsdup = &Ctx.Idents.get("wcsdup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000596 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000597 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
598 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaks30d46682016-03-08 01:21:51 +0000599
600 //MSVC uses `_`-prefixed instead, so we check for them too.
601 II_win_strdup = &Ctx.Idents.get("_strdup");
602 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
603 II_win_alloca = &Ctx.Idents.get("_alloca");
Anna Zaksbbec97c2017-03-09 00:01:01 +0000604
605 // Glib
606 II_g_malloc = &Ctx.Idents.get("g_malloc");
607 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
608 II_g_realloc = &Ctx.Idents.get("g_realloc");
609 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
610 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
611 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
612 II_g_free = &Ctx.Idents.get("g_free");
613 II_g_memdup = &Ctx.Idents.get("g_memdup");
Leslie Zhaie3986c52017-04-26 05:33:14 +0000614 II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
615 II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
616 II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
617 II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
618 II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
619 II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000620}
621
Anna Zaks3d348342012-02-14 21:55:24 +0000622bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000623 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000624 return true;
625
Anna Zaksd79b8402014-10-03 21:48:59 +0000626 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000627 return true;
628
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000629 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
630 return true;
631
Anton Yartsev13df0362013-03-25 01:35:45 +0000632 if (isStandardNewDelete(FD, C))
633 return true;
634
Anna Zaks46d01602012-05-18 01:16:10 +0000635 return false;
636}
637
Anna Zaksd79b8402014-10-03 21:48:59 +0000638bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
639 ASTContext &C,
640 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000641 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000642 if (!FD)
643 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000644
Anna Zaksd79b8402014-10-03 21:48:59 +0000645 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
646 MemKind == MemoryOperationKind::MOK_Free);
647 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
648 MemKind == MemoryOperationKind::MOK_Allocate);
649
Jordan Rose6cd16c52012-07-10 23:13:01 +0000650 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000651 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000652 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000653
Anna Zaksd79b8402014-10-03 21:48:59 +0000654 if (Family == AF_Malloc && CheckFree) {
Anna Zaksbbec97c2017-03-09 00:01:01 +0000655 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
656 FunI == II_g_free)
Anna Zaksd79b8402014-10-03 21:48:59 +0000657 return true;
658 }
659
660 if (Family == AF_Malloc && CheckAlloc) {
661 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
662 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
Anna Zaks30d46682016-03-08 01:21:51 +0000663 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
Anna Zaksbbec97c2017-03-09 00:01:01 +0000664 FunI == II_win_wcsdup || FunI == II_kmalloc ||
665 FunI == II_g_malloc || FunI == II_g_malloc0 ||
666 FunI == II_g_realloc || FunI == II_g_try_malloc ||
667 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
Leslie Zhaie3986c52017-04-26 05:33:14 +0000668 FunI == II_g_memdup || FunI == II_g_malloc_n ||
669 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
670 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
671 FunI == II_g_try_realloc_n)
Anna Zaksd79b8402014-10-03 21:48:59 +0000672 return true;
673 }
674
675 if (Family == AF_IfNameIndex && CheckFree) {
676 if (FunI == II_if_freenameindex)
677 return true;
678 }
679
680 if (Family == AF_IfNameIndex && CheckAlloc) {
681 if (FunI == II_if_nameindex)
682 return true;
683 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000684
685 if (Family == AF_Alloca && CheckAlloc) {
Anna Zaks30d46682016-03-08 01:21:51 +0000686 if (FunI == II_alloca || FunI == II_win_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000687 return true;
688 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000689 }
Anna Zaks3d348342012-02-14 21:55:24 +0000690
Anna Zaksd79b8402014-10-03 21:48:59 +0000691 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000692 return false;
693
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000694 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000695 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
696 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
697 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
698 if (CheckFree)
699 return true;
700 } else if (OwnKind == OwnershipAttr::Returns) {
701 if (CheckAlloc)
702 return true;
703 }
704 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000705 }
Anna Zaks3d348342012-02-14 21:55:24 +0000706
Anna Zaks3d348342012-02-14 21:55:24 +0000707 return false;
708}
709
Anton Yartsev8b662702013-03-28 16:10:38 +0000710// Tells if the callee is one of the following:
711// 1) A global non-placement new/delete operator function.
712// 2) A global placement operator function with the single placement argument
713// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000714bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
715 ASTContext &C) const {
716 if (!FD)
717 return false;
718
719 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000720 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000721 Kind != OO_Delete && Kind != OO_Array_Delete)
722 return false;
723
Anton Yartsev8b662702013-03-28 16:10:38 +0000724 // Skip all operator new/delete methods.
725 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000726 return false;
727
728 // Return true if tested operator is a standard placement nothrow operator.
729 if (FD->getNumParams() == 2) {
730 QualType T = FD->getParamDecl(1)->getType();
731 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
732 return II->getName().equals("nothrow_t");
733 }
734
735 // Skip placement operators.
736 if (FD->getNumParams() != 1 || FD->isVariadic())
737 return false;
738
739 // One of the standard new/new[]/delete/delete[] non-placement operators.
740 return true;
741}
742
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000743llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
744 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
745 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
746 //
747 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
748 //
749 // One of the possible flags is M_ZERO, which means 'give me back an
750 // allocation which is already zeroed', like calloc.
751
752 // 2-argument kmalloc(), as used in the Linux kernel:
753 //
754 // void *kmalloc(size_t size, gfp_t flags);
755 //
756 // Has the similar flag value __GFP_ZERO.
757
758 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
759 // code could be shared.
760
761 ASTContext &Ctx = C.getASTContext();
762 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
763
764 if (!KernelZeroFlagVal.hasValue()) {
765 if (OS == llvm::Triple::FreeBSD)
766 KernelZeroFlagVal = 0x0100;
767 else if (OS == llvm::Triple::NetBSD)
768 KernelZeroFlagVal = 0x0002;
769 else if (OS == llvm::Triple::OpenBSD)
770 KernelZeroFlagVal = 0x0008;
771 else if (OS == llvm::Triple::Linux)
772 // __GFP_ZERO
773 KernelZeroFlagVal = 0x8000;
774 else
775 // FIXME: We need a more general way of getting the M_ZERO value.
776 // See also: O_CREAT in UnixAPIChecker.cpp.
777
778 // Fall back to normal malloc behavior on platforms where we don't
779 // know M_ZERO.
780 return None;
781 }
782
783 // We treat the last argument as the flags argument, and callers fall-back to
784 // normal malloc on a None return. This works for the FreeBSD kernel malloc
785 // as well as Linux kmalloc.
786 if (CE->getNumArgs() < 2)
787 return None;
788
789 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
George Karpenkovd703ec92018-01-17 20:27:29 +0000790 const SVal V = C.getSVal(FlagsEx);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000791 if (!V.getAs<NonLoc>()) {
792 // The case where 'V' can be a location can only be due to a bad header,
793 // so in this case bail out.
794 return None;
795 }
796
797 NonLoc Flags = V.castAs<NonLoc>();
798 NonLoc ZeroFlag = C.getSValBuilder()
799 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
800 .castAs<NonLoc>();
801 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
802 Flags, ZeroFlag,
803 FlagsEx->getType());
804 if (MaskedFlagsUC.isUnknownOrUndef())
805 return None;
806 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
807
808 // Check if maskedFlags is non-zero.
809 ProgramStateRef TrueState, FalseState;
810 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
811
812 // If M_ZERO is set, treat this like calloc (initialized).
813 if (TrueState && !FalseState) {
814 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
815 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
816 }
817
818 return None;
819}
820
Leslie Zhaie3986c52017-04-26 05:33:14 +0000821SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
822 const Expr *BlockBytes) {
823 SValBuilder &SB = C.getSValBuilder();
824 SVal BlocksVal = C.getSVal(Blocks);
825 SVal BlockBytesVal = C.getSVal(BlockBytes);
826 ProgramStateRef State = C.getState();
827 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
828 SB.getContext().getSizeType());
829 return TotalSize;
830}
831
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000832void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000833 if (C.wasInlined)
834 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000835
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000836 const FunctionDecl *FD = C.getCalleeDecl(CE);
837 if (!FD)
838 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000839
Anna Zaks40a7eb32012-02-22 19:24:52 +0000840 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000841 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000842
843 if (FD->getKind() == Decl::Function) {
844 initIdentifierInfo(C.getASTContext());
845 IdentifierInfo *FunI = FD->getIdentifier();
846
Anna Zaksbbec97c2017-03-09 00:01:01 +0000847 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000848 if (CE->getNumArgs() < 1)
849 return;
850 if (CE->getNumArgs() < 3) {
851 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000852 if (CE->getNumArgs() == 1)
853 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000854 } else if (CE->getNumArgs() == 3) {
855 llvm::Optional<ProgramStateRef> MaybeState =
856 performKernelMalloc(CE, C, State);
857 if (MaybeState.hasValue())
858 State = MaybeState.getValue();
859 else
860 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
861 }
862 } else if (FunI == II_kmalloc) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000863 if (CE->getNumArgs() < 1)
864 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000865 llvm::Optional<ProgramStateRef> MaybeState =
866 performKernelMalloc(CE, C, State);
867 if (MaybeState.hasValue())
868 State = MaybeState.getValue();
869 else
870 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
871 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000872 if (CE->getNumArgs() < 1)
873 return;
874 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000875 State = ProcessZeroAllocation(C, CE, 0, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000876 } else if (FunI == II_realloc || FunI == II_g_realloc ||
877 FunI == II_g_try_realloc) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000878 State = ReallocMemAux(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000879 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000880 } else if (FunI == II_reallocf) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000881 State = ReallocMemAux(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000882 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000883 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000884 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000885 State = ProcessZeroAllocation(C, CE, 0, State);
886 State = ProcessZeroAllocation(C, CE, 1, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000887 } else if (FunI == II_free || FunI == II_g_free) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000888 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaks30d46682016-03-08 01:21:51 +0000889 } else if (FunI == II_strdup || FunI == II_win_strdup ||
890 FunI == II_wcsdup || FunI == II_win_wcsdup) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000891 State = MallocUpdateRefState(C, CE, State);
892 } else if (FunI == II_strndup) {
893 State = MallocUpdateRefState(C, CE, State);
Anna Zaks30d46682016-03-08 01:21:51 +0000894 } else if (FunI == II_alloca || FunI == II_win_alloca) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000895 if (CE->getNumArgs() < 1)
896 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000897 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
898 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000899 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000900 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000901 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000902 // as distinct from new/new[]/delete/delete[] expressions that are
903 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000904 // CXXDeleteExpr.
905 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000906 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000907 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
908 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000909 State = ProcessZeroAllocation(C, CE, 0, State);
910 }
911 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000912 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
913 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000914 State = ProcessZeroAllocation(C, CE, 0, State);
915 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000916 else if (K == OO_Delete || K == OO_Array_Delete)
917 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
918 else
919 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000920 } else if (FunI == II_if_nameindex) {
921 // Should we model this differently? We can allocate a fixed number of
922 // elements with zeros in the last one.
923 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
924 AF_IfNameIndex);
925 } else if (FunI == II_if_freenameindex) {
926 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000927 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
928 if (CE->getNumArgs() < 1)
929 return;
930 SValBuilder &svalBuilder = C.getSValBuilder();
931 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
932 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
933 State = ProcessZeroAllocation(C, CE, 0, State);
934 } else if (FunI == II_g_memdup) {
935 if (CE->getNumArgs() < 2)
936 return;
937 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
938 State = ProcessZeroAllocation(C, CE, 1, State);
Leslie Zhaie3986c52017-04-26 05:33:14 +0000939 } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
940 FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
941 if (CE->getNumArgs() < 2)
942 return;
943 SVal Init = UndefinedVal();
944 if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
945 SValBuilder &SB = C.getSValBuilder();
946 Init = SB.makeZeroVal(SB.getContext().CharTy);
947 }
948 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
949 State = MallocMemAux(C, CE, TotalSize, Init, State);
950 State = ProcessZeroAllocation(C, CE, 0, State);
951 State = ProcessZeroAllocation(C, CE, 1, State);
952 } else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
953 if (CE->getNumArgs() < 3)
954 return;
955 State = ReallocMemAux(C, CE, false, State, true);
956 State = ProcessZeroAllocation(C, CE, 1, State);
957 State = ProcessZeroAllocation(C, CE, 2, State);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000958 }
959 }
960
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000961 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000962 // Check all the attributes, if there are any.
963 // There can be multiple of these attributes.
964 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000965 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
966 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000967 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000968 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000969 break;
970 case OwnershipAttr::Takes:
971 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000972 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000973 break;
974 }
975 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000976 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000977 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000978}
979
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000980// Performs a 0-sized allocations check.
Artem Dergachev13b20262018-01-17 23:46:13 +0000981ProgramStateRef MallocChecker::ProcessZeroAllocation(
982 CheckerContext &C, const Expr *E, const unsigned AllocationSizeArg,
983 ProgramStateRef State, Optional<SVal> RetVal) const {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000984 if (!State)
985 return nullptr;
986
Artem Dergachev13b20262018-01-17 23:46:13 +0000987 if (!RetVal)
988 RetVal = C.getSVal(E);
989
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000990 const Expr *Arg = nullptr;
991
992 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
993 Arg = CE->getArg(AllocationSizeArg);
994 }
995 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
996 if (NE->isArray())
997 Arg = NE->getArraySize();
998 else
999 return State;
1000 }
1001 else
1002 llvm_unreachable("not a CallExpr or CXXNewExpr");
1003
1004 assert(Arg);
1005
George Karpenkovd703ec92018-01-17 20:27:29 +00001006 Optional<DefinedSVal> DefArgVal = C.getSVal(Arg).getAs<DefinedSVal>();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001007
1008 if (!DefArgVal)
1009 return State;
1010
1011 // Check if the allocation size is 0.
1012 ProgramStateRef TrueState, FalseState;
1013 SValBuilder &SvalBuilder = C.getSValBuilder();
1014 DefinedSVal Zero =
1015 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1016
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001017 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001018 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1019
1020 if (TrueState && !FalseState) {
Artem Dergachev13b20262018-01-17 23:46:13 +00001021 SymbolRef Sym = RetVal->getAsLocSymbol();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001022 if (!Sym)
1023 return State;
1024
1025 const RefState *RS = State->get<RegionState>(Sym);
Devin Coughlin81771732015-09-22 22:47:14 +00001026 if (RS) {
1027 if (RS->isAllocated())
1028 return TrueState->set<RegionState>(Sym,
1029 RefState::getAllocatedOfSizeZero(RS));
1030 else
1031 return State;
1032 } else {
1033 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1034 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1035 // tracked. Add zero-reallocated Sym to the state to catch references
1036 // to zero-allocated memory.
1037 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1038 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001039 }
1040
1041 // Assume the value is non-zero going forward.
1042 assert(FalseState);
1043 return FalseState;
1044}
1045
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001046static QualType getDeepPointeeType(QualType T) {
1047 QualType Result = T, PointeeType = T->getPointeeType();
1048 while (!PointeeType.isNull()) {
1049 Result = PointeeType;
1050 PointeeType = PointeeType->getPointeeType();
1051 }
1052 return Result;
1053}
1054
1055static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1056
1057 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1058 if (!ConstructE)
1059 return false;
1060
1061 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1062 return false;
1063
1064 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1065
1066 // Iterate over the constructor parameters.
David Majnemer59f77922016-06-24 04:05:48 +00001067 for (const auto *CtorParam : CtorD->parameters()) {
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001068
1069 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1070 if (CtorParamPointeeT.isNull())
1071 continue;
1072
1073 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1074
1075 if (CtorParamPointeeT->getAsCXXRecordDecl())
1076 return true;
1077 }
1078
1079 return false;
1080}
1081
Artem Dergachev13b20262018-01-17 23:46:13 +00001082void MallocChecker::processNewAllocation(const CXXNewExpr *NE,
1083 CheckerContext &C,
1084 SVal Target) const {
Anton Yartsev13df0362013-03-25 01:35:45 +00001085 if (NE->getNumPlacementArgs())
1086 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1087 E = NE->placement_arg_end(); I != E; ++I)
1088 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1089 checkUseAfterFree(Sym, C, *I);
1090
Anton Yartsev13df0362013-03-25 01:35:45 +00001091 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1092 return;
1093
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001094 ParentMap &PM = C.getLocationContext()->getParentMap();
1095 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1096 return;
1097
Anton Yartsev13df0362013-03-25 01:35:45 +00001098 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001099 // The return value from operator new is bound to a specified initialization
1100 // value (if any) and we don't want to loose this value. So we call
1101 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +00001102 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001103 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Artem Dergachev13b20262018-01-17 23:46:13 +00001104 : AF_CXXNew, Target);
1105 State = addExtentSize(C, NE, State, Target);
1106 State = ProcessZeroAllocation(C, NE, 0, State, Target);
Anton Yartsev13df0362013-03-25 01:35:45 +00001107 C.addTransition(State);
1108}
1109
Artem Dergachev13b20262018-01-17 23:46:13 +00001110void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1111 CheckerContext &C) const {
1112 if (!C.getAnalysisManager().getAnalyzerOptions().mayInlineCXXAllocator())
1113 processNewAllocation(NE, C, C.getSVal(NE));
1114}
1115
1116void MallocChecker::checkNewAllocator(const CXXNewExpr *NE, SVal Target,
1117 CheckerContext &C) const {
1118 if (!C.wasInlined)
1119 processNewAllocation(NE, C, Target);
1120}
1121
Gabor Horvath73040272016-09-19 20:39:52 +00001122// Sets the extent value of the MemRegion allocated by
1123// new expression NE to its size in Bytes.
1124//
1125ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1126 const CXXNewExpr *NE,
Artem Dergachev13b20262018-01-17 23:46:13 +00001127 ProgramStateRef State,
1128 SVal Target) {
Gabor Horvath73040272016-09-19 20:39:52 +00001129 if (!State)
1130 return nullptr;
1131 SValBuilder &svalBuilder = C.getSValBuilder();
1132 SVal ElementCount;
Gabor Horvath73040272016-09-19 20:39:52 +00001133 const SubRegion *Region;
1134 if (NE->isArray()) {
1135 const Expr *SizeExpr = NE->getArraySize();
George Karpenkovd703ec92018-01-17 20:27:29 +00001136 ElementCount = C.getSVal(SizeExpr);
Gabor Horvath73040272016-09-19 20:39:52 +00001137 // Store the extent size for the (symbolic)region
1138 // containing the elements.
Artem Dergachev13b20262018-01-17 23:46:13 +00001139 Region = Target.getAsRegion()
Gabor Horvath73040272016-09-19 20:39:52 +00001140 ->getAs<SubRegion>()
Artem Dergachev13b20262018-01-17 23:46:13 +00001141 ->StripCasts()
Gabor Horvath73040272016-09-19 20:39:52 +00001142 ->getAs<SubRegion>();
1143 } else {
1144 ElementCount = svalBuilder.makeIntVal(1, true);
Artem Dergachev13b20262018-01-17 23:46:13 +00001145 Region = Target.getAsRegion()->getAs<SubRegion>();
Gabor Horvath73040272016-09-19 20:39:52 +00001146 }
1147 assert(Region);
1148
1149 // Set the region's extent equal to the Size in Bytes.
1150 QualType ElementType = NE->getAllocatedType();
1151 ASTContext &AstContext = C.getASTContext();
1152 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1153
Devin Coughline3b75de2016-12-16 18:41:40 +00001154 if (ElementCount.getAs<NonLoc>()) {
Gabor Horvath73040272016-09-19 20:39:52 +00001155 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1156 // size in Bytes = ElementCount*TypeSize
1157 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1158 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1159 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1160 svalBuilder.getArrayIndexType());
1161 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1162 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1163 State = State->assume(extentMatchesSize, true);
1164 }
1165 return State;
1166}
1167
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001168void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001169 CheckerContext &C) const {
1170
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001171 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +00001172 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1173 checkUseAfterFree(Sym, C, DE->getArgument());
1174
Anton Yartsev13df0362013-03-25 01:35:45 +00001175 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1176 return;
1177
1178 ProgramStateRef State = C.getState();
1179 bool ReleasedAllocated;
1180 State = FreeMemAux(C, DE->getArgument(), DE, State,
1181 /*Hold*/false, ReleasedAllocated);
1182
1183 C.addTransition(State);
1184}
1185
Jordan Rose613f3c02013-03-09 00:59:10 +00001186static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1187 // If the first selector piece is one of the names below, assume that the
1188 // object takes ownership of the memory, promising to eventually deallocate it
1189 // with free().
1190 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1191 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1192 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
Alexander Kornienko9c104902015-12-28 13:06:58 +00001193 return FirstSlot == "dataWithBytesNoCopy" ||
1194 FirstSlot == "initWithBytesNoCopy" ||
1195 FirstSlot == "initWithCharactersNoCopy";
Anna Zaks0d6989b2012-06-22 02:04:31 +00001196}
1197
Jordan Rose613f3c02013-03-09 00:59:10 +00001198static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1199 Selector S = Call.getSelector();
1200
1201 // FIXME: We should not rely on fully-constrained symbols being folded.
1202 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1203 if (S.getNameForSlot(i).equals("freeWhenDone"))
1204 return !Call.getArgSVal(i).isZeroConstant();
1205
1206 return None;
1207}
1208
Anna Zaks67291b92012-11-13 03:18:01 +00001209void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1210 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001211 if (C.wasInlined)
1212 return;
1213
Jordan Rose613f3c02013-03-09 00:59:10 +00001214 if (!isKnownDeallocObjCMethodName(Call))
1215 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001216
Jordan Rose613f3c02013-03-09 00:59:10 +00001217 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1218 if (!*FreeWhenDone)
1219 return;
1220
1221 bool ReleasedAllocatedMemory;
1222 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1223 Call.getOriginExpr(), C.getState(),
1224 /*Hold=*/true, ReleasedAllocatedMemory,
1225 /*RetNullOnFailure=*/true);
1226
1227 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001228}
1229
Richard Smith852e9ce2013-11-27 01:46:48 +00001230ProgramStateRef
1231MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001232 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001233 ProgramStateRef State) const {
1234 if (!State)
1235 return nullptr;
1236
Richard Smith852e9ce2013-11-27 01:46:48 +00001237 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001238 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001239
Joel E. Dennya6555112018-04-02 19:43:34 +00001240 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001241 if (I != E) {
Joel E. Denny81508102018-03-13 14:51:22 +00001242 return MallocMemAux(C, CE, CE->getArg(I->getASTIndex()), UndefinedVal(),
1243 State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001244 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001245 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1246}
1247
1248ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1249 const CallExpr *CE,
1250 const Expr *SizeEx, SVal Init,
1251 ProgramStateRef State,
1252 AllocationFamily Family) {
1253 if (!State)
1254 return nullptr;
1255
George Karpenkovd703ec92018-01-17 20:27:29 +00001256 return MallocMemAux(C, CE, C.getSVal(SizeEx), Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001257}
1258
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001259ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001260 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001261 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001262 ProgramStateRef State,
1263 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001264 if (!State)
1265 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001266
Jordan Rosef69e65f2014-09-05 16:33:51 +00001267 // We expect the malloc functions to return a pointer.
1268 if (!Loc::isLocType(CE->getType()))
1269 return nullptr;
1270
Anna Zaks3563fde2012-06-07 03:57:32 +00001271 // Bind the return value to the symbolic value from the heap region.
1272 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1273 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001274 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001275 SValBuilder &svalBuilder = C.getSValBuilder();
1276 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001277 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1278 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001279 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001280
Jordy Rose674bd552010-07-04 00:00:41 +00001281 // Fill the region with the initialization value.
Artem Dergachev806486c2018-05-04 21:56:51 +00001282 State = State->bindDefaultInitial(RetVal, Init, LCtx);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001283
Jordy Rose674bd552010-07-04 00:00:41 +00001284 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001285 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001286 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001287 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001288 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001289 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001290 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001291 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001292 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001293 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001294 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001295
Anton Yartsev05789592013-03-28 17:05:19 +00001296 State = State->assume(extentMatchesSize, true);
1297 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001298 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001299
Anton Yartsev05789592013-03-28 17:05:19 +00001300 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001301}
1302
1303ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001304 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001305 ProgramStateRef State,
Artem Dergachev13b20262018-01-17 23:46:13 +00001306 AllocationFamily Family,
1307 Optional<SVal> RetVal) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001308 if (!State)
1309 return nullptr;
1310
Anna Zaks40a7eb32012-02-22 19:24:52 +00001311 // Get the return value.
Artem Dergachev13b20262018-01-17 23:46:13 +00001312 if (!RetVal)
1313 RetVal = C.getSVal(E);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001314
1315 // We expect the malloc functions to return a pointer.
Artem Dergachev13b20262018-01-17 23:46:13 +00001316 if (!RetVal->getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001317 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001318
Artem Dergachev13b20262018-01-17 23:46:13 +00001319 SymbolRef Sym = RetVal->getAsLocSymbol();
1320 // This is a return value of a function that was not inlined, such as malloc()
1321 // or new(). We've checked that in the caller. Therefore, it must be a symbol.
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001322 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001323
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001324 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001325 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001326}
1327
Anna Zaks40a7eb32012-02-22 19:24:52 +00001328ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1329 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001330 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001331 ProgramStateRef State) const {
1332 if (!State)
1333 return nullptr;
1334
Richard Smith852e9ce2013-11-27 01:46:48 +00001335 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001336 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001337
Anna Zaksfe6eb672012-08-24 02:28:20 +00001338 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001339
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001340 for (const auto &Arg : Att->args()) {
Joel E. Denny81508102018-03-13 14:51:22 +00001341 ProgramStateRef StateI = FreeMemAux(
1342 C, CE, State, Arg.getASTIndex(),
1343 Att->getOwnKind() == OwnershipAttr::Holds, ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001344 if (StateI)
1345 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001346 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001347 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001348}
1349
Ted Kremenek49b1e382012-01-26 21:29:00 +00001350ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001351 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001352 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001353 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001354 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001355 bool &ReleasedAllocated,
1356 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001357 if (!State)
1358 return nullptr;
1359
Anna Zaksb508d292012-04-10 23:41:11 +00001360 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001361 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001362
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001363 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001364 ReleasedAllocated, ReturnsNullOnFailure);
1365}
1366
Anna Zaksa14c1d02012-11-13 19:47:40 +00001367/// Checks if the previous call to free on the given symbol failed - if free
1368/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001369static bool didPreviousFreeFail(ProgramStateRef State,
1370 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001371 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001372 if (Ret) {
1373 assert(*Ret && "We should not store the null return symbol");
1374 ConstraintManager &CMgr = State->getConstraintManager();
1375 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001376 RetStatusSymbol = *Ret;
1377 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001378 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001379 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001380}
1381
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001382AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001383 const Stmt *S) const {
1384 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001385 return AF_None;
1386
Anton Yartseve3377fb2013-04-04 23:46:29 +00001387 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001388 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001389
1390 if (!FD)
1391 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1392
Anton Yartsev05789592013-03-28 17:05:19 +00001393 ASTContext &Ctx = C.getASTContext();
1394
Anna Zaksd79b8402014-10-03 21:48:59 +00001395 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001396 return AF_Malloc;
1397
1398 if (isStandardNewDelete(FD, Ctx)) {
1399 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001400 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001401 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001402 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001403 return AF_CXXNewArray;
1404 }
1405
Anna Zaksd79b8402014-10-03 21:48:59 +00001406 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1407 return AF_IfNameIndex;
1408
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001409 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1410 return AF_Alloca;
1411
Anton Yartsev05789592013-03-28 17:05:19 +00001412 return AF_None;
1413 }
1414
Anton Yartseve3377fb2013-04-04 23:46:29 +00001415 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1416 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1417
1418 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001419 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1420
Anton Yartseve3377fb2013-04-04 23:46:29 +00001421 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001422 return AF_Malloc;
1423
1424 return AF_None;
1425}
1426
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001427bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001428 const Expr *E) const {
1429 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1430 // FIXME: This doesn't handle indirect calls.
1431 const FunctionDecl *FD = CE->getDirectCallee();
1432 if (!FD)
1433 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001434
Anton Yartsev05789592013-03-28 17:05:19 +00001435 os << *FD;
1436 if (!FD->isOverloadedOperator())
1437 os << "()";
1438 return true;
1439 }
1440
1441 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1442 if (Msg->isInstanceMessage())
1443 os << "-";
1444 else
1445 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001446 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001447 return true;
1448 }
1449
1450 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001451 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001452 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1453 << "'";
1454 return true;
1455 }
1456
1457 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001458 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001459 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1460 << "'";
1461 return true;
1462 }
1463
1464 return false;
1465}
1466
1467void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1468 const Expr *E) const {
1469 AllocationFamily Family = getAllocationFamily(C, E);
1470
1471 switch(Family) {
1472 case AF_Malloc: os << "malloc()"; return;
1473 case AF_CXXNew: os << "'new'"; return;
1474 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001475 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Reka Kovacs18775fc2018-06-09 13:03:49 +00001476 case AF_InternalBuffer: os << "container-specific allocator"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001477 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001478 case AF_None: llvm_unreachable("not a deallocation expression");
1479 }
1480}
1481
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001482void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001483 AllocationFamily Family) const {
1484 switch(Family) {
1485 case AF_Malloc: os << "free()"; return;
1486 case AF_CXXNew: os << "'delete'"; return;
1487 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001488 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Reka Kovacs18775fc2018-06-09 13:03:49 +00001489 case AF_InternalBuffer: os << "container-specific deallocator"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001490 case AF_Alloca:
1491 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001492 }
1493}
1494
Anna Zaks0d6989b2012-06-22 02:04:31 +00001495ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1496 const Expr *ArgExpr,
1497 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001498 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001499 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001500 bool &ReleasedAllocated,
1501 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001502
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001503 if (!State)
1504 return nullptr;
1505
George Karpenkovd703ec92018-01-17 20:27:29 +00001506 SVal ArgVal = C.getSVal(ArgExpr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001507 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001508 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001509 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001510
1511 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001512 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001513 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001514
Anna Zaksad01ef52012-02-14 00:26:13 +00001515 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001516 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001517 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001518 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001519 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001520
Jordy Rose3597b212010-06-07 19:32:37 +00001521 // Unknown values could easily be okay
1522 // Undefined values are handled elsewhere
1523 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001524 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001525
Jordy Rose3597b212010-06-07 19:32:37 +00001526 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001527
Jordy Rose3597b212010-06-07 19:32:37 +00001528 // Nonlocs can't be freed, of course.
1529 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1530 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001531 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001532 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001533 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001534
Jordy Rose3597b212010-06-07 19:32:37 +00001535 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001536
Jordy Rose3597b212010-06-07 19:32:37 +00001537 // Blocks might show up as heap data, but should not be free()d
1538 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001539 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001540 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001541 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001542
Jordy Rose3597b212010-06-07 19:32:37 +00001543 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001544
1545 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001546 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001547 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1548 // FIXME: at the time this code was written, malloc() regions were
1549 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1550 // This means that there isn't actually anything from HeapSpaceRegion
1551 // that should be freed, even though we allow it here.
1552 // Of course, free() can work on memory allocated outside the current
1553 // function, so UnknownSpaceRegion is always a possibility.
1554 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001555
1556 if (isa<AllocaRegion>(R))
1557 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1558 else
1559 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1560
Craig Topper0dbb7832014-05-27 02:45:47 +00001561 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001562 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001563
1564 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001565 // Various cases could lead to non-symbol values here.
1566 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001567 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001568 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001569
Anna Zaksc89ad072013-02-07 23:05:47 +00001570 SymbolRef SymBase = SrBase->getSymbol();
1571 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001572 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001573
Anton Yartseve3377fb2013-04-04 23:46:29 +00001574 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001575
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001576 // Memory returned by alloca() shouldn't be freed.
1577 if (RsBase->getAllocationFamily() == AF_Alloca) {
1578 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1579 return nullptr;
1580 }
1581
Anna Zaks93a21a82013-04-09 00:30:28 +00001582 // Check for double free first.
1583 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001584 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1585 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1586 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001587 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001588
Anna Zaks93a21a82013-04-09 00:30:28 +00001589 // If the pointer is allocated or escaped, but we are now trying to free it,
1590 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001591 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001592 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001593
1594 // Check if an expected deallocation function matches the real one.
1595 bool DeallocMatchesAlloc =
1596 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1597 if (!DeallocMatchesAlloc) {
1598 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001599 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001600 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001601 }
1602
1603 // Check if the memory location being freed is the actual location
1604 // allocated, or an offset.
1605 RegionOffset Offset = R->getAsOffset();
1606 if (Offset.isValid() &&
1607 !Offset.hasSymbolicOffset() &&
1608 Offset.getOffset() != 0) {
1609 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001610 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001611 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001612 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001613 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001614 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001615 }
1616
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00001617 if (SymBase->getType()->isFunctionPointerType()) {
1618 ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1619 return nullptr;
1620 }
1621
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001622 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001623 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001624
Anna Zaksa14c1d02012-11-13 19:47:40 +00001625 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001626 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001627
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001628 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001629 // failed.
1630 if (ReturnsNullOnFailure) {
1631 SVal RetVal = C.getSVal(ParentExpr);
1632 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1633 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001634 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1635 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001636 }
1637 }
1638
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001639 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1640 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001641 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001642 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001643 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001644 RefState::getRelinquished(Family,
1645 ParentExpr));
1646
1647 return State->set<RegionState>(SymBase,
1648 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001649}
1650
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001651Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001652MallocChecker::getCheckIfTracked(AllocationFamily Family,
1653 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001654 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001655 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001656 case AF_Alloca:
1657 case AF_IfNameIndex: {
1658 if (ChecksEnabled[CK_MallocChecker])
1659 return CK_MallocChecker;
1660
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001661 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001662 }
1663 case AF_CXXNew:
Reka Kovacs18775fc2018-06-09 13:03:49 +00001664 case AF_CXXNewArray:
1665 // FIXME: Add new CheckKind for AF_InternalBuffer.
1666 case AF_InternalBuffer: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001667 if (IsALeakCheck) {
1668 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1669 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001670 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001671 else {
1672 if (ChecksEnabled[CK_NewDeleteChecker])
1673 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001674 }
1675 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001676 }
1677 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001678 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001679 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001680 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001681 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001682}
1683
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001684Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001685MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001686 const Stmt *AllocDeallocStmt,
1687 bool IsALeakCheck) const {
1688 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1689 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001690}
1691
1692Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001693MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1694 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001695 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1696 return CK_MallocChecker;
1697
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001698 const RefState *RS = C.getState()->get<RegionState>(Sym);
1699 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001700 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001701}
1702
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001703bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001704 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001705 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001706 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001707 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001708 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001709 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001710 else
1711 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001712
Jordy Rose3597b212010-06-07 19:32:37 +00001713 return true;
1714}
1715
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001716bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001717 const MemRegion *MR) {
1718 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +00001719 case MemRegion::FunctionCodeRegionKind: {
1720 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001721 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001722 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001723 else
1724 os << "the address of a function";
1725 return true;
1726 }
Artem Dergachev73f018e2016-01-13 13:49:29 +00001727 case MemRegion::BlockCodeRegionKind:
Jordy Rose3597b212010-06-07 19:32:37 +00001728 os << "block text";
1729 return true;
1730 case MemRegion::BlockDataRegionKind:
1731 // FIXME: where the block came from?
1732 os << "a block";
1733 return true;
1734 default: {
1735 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001736
Anna Zaks8158ef02012-01-04 23:54:01 +00001737 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001738 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1739 const VarDecl *VD;
1740 if (VR)
1741 VD = VR->getDecl();
1742 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001743 VD = nullptr;
1744
Jordy Rose3597b212010-06-07 19:32:37 +00001745 if (VD)
1746 os << "the address of the local variable '" << VD->getName() << "'";
1747 else
1748 os << "the address of a local stack variable";
1749 return true;
1750 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001751
1752 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001753 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1754 const VarDecl *VD;
1755 if (VR)
1756 VD = VR->getDecl();
1757 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001758 VD = nullptr;
1759
Jordy Rose3597b212010-06-07 19:32:37 +00001760 if (VD)
1761 os << "the address of the parameter '" << VD->getName() << "'";
1762 else
1763 os << "the address of a parameter";
1764 return true;
1765 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001766
1767 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001768 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1769 const VarDecl *VD;
1770 if (VR)
1771 VD = VR->getDecl();
1772 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001773 VD = nullptr;
1774
Jordy Rose3597b212010-06-07 19:32:37 +00001775 if (VD) {
1776 if (VD->isStaticLocal())
1777 os << "the address of the static variable '" << VD->getName() << "'";
1778 else
1779 os << "the address of the global variable '" << VD->getName() << "'";
1780 } else
1781 os << "the address of a global variable";
1782 return true;
1783 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001784
1785 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001786 }
1787 }
1788}
1789
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001790void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1791 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001792 const Expr *DeallocExpr) const {
1793
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001794 if (!ChecksEnabled[CK_MallocChecker] &&
1795 !ChecksEnabled[CK_NewDeleteChecker])
1796 return;
1797
1798 Optional<MallocChecker::CheckKind> CheckKind =
1799 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001800 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001801 return;
1802
Devin Coughline39bd402015-09-16 22:03:05 +00001803 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001804 if (!BT_BadFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001805 BT_BadFree[*CheckKind].reset(new BugType(
1806 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001807
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001808 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001809 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001810
Jordy Rose3597b212010-06-07 19:32:37 +00001811 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001812 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1813 MR = ER->getSuperRegion();
1814
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001815 os << "Argument to ";
1816 if (!printAllocDeallocName(os, C, DeallocExpr))
1817 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001818
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001819 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001820 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001821 : SummarizeValue(os, ArgVal);
1822 if (Summarized)
1823 os << ", which is not memory allocated by ";
1824 else
1825 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001826
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001827 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001828
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001829 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001830 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001831 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001832 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001833 }
1834}
1835
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001836void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001837 SourceRange Range) const {
1838
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001839 Optional<MallocChecker::CheckKind> CheckKind;
1840
1841 if (ChecksEnabled[CK_MallocChecker])
1842 CheckKind = CK_MallocChecker;
1843 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1844 CheckKind = CK_MismatchedDeallocatorChecker;
1845 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001846 return;
1847
Devin Coughline39bd402015-09-16 22:03:05 +00001848 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001849 if (!BT_FreeAlloca[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001850 BT_FreeAlloca[*CheckKind].reset(new BugType(
1851 CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001852
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001853 auto R = llvm::make_unique<BugReport>(
1854 *BT_FreeAlloca[*CheckKind],
1855 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001856 R->markInteresting(ArgVal.getAsRegion());
1857 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001858 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001859 }
1860}
1861
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001862void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001863 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001864 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001865 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001866 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001867 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001868
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001869 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001870 return;
1871
Devin Coughline39bd402015-09-16 22:03:05 +00001872 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001873 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001874 BT_MismatchedDealloc.reset(
1875 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001876 "Bad deallocator", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001877
Anton Yartsev05789592013-03-28 17:05:19 +00001878 SmallString<100> buf;
1879 llvm::raw_svector_ostream os(buf);
1880
1881 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1882 SmallString<20> AllocBuf;
1883 llvm::raw_svector_ostream AllocOs(AllocBuf);
1884 SmallString<20> DeallocBuf;
1885 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1886
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001887 if (OwnershipTransferred) {
1888 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1889 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001890 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001891 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001892
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001893 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001894
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001895 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1896 os << " allocated by " << AllocOs.str();
1897 } else {
1898 os << "Memory";
1899 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1900 os << " allocated by " << AllocOs.str();
1901
1902 os << " should be deallocated by ";
1903 printExpectedDeallocName(os, RS->getAllocationFamily());
1904
1905 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1906 os << ", not " << DeallocOs.str();
1907 }
Anton Yartsev05789592013-03-28 17:05:19 +00001908
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001909 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001910 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001911 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001912 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001913 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001914 }
1915}
1916
Anna Zaksc89ad072013-02-07 23:05:47 +00001917void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001918 SourceRange Range, const Expr *DeallocExpr,
1919 const Expr *AllocExpr) const {
1920
Anton Yartsev05789592013-03-28 17:05:19 +00001921
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001922 if (!ChecksEnabled[CK_MallocChecker] &&
1923 !ChecksEnabled[CK_NewDeleteChecker])
1924 return;
1925
1926 Optional<MallocChecker::CheckKind> CheckKind =
1927 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001928 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001929 return;
1930
Devin Coughline39bd402015-09-16 22:03:05 +00001931 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001932 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001933 return;
1934
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001935 if (!BT_OffsetFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001936 BT_OffsetFree[*CheckKind].reset(new BugType(
1937 CheckNames[*CheckKind], "Offset free", categories::MemoryError));
Anna Zaksc89ad072013-02-07 23:05:47 +00001938
1939 SmallString<100> buf;
1940 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001941 SmallString<20> AllocNameBuf;
1942 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001943
1944 const MemRegion *MR = ArgVal.getAsRegion();
1945 assert(MR && "Only MemRegion based symbols can have offset free errors");
1946
1947 RegionOffset Offset = MR->getAsOffset();
1948 assert((Offset.isValid() &&
1949 !Offset.hasSymbolicOffset() &&
1950 Offset.getOffset() != 0) &&
1951 "Only symbols with a valid offset can have offset free errors");
1952
1953 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1954
Anton Yartsev05789592013-03-28 17:05:19 +00001955 os << "Argument to ";
1956 if (!printAllocDeallocName(os, C, DeallocExpr))
1957 os << "deallocator";
1958 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001959 << offsetBytes
1960 << " "
1961 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001962 << " from the start of ";
1963 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1964 os << "memory allocated by " << AllocNameOs.str();
1965 else
1966 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001967
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001968 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001969 R->markInteresting(MR->getBaseRegion());
1970 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001971 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001972}
1973
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001974void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1975 SymbolRef Sym) const {
1976
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001977 if (!ChecksEnabled[CK_MallocChecker] &&
1978 !ChecksEnabled[CK_NewDeleteChecker])
1979 return;
1980
1981 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001982 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001983 return;
1984
Devin Coughline39bd402015-09-16 22:03:05 +00001985 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001986 if (!BT_UseFree[*CheckKind])
1987 BT_UseFree[*CheckKind].reset(new BugType(
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001988 CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001989
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001990 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1991 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001992
1993 R->markInteresting(Sym);
1994 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001995 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Reka Kovacse453e602018-07-07 19:27:18 +00001996
1997 const RefState *RS = C.getState()->get<RegionState>(Sym);
1998 if (RS->getAllocationFamily() == AF_InternalBuffer)
1999 R->addVisitor(allocation_state::getDanglingBufferBRVisitor(Sym));
2000
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002001 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002002 }
2003}
2004
2005void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002006 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00002007 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002008
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002009 if (!ChecksEnabled[CK_MallocChecker] &&
2010 !ChecksEnabled[CK_NewDeleteChecker])
2011 return;
2012
2013 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002014 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00002015 return;
2016
Devin Coughline39bd402015-09-16 22:03:05 +00002017 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002018 if (!BT_DoubleFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002019 BT_DoubleFree[*CheckKind].reset(new BugType(
2020 CheckNames[*CheckKind], "Double free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002021
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002022 auto R = llvm::make_unique<BugReport>(
2023 *BT_DoubleFree[*CheckKind],
2024 (Released ? "Attempt to free released memory"
2025 : "Attempt to free non-owned memory"),
2026 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002027 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00002028 R->markInteresting(Sym);
2029 if (PrevSym)
2030 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00002031 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002032 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002033 }
2034}
2035
Jordan Rose656fdd52014-01-08 18:46:55 +00002036void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2037
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002038 if (!ChecksEnabled[CK_NewDeleteChecker])
2039 return;
2040
2041 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002042 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00002043 return;
2044
Devin Coughline39bd402015-09-16 22:03:05 +00002045 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00002046 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002047 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002048 "Double delete",
2049 categories::MemoryError));
Jordan Rose656fdd52014-01-08 18:46:55 +00002050
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002051 auto R = llvm::make_unique<BugReport>(
2052 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00002053
2054 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002055 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002056 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00002057 }
2058}
2059
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002060void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2061 SourceRange Range,
2062 SymbolRef Sym) const {
2063
2064 if (!ChecksEnabled[CK_MallocChecker] &&
2065 !ChecksEnabled[CK_NewDeleteChecker])
2066 return;
2067
2068 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2069
2070 if (!CheckKind.hasValue())
2071 return;
2072
Devin Coughline39bd402015-09-16 22:03:05 +00002073 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002074 if (!BT_UseZerroAllocated[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002075 BT_UseZerroAllocated[*CheckKind].reset(
2076 new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2077 categories::MemoryError));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002078
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002079 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2080 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002081
2082 R->addRange(Range);
2083 if (Sym) {
2084 R->markInteresting(Sym);
2085 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2086 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002087 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002088 }
2089}
2090
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002091void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2092 SourceRange Range,
2093 const Expr *FreeExpr) const {
2094 if (!ChecksEnabled[CK_MallocChecker])
2095 return;
2096
2097 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2098 if (!CheckKind.hasValue())
2099 return;
2100
2101 if (ExplodedNode *N = C.generateErrorNode()) {
2102 if (!BT_BadFree[*CheckKind])
Artem Dergachev9849f592018-02-08 23:28:29 +00002103 BT_BadFree[*CheckKind].reset(new BugType(
2104 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002105
2106 SmallString<100> Buf;
2107 llvm::raw_svector_ostream Os(Buf);
2108
2109 const MemRegion *MR = ArgVal.getAsRegion();
2110 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2111 MR = ER->getSuperRegion();
2112
2113 Os << "Argument to ";
2114 if (!printAllocDeallocName(Os, C, FreeExpr))
2115 Os << "deallocator";
2116
2117 Os << " is a function pointer";
2118
2119 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2120 R->markInteresting(MR);
2121 R->addRange(Range);
2122 C.emitReport(std::move(R));
2123 }
2124}
2125
Leslie Zhaie3986c52017-04-26 05:33:14 +00002126ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2127 const CallExpr *CE,
2128 bool FreesOnFail,
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002129 ProgramStateRef State,
Leslie Zhaie3986c52017-04-26 05:33:14 +00002130 bool SuffixWithN) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002131 if (!State)
2132 return nullptr;
2133
Leslie Zhaie3986c52017-04-26 05:33:14 +00002134 if (SuffixWithN && CE->getNumArgs() < 3)
2135 return nullptr;
2136 else if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002137 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002138
Ted Kremenek90af9092010-12-02 07:49:45 +00002139 const Expr *arg0Expr = CE->getArg(0);
George Karpenkovd703ec92018-01-17 20:27:29 +00002140 SVal Arg0Val = C.getSVal(arg0Expr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00002141 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002142 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00002143 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002144
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002145 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002146
Ted Kremenek90af9092010-12-02 07:49:45 +00002147 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002148 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002149
Leslie Zhaie3986c52017-04-26 05:33:14 +00002150 // Get the size argument.
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002151 const Expr *Arg1 = CE->getArg(1);
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002152
2153 // Get the value of the size argument.
George Karpenkovd703ec92018-01-17 20:27:29 +00002154 SVal TotalSize = C.getSVal(Arg1);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002155 if (SuffixWithN)
2156 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2157 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002158 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002159
2160 // Compare the size argument to 0.
2161 DefinedOrUnknownSVal SizeZero =
Leslie Zhaie3986c52017-04-26 05:33:14 +00002162 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002163 svalBuilder.makeIntValWithPtrWidth(0, false));
2164
Anna Zaksd56c8792012-02-13 18:05:39 +00002165 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002166 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00002167 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002168 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00002169 // We only assume exceptional states if they are definitely true; if the
2170 // state is under-constrained, assume regular realloc behavior.
2171 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2172 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2173
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002174 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002175 // malloc(size).
Leslie Zhaie3986c52017-04-26 05:33:14 +00002176 if (PrtIsNull && !SizeIsZero) {
2177 ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002178 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002179 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002180 }
2181
Anna Zaksd56c8792012-02-13 18:05:39 +00002182 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00002183 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002184
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002185 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00002186 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002187 SymbolRef FromPtr = arg0Val.getAsSymbol();
George Karpenkovd703ec92018-01-17 20:27:29 +00002188 SVal RetVal = C.getSVal(CE);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002189 SymbolRef ToPtr = RetVal.getAsSymbol();
2190 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00002191 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00002192
Anna Zaksfe6eb672012-08-24 02:28:20 +00002193 bool ReleasedAllocated = false;
2194
Anna Zaksd56c8792012-02-13 18:05:39 +00002195 // If the size is 0, free the memory.
2196 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00002197 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2198 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00002199 // The semantics of the return value are:
2200 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00002201 // to free() is returned. We just free the input pointer and do not add
2202 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00002203 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00002204 }
2205
2206 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00002207 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002208 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00002209
Leslie Zhaie3986c52017-04-26 05:33:14 +00002210 ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002211 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002212 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00002213 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00002214
Anna Zaks75cfbb62012-09-12 22:57:34 +00002215 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2216 if (FreesOnFail)
2217 Kind = RPIsFreeOnFailure;
2218 else if (!ReleasedAllocated)
2219 Kind = RPDoNotTrackAfterFailure;
2220
Anna Zaksfe6eb672012-08-24 02:28:20 +00002221 // Record the info about the reallocated symbol so that we could properly
2222 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00002223 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00002224 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00002225 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00002226 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002227 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002228 }
Craig Topper0dbb7832014-05-27 02:45:47 +00002229 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00002230}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002231
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002232ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002233 ProgramStateRef State) {
2234 if (!State)
2235 return nullptr;
2236
Anna Zaksb508d292012-04-10 23:41:11 +00002237 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002238 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002239
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002240 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek90af9092010-12-02 07:49:45 +00002241 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002242 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002243
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002244 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002245}
2246
Anna Zaksfc2e1532012-03-21 19:45:08 +00002247LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002248MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2249 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002250 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002251 // Walk the ExplodedGraph backwards and find the first node that referred to
2252 // the tracked symbol.
2253 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002254 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002255
2256 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002257 ProgramStateRef State = N->getState();
2258 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002259 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002260
2261 // Find the most recent expression bound to the symbol in the current
2262 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002263 if (!ReferenceRegion) {
2264 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2265 SVal Val = State->getSVal(MR);
2266 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002267 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002268 // Do not show local variables belonging to a function other than
2269 // where the error is reported.
2270 if (!VR ||
George Karpenkovdd18b112018-06-27 01:51:55 +00002271 (VR->getStackFrame() == LeakContext->getStackFrame()))
Anna Zaks7c19abe2013-04-10 21:42:02 +00002272 ReferenceRegion = MR;
2273 }
2274 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002275 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002276
Anna Zaks486a0ff2015-02-05 01:02:53 +00002277 // Allocation node, is the last node in the current or parent context in
2278 // which the symbol was tracked.
2279 const LocationContext *NContext = N->getLocationContext();
2280 if (NContext == LeakContext ||
2281 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002282 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002283 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002284 }
2285
Anna Zaksa043d0c2013-01-08 00:25:29 +00002286 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002287}
2288
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002289void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2290 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002291
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002292 if (!ChecksEnabled[CK_MallocChecker] &&
2293 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002294 return;
2295
Anton Yartsev9907fc92015-03-04 23:18:21 +00002296 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002297 assert(RS && "cannot leak an untracked symbol");
2298 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002299
2300 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002301 return;
2302
Anton Yartsev2487dd62015-03-10 22:24:21 +00002303 Optional<MallocChecker::CheckKind>
2304 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002305
Anton Yartsev2487dd62015-03-10 22:24:21 +00002306 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002307 return;
2308
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002309 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002310 if (!BT_Leak[*CheckKind]) {
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002311 BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2312 categories::MemoryError));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002313 // Leaks should not be reported if they are post-dominated by a sink:
2314 // (1) Sinks are higher importance bugs.
2315 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2316 // with __noreturn functions such as assert() or exit(). We choose not
2317 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002318 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002319 }
2320
Anna Zaksdf901a42012-02-23 21:38:21 +00002321 // Most bug reports are cached at the location where they occurred.
2322 // With leaks, we want to unique them by the location where they were
2323 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002324 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002325 const ExplodedNode *AllocNode = nullptr;
2326 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002327 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002328
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002329 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
Anton Yartsev6e499252013-04-05 02:25:02 +00002330 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002331 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2332 C.getSourceManager(),
2333 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002334
Anna Zaksfc2e1532012-03-21 19:45:08 +00002335 SmallString<200> buf;
2336 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002337 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002338 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002339 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002340 } else {
2341 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002342 }
2343
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002344 auto R = llvm::make_unique<BugReport>(
2345 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2346 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002347 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002348 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002349 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002350}
2351
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002352void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2353 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002354{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002355 if (!SymReaper.hasDeadSymbols())
2356 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002357
Ted Kremenek49b1e382012-01-26 21:29:00 +00002358 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002359 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002360 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002361
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002362 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002363 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2364 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002365 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002366 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002367 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002368 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002369
Zhongxing Xuc7460962009-11-13 07:48:11 +00002370 }
2371 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002372
Anna Zaksd56c8792012-02-13 18:05:39 +00002373 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002374 ReallocPairsTy RP = state->get<ReallocPairs>();
2375 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002376 if (SymReaper.isDead(I->first) ||
2377 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002378 state = state->remove<ReallocPairs>(I->first);
2379 }
2380 }
2381
Anna Zaks67291b92012-11-13 03:18:01 +00002382 // Cleanup the FreeReturnValue Map.
2383 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2384 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2385 if (SymReaper.isDead(I->first) ||
2386 SymReaper.isDead(I->second)) {
2387 state = state->remove<FreeReturnValue>(I->first);
2388 }
2389 }
2390
Anna Zaksdf901a42012-02-23 21:38:21 +00002391 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002392 ExplodedNode *N = C.getPredecessor();
2393 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002394 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002395 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2396 if (N) {
2397 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002398 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002399 reportLeak(*I, N, C);
2400 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002401 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002402 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002403
Anna Zaksdf901a42012-02-23 21:38:21 +00002404 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002405}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002406
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002407void MallocChecker::checkPreCall(const CallEvent &Call,
2408 CheckerContext &C) const {
2409
Jordan Rose656fdd52014-01-08 18:46:55 +00002410 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2411 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2412 if (!Sym || checkDoubleDelete(Sym, C))
2413 return;
2414 }
2415
Anna Zaks46d01602012-05-18 01:16:10 +00002416 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002417 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2418 const FunctionDecl *FD = FC->getDecl();
2419 if (!FD)
2420 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002421
Anna Zaksd79b8402014-10-03 21:48:59 +00002422 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002423 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002424 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2425 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2426 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002427 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002428
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002429 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002430 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002431 return;
2432 }
2433
2434 // Check if the callee of a method is deleted.
2435 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2436 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2437 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2438 return;
2439 }
2440
2441 // Check arguments for being used after free.
2442 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2443 SVal ArgSVal = Call.getArgSVal(I);
2444 if (ArgSVal.getAs<Loc>()) {
2445 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002446 if (!Sym)
2447 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002448 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002449 return;
2450 }
2451 }
2452}
2453
Anna Zaksa1b227b2012-02-08 23:16:56 +00002454void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2455 const Expr *E = S->getRetValue();
2456 if (!E)
2457 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002458
2459 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002460 ProgramStateRef State = C.getState();
George Karpenkovd703ec92018-01-17 20:27:29 +00002461 SVal RetVal = C.getSVal(E);
Anna Zaks4ca45b12012-02-22 02:36:01 +00002462 SymbolRef Sym = RetVal.getAsSymbol();
2463 if (!Sym)
2464 // If we are returning a field of the allocated struct or an array element,
2465 // the callee could still free the memory.
2466 // TODO: This logic should be a part of generic symbol escape callback.
2467 if (const MemRegion *MR = RetVal.getAsRegion())
2468 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2469 if (const SymbolicRegion *BMR =
2470 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2471 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002472
Anna Zaks3aa52252012-02-11 21:44:39 +00002473 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002474 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002475 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002476}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002477
Anna Zaks9fe80982012-03-22 00:57:20 +00002478// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002479// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002480// needed.
2481void MallocChecker::checkPostStmt(const BlockExpr *BE,
2482 CheckerContext &C) const {
2483
2484 // Scan the BlockDecRefExprs for any object the retain count checker
2485 // may be tracking.
2486 if (!BE->getBlockDecl()->hasCaptures())
2487 return;
2488
2489 ProgramStateRef state = C.getState();
2490 const BlockDataRegion *R =
George Karpenkovd703ec92018-01-17 20:27:29 +00002491 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
Anna Zaks9fe80982012-03-22 00:57:20 +00002492
2493 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2494 E = R->referenced_vars_end();
2495
2496 if (I == E)
2497 return;
2498
2499 SmallVector<const MemRegion*, 10> Regions;
2500 const LocationContext *LC = C.getLocationContext();
2501 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2502
2503 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002504 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002505 if (VR->getSuperRegion() == R) {
2506 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2507 }
2508 Regions.push_back(VR);
2509 }
2510
2511 state =
2512 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2513 Regions.data() + Regions.size()).getState();
2514 C.addTransition(state);
2515}
2516
Anna Zaks46d01602012-05-18 01:16:10 +00002517bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002518 assert(Sym);
2519 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002520 return (RS && RS->isReleased());
2521}
2522
2523bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2524 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002525
Jordan Rose656fdd52014-01-08 18:46:55 +00002526 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002527 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2528 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002529 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002530
Anna Zaksa1b227b2012-02-08 23:16:56 +00002531 return false;
2532}
2533
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002534void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2535 const Stmt *S) const {
2536 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002537
Devin Coughlin81771732015-09-22 22:47:14 +00002538 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2539 if (RS->isAllocatedOfSizeZero())
2540 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2541 }
2542 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2543 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2544 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002545}
2546
Jordan Rose656fdd52014-01-08 18:46:55 +00002547bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2548
2549 if (isReleased(Sym, C)) {
2550 ReportDoubleDelete(C, Sym);
2551 return true;
2552 }
2553 return false;
2554}
2555
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002556// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002557void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2558 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002559 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002560 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002561 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002562 checkUseZeroAllocated(Sym, C, S);
2563 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002564}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002565
Anna Zaksbb1ef902012-02-11 21:02:35 +00002566// If a symbolic region is assumed to NULL (or another constant), stop tracking
2567// it - assuming that allocation failed on this path.
2568ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2569 SVal Cond,
2570 bool Assumption) const {
2571 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002572 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002573 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002574 ConstraintManager &CMgr = state->getConstraintManager();
2575 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2576 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002577 state = state->remove<RegionState>(I.getKey());
2578 }
2579
Anna Zaksd56c8792012-02-13 18:05:39 +00002580 // Realloc returns 0 when reallocation fails, which means that we should
2581 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002582 ReallocPairsTy RP = state->get<ReallocPairs>();
2583 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002584 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002585 ConstraintManager &CMgr = state->getConstraintManager();
2586 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002587 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002588 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002589
Anna Zaks75cfbb62012-09-12 22:57:34 +00002590 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2591 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2592 if (RS->isReleased()) {
2593 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002594 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002595 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002596 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2597 state = state->remove<RegionState>(ReallocSym);
2598 else
2599 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002600 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002601 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002602 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002603 }
2604
Anna Zaksbb1ef902012-02-11 21:02:35 +00002605 return state;
2606}
2607
Anna Zaks8ebeb642013-06-08 00:29:29 +00002608bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002609 const CallEvent *Call,
2610 ProgramStateRef State,
2611 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002612 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002613 EscapingSymbol = nullptr;
2614
Jordan Rose2a833ca2014-01-15 17:25:15 +00002615 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002616 // TODO: If we want to be more optimistic here, we'll need to make sure that
2617 // regions escape to C++ containers. They seem to do that even now, but for
2618 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002619 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002620 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002621
Jordan Rose742920c2012-07-02 19:27:35 +00002622 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002623 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002624 // If it's not a framework call, or if it takes a callback, assume it
2625 // can free memory.
Anna Zaksfe1eca52015-10-27 20:19:45 +00002626 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002627 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002628
Jordan Rose613f3c02013-03-09 00:59:10 +00002629 // If it's a method we know about, handle it explicitly post-call.
2630 // This should happen before the "freeWhenDone" check below.
2631 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002632 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002633
Jordan Rose613f3c02013-03-09 00:59:10 +00002634 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2635 // about, we can't be sure that the object will use free() to deallocate the
2636 // memory, so we can't model it explicitly. The best we can do is use it to
2637 // decide whether the pointer escapes.
2638 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002639 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002640
Jordan Rose613f3c02013-03-09 00:59:10 +00002641 // If the first selector piece ends with "NoCopy", and there is no
2642 // "freeWhenDone" parameter set to zero, we know ownership is being
2643 // transferred. Again, though, we can't be sure that the object will use
2644 // free() to deallocate the memory, so we can't model it explicitly.
2645 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002646 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002647 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002648
Anna Zaks42908c72012-06-19 05:10:32 +00002649 // If the first selector starts with addPointer, insertPointer,
2650 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2651 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002652 // that the pointers get freed by following the container itself.
2653 if (FirstSlot.startswith("addPointer") ||
2654 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002655 FirstSlot.startswith("replacePointer") ||
2656 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002657 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002658 }
2659
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002660 // We should escape receiver on call to 'init'. This is especially relevant
2661 // to the receiver, as the corresponding symbol is usually not referenced
2662 // after the call.
2663 if (Msg->getMethodFamily() == OMF_init) {
2664 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2665 return true;
2666 }
Anna Zaks737926b2013-05-31 22:39:13 +00002667
Jordan Rose742920c2012-07-02 19:27:35 +00002668 // Otherwise, assume that the method does not free memory.
2669 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002670 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002671 }
2672
Jordan Rose742920c2012-07-02 19:27:35 +00002673 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002674 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002675 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002676 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002677
Jordan Rose742920c2012-07-02 19:27:35 +00002678 ASTContext &ASTC = State->getStateManager().getContext();
2679
2680 // If it's one of the allocation functions we can reason about, we model
2681 // its behavior explicitly.
2682 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002683 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002684
2685 // If it's not a system call, assume it frees memory.
2686 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002687 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002688
2689 // White list the system functions whose arguments escape.
2690 const IdentifierInfo *II = FD->getIdentifier();
2691 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002692 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002693 StringRef FName = II->getName();
2694
Jordan Rose742920c2012-07-02 19:27:35 +00002695 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002696 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002697 if (FName.endswith("NoCopy")) {
2698 // Look for the deallocator argument. We know that the memory ownership
2699 // is not transferred only if the deallocator argument is
2700 // 'kCFAllocatorNull'.
2701 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2702 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2703 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2704 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2705 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002706 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002707 }
2708 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002709 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002710 }
2711
Jordan Rose742920c2012-07-02 19:27:35 +00002712 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002713 // 'closefn' is specified (and if that function does free memory),
2714 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002715 // Currently, we do not inspect the 'closefn' function (PR12101).
2716 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002717 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002718 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002719
2720 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2721 // these leaks might be intentional when setting the buffer for stdio.
2722 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2723 if (FName == "setbuf" || FName =="setbuffer" ||
2724 FName == "setlinebuf" || FName == "setvbuf") {
2725 if (Call->getNumArgs() >= 1) {
2726 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2727 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2728 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2729 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002730 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002731 }
2732 }
2733
2734 // A bunch of other functions which either take ownership of a pointer or
2735 // wrap the result up in a struct or object, meaning it can be freed later.
2736 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2737 // but the Malloc checker cannot differentiate between them. The right way
2738 // of doing this would be to implement a pointer escapes callback.
2739 if (FName == "CGBitmapContextCreate" ||
2740 FName == "CGBitmapContextCreateWithData" ||
2741 FName == "CVPixelBufferCreateWithBytes" ||
2742 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2743 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002744 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002745 }
2746
Anna Zaks03f48332016-01-06 00:32:56 +00002747 if (FName == "postEvent" &&
2748 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2749 return true;
2750 }
2751
2752 if (FName == "postEvent" &&
2753 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2754 return true;
2755 }
2756
Artem Dergachev85c92112016-12-16 12:21:55 +00002757 if (FName == "connectImpl" &&
2758 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2759 return true;
2760 }
2761
Jordan Rose7ab01822012-07-02 19:27:51 +00002762 // Handle cases where we know a buffer's /address/ can escape.
2763 // Note that the above checks handle some special cases where we know that
2764 // even though the address escapes, it's still our responsibility to free the
2765 // buffer.
2766 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002767 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002768
2769 // Otherwise, assume that the function does not free memory.
2770 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002771 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002772}
2773
Anna Zaks333481b2013-03-28 23:15:29 +00002774static bool retTrue(const RefState *RS) {
2775 return true;
2776}
2777
2778static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2779 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2780 RS->getAllocationFamily() == AF_CXXNew);
2781}
2782
Anna Zaksdc154152012-12-20 00:38:25 +00002783ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2784 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002785 const CallEvent *Call,
2786 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002787 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2788}
2789
2790ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2791 const InvalidatedSymbols &Escaped,
2792 const CallEvent *Call,
2793 PointerEscapeKind Kind) const {
2794 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2795 &checkIfNewOrNewArrayFamily);
2796}
2797
2798ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2799 const InvalidatedSymbols &Escaped,
2800 const CallEvent *Call,
2801 PointerEscapeKind Kind,
2802 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002803 // If we know that the call does not free memory, or we want to process the
2804 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002805 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002806 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002807 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2808 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002809 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002810 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002811 }
Anna Zaks3d348342012-02-14 21:55:24 +00002812
Anna Zaksdc154152012-12-20 00:38:25 +00002813 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002814 E = Escaped.end();
2815 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002816 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002817
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002818 if (EscapingSymbol && EscapingSymbol != sym)
2819 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002820
Anna Zaks0d6989b2012-06-22 02:04:31 +00002821 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002822 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2823 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002824 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002825 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2826 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002827 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002828 }
Anna Zaks3d348342012-02-14 21:55:24 +00002829 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002830}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002831
Jordy Rosebf38f202012-03-18 07:43:35 +00002832static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2833 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002834 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2835 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002836
Jordan Rose0c153cb2012-11-02 01:54:06 +00002837 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002838 I != E; ++I) {
2839 SymbolRef sym = I.getKey();
2840 if (!currMap.lookup(sym))
2841 return sym;
2842 }
2843
Craig Topper0dbb7832014-05-27 02:45:47 +00002844 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002845}
2846
Artem Dergachevff1fc212018-03-21 00:49:47 +00002847static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) {
2848 if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
2849 StringRef N = II->getName();
2850 if (N.contains_lower("ptr") || N.contains_lower("pointer")) {
2851 if (N.contains_lower("ref") || N.contains_lower("cnt") ||
2852 N.contains_lower("intrusive") || N.contains_lower("shared")) {
2853 return true;
2854 }
2855 }
2856 }
2857 return false;
2858}
2859
David Blaikie0a0c2752017-01-05 17:26:53 +00002860std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2861 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2862 BugReport &BR) {
Reka Kovacs8707cd12018-07-07 17:22:45 +00002863
2864 ProgramStateRef state = N->getState();
2865 ProgramStateRef statePrev = PrevN->getState();
2866
2867 const RefState *RS = state->get<RegionState>(Sym);
2868 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2869
Artem Dergachev5337efc2018-02-27 21:19:33 +00002870 const Stmt *S = PathDiagnosticLocation::getStmt(N);
Reka Kovacs8707cd12018-07-07 17:22:45 +00002871 // When dealing with containers, we sometimes want to give a note
2872 // even if the statement is missing.
2873 if (!S && (!RS || RS->getAllocationFamily() != AF_InternalBuffer))
Artem Dergachev5337efc2018-02-27 21:19:33 +00002874 return nullptr;
2875
2876 const LocationContext *CurrentLC = N->getLocationContext();
2877
2878 // If we find an atomic fetch_add or fetch_sub within the destructor in which
2879 // the pointer was released (before the release), this is likely a destructor
2880 // of a shared pointer.
2881 // Because we don't model atomics, and also because we don't know that the
2882 // original reference count is positive, we should not report use-after-frees
2883 // on objects deleted in such destructors. This can probably be improved
2884 // through better shared pointer modeling.
2885 if (ReleaseDestructorLC) {
2886 if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
2887 AtomicExpr::AtomicOp Op = AE->getOp();
2888 if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
2889 Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
2890 if (ReleaseDestructorLC == CurrentLC ||
2891 ReleaseDestructorLC->isParentOf(CurrentLC)) {
2892 BR.markInvalid(getTag(), S);
2893 }
2894 }
2895 }
2896 }
2897
Jordan Rose681cce92012-07-10 22:07:42 +00002898 // FIXME: We will eventually need to handle non-statement-based events
2899 // (__attribute__((cleanup))).
2900
Anna Zaks2b5bb972012-02-09 06:25:51 +00002901 // Find out if this is an interesting point and what is the kind.
Reka Kovacsa14a2fe2018-07-19 17:43:09 +00002902 StringRef Msg;
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002903 StackHintGeneratorForSymbol *StackHint = nullptr;
Reka Kovacs52dd98b2018-07-19 15:44:46 +00002904 SmallString<256> Buf;
2905 llvm::raw_svector_ostream OS(Buf);
2906
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002907 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002908 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002909 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002910 StackHint = new StackHintGeneratorForSymbol(Sym,
2911 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002912 } else if (isReleased(RS, RSPrev, S)) {
Reka Kovacs8707cd12018-07-07 17:22:45 +00002913 const auto Family = RS->getAllocationFamily();
Reka Kovacsc18ecc82018-07-19 15:10:06 +00002914 switch (Family) {
Reka Kovacs8707cd12018-07-07 17:22:45 +00002915 case AF_Alloca:
2916 case AF_Malloc:
2917 case AF_CXXNew:
2918 case AF_CXXNewArray:
2919 case AF_IfNameIndex:
2920 Msg = "Memory is released";
2921 break;
Reka Kovacsc18ecc82018-07-19 15:10:06 +00002922 case AF_InternalBuffer: {
Reka Kovacsc18ecc82018-07-19 15:10:06 +00002923 OS << "Inner pointer invalidated by call to ";
2924 if (N->getLocation().getKind() == ProgramPoint::PostImplicitCallKind) {
2925 OS << "destructor";
2926 } else {
2927 OS << "'";
2928 const Stmt *S = RS->getStmt();
2929 if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
2930 OS << MemCallE->getMethodDecl()->getNameAsString();
2931 } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
2932 OS << OpCallE->getDirectCallee()->getNameAsString();
2933 }
2934 OS << "'";
2935 }
Reka Kovacsa14a2fe2018-07-19 17:43:09 +00002936 Msg = OS.str();
Reka Kovacs8707cd12018-07-07 17:22:45 +00002937 break;
Reka Kovacsc18ecc82018-07-19 15:10:06 +00002938 }
Reka Kovacs8707cd12018-07-07 17:22:45 +00002939 case AF_None:
Reka Kovacs8707cd12018-07-07 17:22:45 +00002940 llvm_unreachable("Unhandled allocation family!");
2941 }
Anna Zaksa7f457a2012-03-16 23:44:28 +00002942 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002943 "Returning; memory was released");
Artem Dergachev5337efc2018-02-27 21:19:33 +00002944
Artem Dergachevff1fc212018-03-21 00:49:47 +00002945 // See if we're releasing memory while inlining a destructor
2946 // (or one of its callees). This turns on various common
2947 // false positive suppressions.
2948 bool FoundAnyDestructor = false;
Artem Dergachev5337efc2018-02-27 21:19:33 +00002949 for (const LocationContext *LC = CurrentLC; LC; LC = LC->getParent()) {
Artem Dergachevff1fc212018-03-21 00:49:47 +00002950 if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
2951 if (isReferenceCountingPointerDestructor(DD)) {
2952 // This immediately looks like a reference-counting destructor.
2953 // We're bad at guessing the original reference count of the object,
2954 // so suppress the report for now.
2955 BR.markInvalid(getTag(), DD);
2956 } else if (!FoundAnyDestructor) {
2957 assert(!ReleaseDestructorLC &&
2958 "There can be only one release point!");
2959 // Suspect that it's a reference counting pointer destructor.
2960 // On one of the next nodes might find out that it has atomic
2961 // reference counting operations within it (see the code above),
2962 // and if so, we'd conclude that it likely is a reference counting
2963 // pointer destructor.
George Karpenkovdd18b112018-06-27 01:51:55 +00002964 ReleaseDestructorLC = LC->getStackFrame();
Artem Dergachevff1fc212018-03-21 00:49:47 +00002965 // It is unlikely that releasing memory is delegated to a destructor
2966 // inside a destructor of a shared pointer, because it's fairly hard
2967 // to pass the information that the pointer indeed needs to be
2968 // released into it. So we're only interested in the innermost
2969 // destructor.
2970 FoundAnyDestructor = true;
2971 }
Artem Dergachev5337efc2018-02-27 21:19:33 +00002972 }
2973 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002974 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002975 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002976 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002977 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002978 Mode = ReallocationFailed;
2979 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002980 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002981 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002982
Jordy Rose21ff76e2012-03-24 03:15:09 +00002983 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2984 // Is it possible to fail two reallocs WITHOUT testing in between?
2985 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2986 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002987 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002988 FailedReallocSymbol = sym;
2989 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002990 }
2991
2992 // We are in a special mode if a reallocation failed later in the path.
2993 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002994 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002995
Jordy Rose21ff76e2012-03-24 03:15:09 +00002996 // Is this is the first appearance of the reallocated symbol?
2997 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002998 // We're at the reallocation point.
2999 Msg = "Attempt to reallocate memory";
3000 StackHint = new StackHintGeneratorForSymbol(Sym,
3001 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00003002 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00003003 Mode = Normal;
3004 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00003005 }
3006
Reka Kovacsa14a2fe2018-07-19 17:43:09 +00003007 if (Msg.empty())
Craig Topper0dbb7832014-05-27 02:45:47 +00003008 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00003009 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00003010
3011 // Generate the extra diagnostic.
Reka Kovacs8707cd12018-07-07 17:22:45 +00003012 PathDiagnosticLocation Pos;
3013 if (!S) {
3014 assert(RS->getAllocationFamily() == AF_InternalBuffer);
3015 auto PostImplCall = N->getLocation().getAs<PostImplicitCall>();
3016 if (!PostImplCall)
3017 return nullptr;
3018 Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3019 BRC.getSourceManager());
3020 } else {
3021 Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3022 N->getLocationContext());
3023 }
3024
David Blaikie0a0c2752017-01-05 17:26:53 +00003025 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00003026}
3027
Anna Zaks263b7e02012-05-02 00:05:20 +00003028void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
3029 const char *NL, const char *Sep) const {
3030
3031 RegionStateTy RS = State->get<RegionState>();
3032
Ted Kremenek6fcefb52013-01-03 01:30:12 +00003033 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00003034 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00003035 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00003036 const RefState *RefS = State->get<RegionState>(I.getKey());
3037 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00003038 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00003039 if (!CheckKind.hasValue())
3040 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00003041
Ted Kremenek6fcefb52013-01-03 01:30:12 +00003042 I.getKey()->dumpToStream(Out);
3043 Out << " : ";
3044 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00003045 if (CheckKind.hasValue())
3046 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00003047 Out << NL;
3048 }
3049 }
Anna Zaks263b7e02012-05-02 00:05:20 +00003050}
Anna Zaks2b5bb972012-02-09 06:25:51 +00003051
Reka Kovacs18775fc2018-06-09 13:03:49 +00003052namespace clang {
3053namespace ento {
3054namespace allocation_state {
3055
3056ProgramStateRef
3057markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
3058 AllocationFamily Family = AF_InternalBuffer;
3059 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3060}
3061
3062} // end namespace allocation_state
3063} // end namespace ento
3064} // end namespace clang
3065
Anna Zakse4cfcd42013-04-16 00:22:55 +00003066void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
3067 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003068 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00003069 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
3070 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003071 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
3072 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
3073 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003074 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00003075 // checker.
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00003076 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003077 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00003078 // FIXME: This does not set the correct name, but without this workaround
3079 // no name will be set at all.
3080 checker->CheckNames[MallocChecker::CK_NewDeleteChecker] =
3081 mgr.getCurrentCheckName();
3082 }
Anna Zakse4cfcd42013-04-16 00:22:55 +00003083}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00003084
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003085#define REGISTER_CHECKER(name) \
3086 void ento::register##name(CheckerManager &mgr) { \
3087 registerCStringCheckerBasic(mgr); \
3088 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00003089 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
3090 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003091 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
3092 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
3093 }
Anna Zakscd37bf42012-02-08 23:16:52 +00003094
Gabor Horvathe40c71c2015-03-04 17:59:34 +00003095REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00003096REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00003097REGISTER_CHECKER(MismatchedDeallocatorChecker)