blob: b008bcdf4ee1eca39abb2d4bd9b5d3b43079e95e [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.
Anton Yartsev13df0362013-03-25 01:35:45 +0000483 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000484 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
485 }
486
Anna Zaks0d6989b2012-06-22 02:04:31 +0000487 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
488 const Stmt *Stmt) {
489 // Did not track -> relinquished. Other state (allocated) -> relinquished.
490 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
491 isa<ObjCPropertyRefExpr>(Stmt)) &&
492 (S && S->isRelinquished()) &&
493 (!SPrev || !SPrev->isRelinquished()));
494 }
495
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000496 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
497 const Stmt *Stmt) {
498 // If the expression is not a call, and the state change is
499 // released -> allocated, it must be the realloc return value
500 // check. If we have to handle more cases here, it might be cleaner just
501 // to track this extra bit in the state itself.
502 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000503 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
504 (SPrev && !(SPrev->isAllocated() ||
505 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000506 }
507
David Blaikie0a0c2752017-01-05 17:26:53 +0000508 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
509 const ExplodedNode *PrevN,
510 BugReporterContext &BRC,
511 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000512
George Karpenkov70ec1dd2018-06-26 21:12:08 +0000513 std::shared_ptr<PathDiagnosticPiece>
David Blaikied15481c2014-08-29 18:18:43 +0000514 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
515 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000516 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000517 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000518
519 PathDiagnosticLocation L =
520 PathDiagnosticLocation::createEndOfPath(EndPathNode,
521 BRC.getSourceManager());
522 // Do not add the statement itself as a range in case of leak.
George Karpenkov70ec1dd2018-06-26 21:12:08 +0000523 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
David Blaikied15481c2014-08-29 18:18:43 +0000524 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000525 }
526
Anna Zakscba4f292012-03-16 23:24:20 +0000527 private:
528 class StackHintGeneratorForReallocationFailed
529 : public StackHintGeneratorForSymbol {
530 public:
531 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
532 : StackHintGeneratorForSymbol(S, M) {}
533
Craig Topperfb6b25b2014-03-15 04:29:04 +0000534 std::string getMessageForArg(const Expr *ArgE,
535 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000536 // Printed parameters start at 1, not 0.
537 ++ArgIndex;
538
Anna Zakscba4f292012-03-16 23:24:20 +0000539 SmallString<200> buf;
540 llvm::raw_svector_ostream os(buf);
541
Jordan Rosec102b352012-09-22 01:24:42 +0000542 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
543 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000544
545 return os.str();
546 }
547
Craig Topperfb6b25b2014-03-15 04:29:04 +0000548 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000549 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000550 }
551 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000552 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000553};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000554} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000555
Jordan Rose0c153cb2012-11-02 01:54:06 +0000556REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
557REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Devin Coughlin81771732015-09-22 22:47:14 +0000558REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000559
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000560// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000561// the free function.
562REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
563
Anna Zaksbb1ef902012-02-11 21:02:35 +0000564namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000565class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000566 ProgramStateRef state;
567public:
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000568 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
Anna Zaksbb1ef902012-02-11 21:02:35 +0000569 ProgramStateRef getState() const { return state; }
570
Craig Topperfb6b25b2014-03-15 04:29:04 +0000571 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000572 state = state->remove<RegionState>(sym);
573 return true;
574 }
575};
576} // end anonymous namespace
577
Anna Zaks3d348342012-02-14 21:55:24 +0000578void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000579 if (II_malloc)
580 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000581 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000582 II_malloc = &Ctx.Idents.get("malloc");
583 II_free = &Ctx.Idents.get("free");
584 II_realloc = &Ctx.Idents.get("realloc");
585 II_reallocf = &Ctx.Idents.get("reallocf");
586 II_calloc = &Ctx.Idents.get("calloc");
587 II_valloc = &Ctx.Idents.get("valloc");
588 II_strdup = &Ctx.Idents.get("strdup");
589 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaks30d46682016-03-08 01:21:51 +0000590 II_wcsdup = &Ctx.Idents.get("wcsdup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000591 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000592 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
593 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaks30d46682016-03-08 01:21:51 +0000594
595 //MSVC uses `_`-prefixed instead, so we check for them too.
596 II_win_strdup = &Ctx.Idents.get("_strdup");
597 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
598 II_win_alloca = &Ctx.Idents.get("_alloca");
Anna Zaksbbec97c2017-03-09 00:01:01 +0000599
600 // Glib
601 II_g_malloc = &Ctx.Idents.get("g_malloc");
602 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
603 II_g_realloc = &Ctx.Idents.get("g_realloc");
604 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
605 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
606 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
607 II_g_free = &Ctx.Idents.get("g_free");
608 II_g_memdup = &Ctx.Idents.get("g_memdup");
Leslie Zhaie3986c52017-04-26 05:33:14 +0000609 II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
610 II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
611 II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
612 II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
613 II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
614 II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000615}
616
Anna Zaks3d348342012-02-14 21:55:24 +0000617bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000618 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000619 return true;
620
Anna Zaksd79b8402014-10-03 21:48:59 +0000621 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000622 return true;
623
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000624 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
625 return true;
626
Anton Yartsev13df0362013-03-25 01:35:45 +0000627 if (isStandardNewDelete(FD, C))
628 return true;
629
Anna Zaks46d01602012-05-18 01:16:10 +0000630 return false;
631}
632
Anna Zaksd79b8402014-10-03 21:48:59 +0000633bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
634 ASTContext &C,
635 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000636 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000637 if (!FD)
638 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000639
Anna Zaksd79b8402014-10-03 21:48:59 +0000640 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
641 MemKind == MemoryOperationKind::MOK_Free);
642 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
643 MemKind == MemoryOperationKind::MOK_Allocate);
644
Jordan Rose6cd16c52012-07-10 23:13:01 +0000645 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000646 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000647 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000648
Anna Zaksd79b8402014-10-03 21:48:59 +0000649 if (Family == AF_Malloc && CheckFree) {
Anna Zaksbbec97c2017-03-09 00:01:01 +0000650 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
651 FunI == II_g_free)
Anna Zaksd79b8402014-10-03 21:48:59 +0000652 return true;
653 }
654
655 if (Family == AF_Malloc && CheckAlloc) {
656 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
657 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
Anna Zaks30d46682016-03-08 01:21:51 +0000658 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
Anna Zaksbbec97c2017-03-09 00:01:01 +0000659 FunI == II_win_wcsdup || FunI == II_kmalloc ||
660 FunI == II_g_malloc || FunI == II_g_malloc0 ||
661 FunI == II_g_realloc || FunI == II_g_try_malloc ||
662 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
Leslie Zhaie3986c52017-04-26 05:33:14 +0000663 FunI == II_g_memdup || FunI == II_g_malloc_n ||
664 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
665 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
666 FunI == II_g_try_realloc_n)
Anna Zaksd79b8402014-10-03 21:48:59 +0000667 return true;
668 }
669
670 if (Family == AF_IfNameIndex && CheckFree) {
671 if (FunI == II_if_freenameindex)
672 return true;
673 }
674
675 if (Family == AF_IfNameIndex && CheckAlloc) {
676 if (FunI == II_if_nameindex)
677 return true;
678 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000679
680 if (Family == AF_Alloca && CheckAlloc) {
Anna Zaks30d46682016-03-08 01:21:51 +0000681 if (FunI == II_alloca || FunI == II_win_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000682 return true;
683 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000684 }
Anna Zaks3d348342012-02-14 21:55:24 +0000685
Anna Zaksd79b8402014-10-03 21:48:59 +0000686 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000687 return false;
688
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000689 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000690 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
691 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
692 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
693 if (CheckFree)
694 return true;
695 } else if (OwnKind == OwnershipAttr::Returns) {
696 if (CheckAlloc)
697 return true;
698 }
699 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000700 }
Anna Zaks3d348342012-02-14 21:55:24 +0000701
Anna Zaks3d348342012-02-14 21:55:24 +0000702 return false;
703}
704
Anton Yartsev8b662702013-03-28 16:10:38 +0000705// Tells if the callee is one of the following:
706// 1) A global non-placement new/delete operator function.
707// 2) A global placement operator function with the single placement argument
708// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000709bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
710 ASTContext &C) const {
711 if (!FD)
712 return false;
713
714 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000715 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000716 Kind != OO_Delete && Kind != OO_Array_Delete)
717 return false;
718
Anton Yartsev8b662702013-03-28 16:10:38 +0000719 // Skip all operator new/delete methods.
720 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000721 return false;
722
723 // Return true if tested operator is a standard placement nothrow operator.
724 if (FD->getNumParams() == 2) {
725 QualType T = FD->getParamDecl(1)->getType();
726 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
727 return II->getName().equals("nothrow_t");
728 }
729
730 // Skip placement operators.
731 if (FD->getNumParams() != 1 || FD->isVariadic())
732 return false;
733
734 // One of the standard new/new[]/delete/delete[] non-placement operators.
735 return true;
736}
737
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000738llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
739 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
740 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
741 //
742 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
743 //
744 // One of the possible flags is M_ZERO, which means 'give me back an
745 // allocation which is already zeroed', like calloc.
746
747 // 2-argument kmalloc(), as used in the Linux kernel:
748 //
749 // void *kmalloc(size_t size, gfp_t flags);
750 //
751 // Has the similar flag value __GFP_ZERO.
752
753 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
754 // code could be shared.
755
756 ASTContext &Ctx = C.getASTContext();
757 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
758
759 if (!KernelZeroFlagVal.hasValue()) {
760 if (OS == llvm::Triple::FreeBSD)
761 KernelZeroFlagVal = 0x0100;
762 else if (OS == llvm::Triple::NetBSD)
763 KernelZeroFlagVal = 0x0002;
764 else if (OS == llvm::Triple::OpenBSD)
765 KernelZeroFlagVal = 0x0008;
766 else if (OS == llvm::Triple::Linux)
767 // __GFP_ZERO
768 KernelZeroFlagVal = 0x8000;
769 else
770 // FIXME: We need a more general way of getting the M_ZERO value.
771 // See also: O_CREAT in UnixAPIChecker.cpp.
772
773 // Fall back to normal malloc behavior on platforms where we don't
774 // know M_ZERO.
775 return None;
776 }
777
778 // We treat the last argument as the flags argument, and callers fall-back to
779 // normal malloc on a None return. This works for the FreeBSD kernel malloc
780 // as well as Linux kmalloc.
781 if (CE->getNumArgs() < 2)
782 return None;
783
784 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
George Karpenkovd703ec92018-01-17 20:27:29 +0000785 const SVal V = C.getSVal(FlagsEx);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000786 if (!V.getAs<NonLoc>()) {
787 // The case where 'V' can be a location can only be due to a bad header,
788 // so in this case bail out.
789 return None;
790 }
791
792 NonLoc Flags = V.castAs<NonLoc>();
793 NonLoc ZeroFlag = C.getSValBuilder()
794 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
795 .castAs<NonLoc>();
796 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
797 Flags, ZeroFlag,
798 FlagsEx->getType());
799 if (MaskedFlagsUC.isUnknownOrUndef())
800 return None;
801 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
802
803 // Check if maskedFlags is non-zero.
804 ProgramStateRef TrueState, FalseState;
805 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
806
807 // If M_ZERO is set, treat this like calloc (initialized).
808 if (TrueState && !FalseState) {
809 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
810 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
811 }
812
813 return None;
814}
815
Leslie Zhaie3986c52017-04-26 05:33:14 +0000816SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
817 const Expr *BlockBytes) {
818 SValBuilder &SB = C.getSValBuilder();
819 SVal BlocksVal = C.getSVal(Blocks);
820 SVal BlockBytesVal = C.getSVal(BlockBytes);
821 ProgramStateRef State = C.getState();
822 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
823 SB.getContext().getSizeType());
824 return TotalSize;
825}
826
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000827void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000828 if (C.wasInlined)
829 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000830
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000831 const FunctionDecl *FD = C.getCalleeDecl(CE);
832 if (!FD)
833 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000834
Anna Zaks40a7eb32012-02-22 19:24:52 +0000835 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000836 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000837
838 if (FD->getKind() == Decl::Function) {
839 initIdentifierInfo(C.getASTContext());
840 IdentifierInfo *FunI = FD->getIdentifier();
841
Anna Zaksbbec97c2017-03-09 00:01:01 +0000842 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000843 if (CE->getNumArgs() < 1)
844 return;
845 if (CE->getNumArgs() < 3) {
846 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000847 if (CE->getNumArgs() == 1)
848 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000849 } else if (CE->getNumArgs() == 3) {
850 llvm::Optional<ProgramStateRef> MaybeState =
851 performKernelMalloc(CE, C, State);
852 if (MaybeState.hasValue())
853 State = MaybeState.getValue();
854 else
855 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
856 }
857 } else if (FunI == II_kmalloc) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000858 if (CE->getNumArgs() < 1)
859 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000860 llvm::Optional<ProgramStateRef> MaybeState =
861 performKernelMalloc(CE, C, State);
862 if (MaybeState.hasValue())
863 State = MaybeState.getValue();
864 else
865 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
866 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000867 if (CE->getNumArgs() < 1)
868 return;
869 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000870 State = ProcessZeroAllocation(C, CE, 0, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000871 } else if (FunI == II_realloc || FunI == II_g_realloc ||
872 FunI == II_g_try_realloc) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000873 State = ReallocMemAux(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000874 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000875 } else if (FunI == II_reallocf) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000876 State = ReallocMemAux(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000877 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000878 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000879 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000880 State = ProcessZeroAllocation(C, CE, 0, State);
881 State = ProcessZeroAllocation(C, CE, 1, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000882 } else if (FunI == II_free || FunI == II_g_free) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000883 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaks30d46682016-03-08 01:21:51 +0000884 } else if (FunI == II_strdup || FunI == II_win_strdup ||
885 FunI == II_wcsdup || FunI == II_win_wcsdup) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000886 State = MallocUpdateRefState(C, CE, State);
887 } else if (FunI == II_strndup) {
888 State = MallocUpdateRefState(C, CE, State);
Anna Zaks30d46682016-03-08 01:21:51 +0000889 } else if (FunI == II_alloca || FunI == II_win_alloca) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000890 if (CE->getNumArgs() < 1)
891 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000892 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
893 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000894 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000895 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000896 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000897 // as distinct from new/new[]/delete/delete[] expressions that are
898 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000899 // CXXDeleteExpr.
900 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000901 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000902 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
903 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000904 State = ProcessZeroAllocation(C, CE, 0, State);
905 }
906 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000907 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
908 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000909 State = ProcessZeroAllocation(C, CE, 0, State);
910 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000911 else if (K == OO_Delete || K == OO_Array_Delete)
912 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
913 else
914 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000915 } else if (FunI == II_if_nameindex) {
916 // Should we model this differently? We can allocate a fixed number of
917 // elements with zeros in the last one.
918 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
919 AF_IfNameIndex);
920 } else if (FunI == II_if_freenameindex) {
921 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000922 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
923 if (CE->getNumArgs() < 1)
924 return;
925 SValBuilder &svalBuilder = C.getSValBuilder();
926 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
927 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
928 State = ProcessZeroAllocation(C, CE, 0, State);
929 } else if (FunI == II_g_memdup) {
930 if (CE->getNumArgs() < 2)
931 return;
932 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
933 State = ProcessZeroAllocation(C, CE, 1, State);
Leslie Zhaie3986c52017-04-26 05:33:14 +0000934 } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
935 FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
936 if (CE->getNumArgs() < 2)
937 return;
938 SVal Init = UndefinedVal();
939 if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
940 SValBuilder &SB = C.getSValBuilder();
941 Init = SB.makeZeroVal(SB.getContext().CharTy);
942 }
943 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
944 State = MallocMemAux(C, CE, TotalSize, Init, State);
945 State = ProcessZeroAllocation(C, CE, 0, State);
946 State = ProcessZeroAllocation(C, CE, 1, State);
947 } else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
948 if (CE->getNumArgs() < 3)
949 return;
950 State = ReallocMemAux(C, CE, false, State, true);
951 State = ProcessZeroAllocation(C, CE, 1, State);
952 State = ProcessZeroAllocation(C, CE, 2, State);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000953 }
954 }
955
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000956 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000957 // Check all the attributes, if there are any.
958 // There can be multiple of these attributes.
959 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000960 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
961 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000962 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000963 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000964 break;
965 case OwnershipAttr::Takes:
966 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000967 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000968 break;
969 }
970 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000971 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000972 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000973}
974
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000975// Performs a 0-sized allocations check.
Artem Dergachev13b20262018-01-17 23:46:13 +0000976ProgramStateRef MallocChecker::ProcessZeroAllocation(
977 CheckerContext &C, const Expr *E, const unsigned AllocationSizeArg,
978 ProgramStateRef State, Optional<SVal> RetVal) const {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000979 if (!State)
980 return nullptr;
981
Artem Dergachev13b20262018-01-17 23:46:13 +0000982 if (!RetVal)
983 RetVal = C.getSVal(E);
984
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000985 const Expr *Arg = nullptr;
986
987 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
988 Arg = CE->getArg(AllocationSizeArg);
989 }
990 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
991 if (NE->isArray())
992 Arg = NE->getArraySize();
993 else
994 return State;
995 }
996 else
997 llvm_unreachable("not a CallExpr or CXXNewExpr");
998
999 assert(Arg);
1000
George Karpenkovd703ec92018-01-17 20:27:29 +00001001 Optional<DefinedSVal> DefArgVal = C.getSVal(Arg).getAs<DefinedSVal>();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001002
1003 if (!DefArgVal)
1004 return State;
1005
1006 // Check if the allocation size is 0.
1007 ProgramStateRef TrueState, FalseState;
1008 SValBuilder &SvalBuilder = C.getSValBuilder();
1009 DefinedSVal Zero =
1010 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1011
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001012 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001013 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1014
1015 if (TrueState && !FalseState) {
Artem Dergachev13b20262018-01-17 23:46:13 +00001016 SymbolRef Sym = RetVal->getAsLocSymbol();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001017 if (!Sym)
1018 return State;
1019
1020 const RefState *RS = State->get<RegionState>(Sym);
Devin Coughlin81771732015-09-22 22:47:14 +00001021 if (RS) {
1022 if (RS->isAllocated())
1023 return TrueState->set<RegionState>(Sym,
1024 RefState::getAllocatedOfSizeZero(RS));
1025 else
1026 return State;
1027 } else {
1028 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1029 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1030 // tracked. Add zero-reallocated Sym to the state to catch references
1031 // to zero-allocated memory.
1032 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1033 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001034 }
1035
1036 // Assume the value is non-zero going forward.
1037 assert(FalseState);
1038 return FalseState;
1039}
1040
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001041static QualType getDeepPointeeType(QualType T) {
1042 QualType Result = T, PointeeType = T->getPointeeType();
1043 while (!PointeeType.isNull()) {
1044 Result = PointeeType;
1045 PointeeType = PointeeType->getPointeeType();
1046 }
1047 return Result;
1048}
1049
1050static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1051
1052 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1053 if (!ConstructE)
1054 return false;
1055
1056 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1057 return false;
1058
1059 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1060
1061 // Iterate over the constructor parameters.
David Majnemer59f77922016-06-24 04:05:48 +00001062 for (const auto *CtorParam : CtorD->parameters()) {
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001063
1064 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1065 if (CtorParamPointeeT.isNull())
1066 continue;
1067
1068 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1069
1070 if (CtorParamPointeeT->getAsCXXRecordDecl())
1071 return true;
1072 }
1073
1074 return false;
1075}
1076
Artem Dergachev13b20262018-01-17 23:46:13 +00001077void MallocChecker::processNewAllocation(const CXXNewExpr *NE,
1078 CheckerContext &C,
1079 SVal Target) const {
Anton Yartsev13df0362013-03-25 01:35:45 +00001080 if (NE->getNumPlacementArgs())
1081 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1082 E = NE->placement_arg_end(); I != E; ++I)
1083 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1084 checkUseAfterFree(Sym, C, *I);
1085
Anton Yartsev13df0362013-03-25 01:35:45 +00001086 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1087 return;
1088
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001089 ParentMap &PM = C.getLocationContext()->getParentMap();
1090 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1091 return;
1092
Anton Yartsev13df0362013-03-25 01:35:45 +00001093 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001094 // The return value from operator new is bound to a specified initialization
1095 // value (if any) and we don't want to loose this value. So we call
1096 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +00001097 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001098 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Artem Dergachev13b20262018-01-17 23:46:13 +00001099 : AF_CXXNew, Target);
1100 State = addExtentSize(C, NE, State, Target);
1101 State = ProcessZeroAllocation(C, NE, 0, State, Target);
Anton Yartsev13df0362013-03-25 01:35:45 +00001102 C.addTransition(State);
1103}
1104
Artem Dergachev13b20262018-01-17 23:46:13 +00001105void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1106 CheckerContext &C) const {
1107 if (!C.getAnalysisManager().getAnalyzerOptions().mayInlineCXXAllocator())
1108 processNewAllocation(NE, C, C.getSVal(NE));
1109}
1110
1111void MallocChecker::checkNewAllocator(const CXXNewExpr *NE, SVal Target,
1112 CheckerContext &C) const {
1113 if (!C.wasInlined)
1114 processNewAllocation(NE, C, Target);
1115}
1116
Gabor Horvath73040272016-09-19 20:39:52 +00001117// Sets the extent value of the MemRegion allocated by
1118// new expression NE to its size in Bytes.
1119//
1120ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1121 const CXXNewExpr *NE,
Artem Dergachev13b20262018-01-17 23:46:13 +00001122 ProgramStateRef State,
1123 SVal Target) {
Gabor Horvath73040272016-09-19 20:39:52 +00001124 if (!State)
1125 return nullptr;
1126 SValBuilder &svalBuilder = C.getSValBuilder();
1127 SVal ElementCount;
Gabor Horvath73040272016-09-19 20:39:52 +00001128 const SubRegion *Region;
1129 if (NE->isArray()) {
1130 const Expr *SizeExpr = NE->getArraySize();
George Karpenkovd703ec92018-01-17 20:27:29 +00001131 ElementCount = C.getSVal(SizeExpr);
Gabor Horvath73040272016-09-19 20:39:52 +00001132 // Store the extent size for the (symbolic)region
1133 // containing the elements.
Artem Dergachev13b20262018-01-17 23:46:13 +00001134 Region = Target.getAsRegion()
Gabor Horvath73040272016-09-19 20:39:52 +00001135 ->getAs<SubRegion>()
Artem Dergachev13b20262018-01-17 23:46:13 +00001136 ->StripCasts()
Gabor Horvath73040272016-09-19 20:39:52 +00001137 ->getAs<SubRegion>();
1138 } else {
1139 ElementCount = svalBuilder.makeIntVal(1, true);
Artem Dergachev13b20262018-01-17 23:46:13 +00001140 Region = Target.getAsRegion()->getAs<SubRegion>();
Gabor Horvath73040272016-09-19 20:39:52 +00001141 }
1142 assert(Region);
1143
1144 // Set the region's extent equal to the Size in Bytes.
1145 QualType ElementType = NE->getAllocatedType();
1146 ASTContext &AstContext = C.getASTContext();
1147 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1148
Devin Coughline3b75de2016-12-16 18:41:40 +00001149 if (ElementCount.getAs<NonLoc>()) {
Gabor Horvath73040272016-09-19 20:39:52 +00001150 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1151 // size in Bytes = ElementCount*TypeSize
1152 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1153 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1154 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1155 svalBuilder.getArrayIndexType());
1156 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1157 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1158 State = State->assume(extentMatchesSize, true);
1159 }
1160 return State;
1161}
1162
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001163void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001164 CheckerContext &C) const {
1165
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001166 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +00001167 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1168 checkUseAfterFree(Sym, C, DE->getArgument());
1169
Anton Yartsev13df0362013-03-25 01:35:45 +00001170 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1171 return;
1172
1173 ProgramStateRef State = C.getState();
1174 bool ReleasedAllocated;
1175 State = FreeMemAux(C, DE->getArgument(), DE, State,
1176 /*Hold*/false, ReleasedAllocated);
1177
1178 C.addTransition(State);
1179}
1180
Jordan Rose613f3c02013-03-09 00:59:10 +00001181static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1182 // If the first selector piece is one of the names below, assume that the
1183 // object takes ownership of the memory, promising to eventually deallocate it
1184 // with free().
1185 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1186 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1187 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
Alexander Kornienko9c104902015-12-28 13:06:58 +00001188 return FirstSlot == "dataWithBytesNoCopy" ||
1189 FirstSlot == "initWithBytesNoCopy" ||
1190 FirstSlot == "initWithCharactersNoCopy";
Anna Zaks0d6989b2012-06-22 02:04:31 +00001191}
1192
Jordan Rose613f3c02013-03-09 00:59:10 +00001193static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1194 Selector S = Call.getSelector();
1195
1196 // FIXME: We should not rely on fully-constrained symbols being folded.
1197 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1198 if (S.getNameForSlot(i).equals("freeWhenDone"))
1199 return !Call.getArgSVal(i).isZeroConstant();
1200
1201 return None;
1202}
1203
Anna Zaks67291b92012-11-13 03:18:01 +00001204void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1205 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001206 if (C.wasInlined)
1207 return;
1208
Jordan Rose613f3c02013-03-09 00:59:10 +00001209 if (!isKnownDeallocObjCMethodName(Call))
1210 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001211
Jordan Rose613f3c02013-03-09 00:59:10 +00001212 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1213 if (!*FreeWhenDone)
1214 return;
1215
1216 bool ReleasedAllocatedMemory;
1217 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1218 Call.getOriginExpr(), C.getState(),
1219 /*Hold=*/true, ReleasedAllocatedMemory,
1220 /*RetNullOnFailure=*/true);
1221
1222 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001223}
1224
Richard Smith852e9ce2013-11-27 01:46:48 +00001225ProgramStateRef
1226MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001227 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001228 ProgramStateRef State) const {
1229 if (!State)
1230 return nullptr;
1231
Richard Smith852e9ce2013-11-27 01:46:48 +00001232 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001233 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001234
Joel E. Dennya6555112018-04-02 19:43:34 +00001235 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001236 if (I != E) {
Joel E. Denny81508102018-03-13 14:51:22 +00001237 return MallocMemAux(C, CE, CE->getArg(I->getASTIndex()), UndefinedVal(),
1238 State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001239 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001240 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1241}
1242
1243ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1244 const CallExpr *CE,
1245 const Expr *SizeEx, SVal Init,
1246 ProgramStateRef State,
1247 AllocationFamily Family) {
1248 if (!State)
1249 return nullptr;
1250
George Karpenkovd703ec92018-01-17 20:27:29 +00001251 return MallocMemAux(C, CE, C.getSVal(SizeEx), Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001252}
1253
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001254ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001255 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001256 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001257 ProgramStateRef State,
1258 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001259 if (!State)
1260 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001261
Jordan Rosef69e65f2014-09-05 16:33:51 +00001262 // We expect the malloc functions to return a pointer.
1263 if (!Loc::isLocType(CE->getType()))
1264 return nullptr;
1265
Anna Zaks3563fde2012-06-07 03:57:32 +00001266 // Bind the return value to the symbolic value from the heap region.
1267 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1268 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001269 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001270 SValBuilder &svalBuilder = C.getSValBuilder();
1271 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001272 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1273 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001274 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001275
Jordy Rose674bd552010-07-04 00:00:41 +00001276 // Fill the region with the initialization value.
Artem Dergachev806486c2018-05-04 21:56:51 +00001277 State = State->bindDefaultInitial(RetVal, Init, LCtx);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001278
Jordy Rose674bd552010-07-04 00:00:41 +00001279 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001280 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001281 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001282 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001283 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001284 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001285 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001286 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001287 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001288 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001289 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001290
Anton Yartsev05789592013-03-28 17:05:19 +00001291 State = State->assume(extentMatchesSize, true);
1292 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001293 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001294
Anton Yartsev05789592013-03-28 17:05:19 +00001295 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001296}
1297
1298ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001299 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001300 ProgramStateRef State,
Artem Dergachev13b20262018-01-17 23:46:13 +00001301 AllocationFamily Family,
1302 Optional<SVal> RetVal) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001303 if (!State)
1304 return nullptr;
1305
Anna Zaks40a7eb32012-02-22 19:24:52 +00001306 // Get the return value.
Artem Dergachev13b20262018-01-17 23:46:13 +00001307 if (!RetVal)
1308 RetVal = C.getSVal(E);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001309
1310 // We expect the malloc functions to return a pointer.
Artem Dergachev13b20262018-01-17 23:46:13 +00001311 if (!RetVal->getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001312 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001313
Artem Dergachev13b20262018-01-17 23:46:13 +00001314 SymbolRef Sym = RetVal->getAsLocSymbol();
1315 // This is a return value of a function that was not inlined, such as malloc()
1316 // or new(). We've checked that in the caller. Therefore, it must be a symbol.
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001317 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001318
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001319 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001320 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001321}
1322
Anna Zaks40a7eb32012-02-22 19:24:52 +00001323ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1324 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001325 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001326 ProgramStateRef State) const {
1327 if (!State)
1328 return nullptr;
1329
Richard Smith852e9ce2013-11-27 01:46:48 +00001330 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001331 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001332
Anna Zaksfe6eb672012-08-24 02:28:20 +00001333 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001334
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001335 for (const auto &Arg : Att->args()) {
Joel E. Denny81508102018-03-13 14:51:22 +00001336 ProgramStateRef StateI = FreeMemAux(
1337 C, CE, State, Arg.getASTIndex(),
1338 Att->getOwnKind() == OwnershipAttr::Holds, ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001339 if (StateI)
1340 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001341 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001342 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001343}
1344
Ted Kremenek49b1e382012-01-26 21:29:00 +00001345ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001346 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001347 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001348 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001349 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001350 bool &ReleasedAllocated,
1351 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001352 if (!State)
1353 return nullptr;
1354
Anna Zaksb508d292012-04-10 23:41:11 +00001355 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001356 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001357
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001358 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001359 ReleasedAllocated, ReturnsNullOnFailure);
1360}
1361
Anna Zaksa14c1d02012-11-13 19:47:40 +00001362/// Checks if the previous call to free on the given symbol failed - if free
1363/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001364static bool didPreviousFreeFail(ProgramStateRef State,
1365 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001366 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001367 if (Ret) {
1368 assert(*Ret && "We should not store the null return symbol");
1369 ConstraintManager &CMgr = State->getConstraintManager();
1370 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001371 RetStatusSymbol = *Ret;
1372 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001373 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001374 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001375}
1376
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001377AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001378 const Stmt *S) const {
1379 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001380 return AF_None;
1381
Anton Yartseve3377fb2013-04-04 23:46:29 +00001382 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001383 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001384
1385 if (!FD)
1386 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1387
Anton Yartsev05789592013-03-28 17:05:19 +00001388 ASTContext &Ctx = C.getASTContext();
1389
Anna Zaksd79b8402014-10-03 21:48:59 +00001390 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001391 return AF_Malloc;
1392
1393 if (isStandardNewDelete(FD, Ctx)) {
1394 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001395 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001396 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001397 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001398 return AF_CXXNewArray;
1399 }
1400
Anna Zaksd79b8402014-10-03 21:48:59 +00001401 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1402 return AF_IfNameIndex;
1403
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001404 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1405 return AF_Alloca;
1406
Anton Yartsev05789592013-03-28 17:05:19 +00001407 return AF_None;
1408 }
1409
Anton Yartseve3377fb2013-04-04 23:46:29 +00001410 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1411 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1412
1413 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001414 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1415
Anton Yartseve3377fb2013-04-04 23:46:29 +00001416 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001417 return AF_Malloc;
1418
1419 return AF_None;
1420}
1421
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001422bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001423 const Expr *E) const {
1424 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1425 // FIXME: This doesn't handle indirect calls.
1426 const FunctionDecl *FD = CE->getDirectCallee();
1427 if (!FD)
1428 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001429
Anton Yartsev05789592013-03-28 17:05:19 +00001430 os << *FD;
1431 if (!FD->isOverloadedOperator())
1432 os << "()";
1433 return true;
1434 }
1435
1436 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1437 if (Msg->isInstanceMessage())
1438 os << "-";
1439 else
1440 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001441 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001442 return true;
1443 }
1444
1445 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001446 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001447 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1448 << "'";
1449 return true;
1450 }
1451
1452 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001453 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001454 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1455 << "'";
1456 return true;
1457 }
1458
1459 return false;
1460}
1461
1462void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1463 const Expr *E) const {
1464 AllocationFamily Family = getAllocationFamily(C, E);
1465
1466 switch(Family) {
1467 case AF_Malloc: os << "malloc()"; return;
1468 case AF_CXXNew: os << "'new'"; return;
1469 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001470 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Reka Kovacs18775fc2018-06-09 13:03:49 +00001471 case AF_InternalBuffer: os << "container-specific allocator"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001472 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001473 case AF_None: llvm_unreachable("not a deallocation expression");
1474 }
1475}
1476
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001477void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001478 AllocationFamily Family) const {
1479 switch(Family) {
1480 case AF_Malloc: os << "free()"; return;
1481 case AF_CXXNew: os << "'delete'"; return;
1482 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001483 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Reka Kovacs18775fc2018-06-09 13:03:49 +00001484 case AF_InternalBuffer: os << "container-specific deallocator"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001485 case AF_Alloca:
1486 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001487 }
1488}
1489
Anna Zaks0d6989b2012-06-22 02:04:31 +00001490ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1491 const Expr *ArgExpr,
1492 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001493 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001494 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001495 bool &ReleasedAllocated,
1496 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001497
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001498 if (!State)
1499 return nullptr;
1500
George Karpenkovd703ec92018-01-17 20:27:29 +00001501 SVal ArgVal = C.getSVal(ArgExpr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001502 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001503 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001504 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001505
1506 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001507 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001508 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001509
Anna Zaksad01ef52012-02-14 00:26:13 +00001510 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001511 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001512 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001513 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001514 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001515
Jordy Rose3597b212010-06-07 19:32:37 +00001516 // Unknown values could easily be okay
1517 // Undefined values are handled elsewhere
1518 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001519 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001520
Jordy Rose3597b212010-06-07 19:32:37 +00001521 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001522
Jordy Rose3597b212010-06-07 19:32:37 +00001523 // Nonlocs can't be freed, of course.
1524 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1525 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001526 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001527 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001528 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001529
Jordy Rose3597b212010-06-07 19:32:37 +00001530 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001531
Jordy Rose3597b212010-06-07 19:32:37 +00001532 // Blocks might show up as heap data, but should not be free()d
1533 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001534 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001535 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001536 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001537
Jordy Rose3597b212010-06-07 19:32:37 +00001538 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001539
1540 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001541 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001542 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1543 // FIXME: at the time this code was written, malloc() regions were
1544 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1545 // This means that there isn't actually anything from HeapSpaceRegion
1546 // that should be freed, even though we allow it here.
1547 // Of course, free() can work on memory allocated outside the current
1548 // function, so UnknownSpaceRegion is always a possibility.
1549 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001550
1551 if (isa<AllocaRegion>(R))
1552 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1553 else
1554 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1555
Craig Topper0dbb7832014-05-27 02:45:47 +00001556 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001557 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001558
1559 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001560 // Various cases could lead to non-symbol values here.
1561 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001562 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001563 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001564
Anna Zaksc89ad072013-02-07 23:05:47 +00001565 SymbolRef SymBase = SrBase->getSymbol();
1566 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001567 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001568
Anton Yartseve3377fb2013-04-04 23:46:29 +00001569 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001570
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001571 // Memory returned by alloca() shouldn't be freed.
1572 if (RsBase->getAllocationFamily() == AF_Alloca) {
1573 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1574 return nullptr;
1575 }
1576
Anna Zaks93a21a82013-04-09 00:30:28 +00001577 // Check for double free first.
1578 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001579 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1580 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1581 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001582 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001583
Anna Zaks93a21a82013-04-09 00:30:28 +00001584 // If the pointer is allocated or escaped, but we are now trying to free it,
1585 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001586 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001587 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001588
1589 // Check if an expected deallocation function matches the real one.
1590 bool DeallocMatchesAlloc =
1591 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1592 if (!DeallocMatchesAlloc) {
1593 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001594 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001595 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001596 }
1597
1598 // Check if the memory location being freed is the actual location
1599 // allocated, or an offset.
1600 RegionOffset Offset = R->getAsOffset();
1601 if (Offset.isValid() &&
1602 !Offset.hasSymbolicOffset() &&
1603 Offset.getOffset() != 0) {
1604 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001605 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001606 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001607 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001608 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001609 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001610 }
1611
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00001612 if (SymBase->getType()->isFunctionPointerType()) {
1613 ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1614 return nullptr;
1615 }
1616
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001617 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001618 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001619
Anna Zaksa14c1d02012-11-13 19:47:40 +00001620 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001621 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001622
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001623 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001624 // failed.
1625 if (ReturnsNullOnFailure) {
1626 SVal RetVal = C.getSVal(ParentExpr);
1627 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1628 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001629 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1630 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001631 }
1632 }
1633
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001634 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1635 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001636 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001637 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001638 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001639 RefState::getRelinquished(Family,
1640 ParentExpr));
1641
1642 return State->set<RegionState>(SymBase,
1643 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001644}
1645
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001646Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001647MallocChecker::getCheckIfTracked(AllocationFamily Family,
1648 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001649 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001650 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001651 case AF_Alloca:
1652 case AF_IfNameIndex: {
1653 if (ChecksEnabled[CK_MallocChecker])
1654 return CK_MallocChecker;
1655
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001656 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001657 }
1658 case AF_CXXNew:
Reka Kovacs18775fc2018-06-09 13:03:49 +00001659 case AF_CXXNewArray:
1660 // FIXME: Add new CheckKind for AF_InternalBuffer.
1661 case AF_InternalBuffer: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001662 if (IsALeakCheck) {
1663 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1664 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001665 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001666 else {
1667 if (ChecksEnabled[CK_NewDeleteChecker])
1668 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001669 }
1670 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001671 }
1672 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001673 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001674 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001675 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001676 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001677}
1678
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001679Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001680MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001681 const Stmt *AllocDeallocStmt,
1682 bool IsALeakCheck) const {
1683 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1684 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001685}
1686
1687Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001688MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1689 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001690 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1691 return CK_MallocChecker;
1692
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001693 const RefState *RS = C.getState()->get<RegionState>(Sym);
1694 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001695 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001696}
1697
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001698bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001699 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001700 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001701 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001702 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001703 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001704 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001705 else
1706 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001707
Jordy Rose3597b212010-06-07 19:32:37 +00001708 return true;
1709}
1710
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001711bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001712 const MemRegion *MR) {
1713 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +00001714 case MemRegion::FunctionCodeRegionKind: {
1715 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001716 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001717 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001718 else
1719 os << "the address of a function";
1720 return true;
1721 }
Artem Dergachev73f018e2016-01-13 13:49:29 +00001722 case MemRegion::BlockCodeRegionKind:
Jordy Rose3597b212010-06-07 19:32:37 +00001723 os << "block text";
1724 return true;
1725 case MemRegion::BlockDataRegionKind:
1726 // FIXME: where the block came from?
1727 os << "a block";
1728 return true;
1729 default: {
1730 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001731
Anna Zaks8158ef02012-01-04 23:54:01 +00001732 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001733 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1734 const VarDecl *VD;
1735 if (VR)
1736 VD = VR->getDecl();
1737 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001738 VD = nullptr;
1739
Jordy Rose3597b212010-06-07 19:32:37 +00001740 if (VD)
1741 os << "the address of the local variable '" << VD->getName() << "'";
1742 else
1743 os << "the address of a local stack variable";
1744 return true;
1745 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001746
1747 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001748 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1749 const VarDecl *VD;
1750 if (VR)
1751 VD = VR->getDecl();
1752 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001753 VD = nullptr;
1754
Jordy Rose3597b212010-06-07 19:32:37 +00001755 if (VD)
1756 os << "the address of the parameter '" << VD->getName() << "'";
1757 else
1758 os << "the address of a parameter";
1759 return true;
1760 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001761
1762 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001763 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1764 const VarDecl *VD;
1765 if (VR)
1766 VD = VR->getDecl();
1767 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001768 VD = nullptr;
1769
Jordy Rose3597b212010-06-07 19:32:37 +00001770 if (VD) {
1771 if (VD->isStaticLocal())
1772 os << "the address of the static variable '" << VD->getName() << "'";
1773 else
1774 os << "the address of the global variable '" << VD->getName() << "'";
1775 } else
1776 os << "the address of a global variable";
1777 return true;
1778 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001779
1780 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001781 }
1782 }
1783}
1784
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001785void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1786 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001787 const Expr *DeallocExpr) const {
1788
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001789 if (!ChecksEnabled[CK_MallocChecker] &&
1790 !ChecksEnabled[CK_NewDeleteChecker])
1791 return;
1792
1793 Optional<MallocChecker::CheckKind> CheckKind =
1794 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001795 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001796 return;
1797
Devin Coughline39bd402015-09-16 22:03:05 +00001798 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001799 if (!BT_BadFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001800 BT_BadFree[*CheckKind].reset(new BugType(
1801 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001802
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001803 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001804 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001805
Jordy Rose3597b212010-06-07 19:32:37 +00001806 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001807 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1808 MR = ER->getSuperRegion();
1809
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001810 os << "Argument to ";
1811 if (!printAllocDeallocName(os, C, DeallocExpr))
1812 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001813
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001814 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001815 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001816 : SummarizeValue(os, ArgVal);
1817 if (Summarized)
1818 os << ", which is not memory allocated by ";
1819 else
1820 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001821
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001822 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001823
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001824 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001825 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001826 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001827 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001828 }
1829}
1830
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001831void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001832 SourceRange Range) const {
1833
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001834 Optional<MallocChecker::CheckKind> CheckKind;
1835
1836 if (ChecksEnabled[CK_MallocChecker])
1837 CheckKind = CK_MallocChecker;
1838 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1839 CheckKind = CK_MismatchedDeallocatorChecker;
1840 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001841 return;
1842
Devin Coughline39bd402015-09-16 22:03:05 +00001843 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001844 if (!BT_FreeAlloca[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001845 BT_FreeAlloca[*CheckKind].reset(new BugType(
1846 CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001847
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001848 auto R = llvm::make_unique<BugReport>(
1849 *BT_FreeAlloca[*CheckKind],
1850 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001851 R->markInteresting(ArgVal.getAsRegion());
1852 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001853 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001854 }
1855}
1856
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001857void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001858 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001859 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001860 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001861 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001862 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001863
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001864 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001865 return;
1866
Devin Coughline39bd402015-09-16 22:03:05 +00001867 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001868 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001869 BT_MismatchedDealloc.reset(
1870 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001871 "Bad deallocator", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001872
Anton Yartsev05789592013-03-28 17:05:19 +00001873 SmallString<100> buf;
1874 llvm::raw_svector_ostream os(buf);
1875
1876 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1877 SmallString<20> AllocBuf;
1878 llvm::raw_svector_ostream AllocOs(AllocBuf);
1879 SmallString<20> DeallocBuf;
1880 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1881
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001882 if (OwnershipTransferred) {
1883 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1884 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001885 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001886 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001887
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001888 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001889
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001890 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1891 os << " allocated by " << AllocOs.str();
1892 } else {
1893 os << "Memory";
1894 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1895 os << " allocated by " << AllocOs.str();
1896
1897 os << " should be deallocated by ";
1898 printExpectedDeallocName(os, RS->getAllocationFamily());
1899
1900 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1901 os << ", not " << DeallocOs.str();
1902 }
Anton Yartsev05789592013-03-28 17:05:19 +00001903
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001904 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001905 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001906 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001907 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001908 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001909 }
1910}
1911
Anna Zaksc89ad072013-02-07 23:05:47 +00001912void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001913 SourceRange Range, const Expr *DeallocExpr,
1914 const Expr *AllocExpr) const {
1915
Anton Yartsev05789592013-03-28 17:05:19 +00001916
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001917 if (!ChecksEnabled[CK_MallocChecker] &&
1918 !ChecksEnabled[CK_NewDeleteChecker])
1919 return;
1920
1921 Optional<MallocChecker::CheckKind> CheckKind =
1922 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001923 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001924 return;
1925
Devin Coughline39bd402015-09-16 22:03:05 +00001926 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001927 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001928 return;
1929
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001930 if (!BT_OffsetFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001931 BT_OffsetFree[*CheckKind].reset(new BugType(
1932 CheckNames[*CheckKind], "Offset free", categories::MemoryError));
Anna Zaksc89ad072013-02-07 23:05:47 +00001933
1934 SmallString<100> buf;
1935 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001936 SmallString<20> AllocNameBuf;
1937 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001938
1939 const MemRegion *MR = ArgVal.getAsRegion();
1940 assert(MR && "Only MemRegion based symbols can have offset free errors");
1941
1942 RegionOffset Offset = MR->getAsOffset();
1943 assert((Offset.isValid() &&
1944 !Offset.hasSymbolicOffset() &&
1945 Offset.getOffset() != 0) &&
1946 "Only symbols with a valid offset can have offset free errors");
1947
1948 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1949
Anton Yartsev05789592013-03-28 17:05:19 +00001950 os << "Argument to ";
1951 if (!printAllocDeallocName(os, C, DeallocExpr))
1952 os << "deallocator";
1953 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001954 << offsetBytes
1955 << " "
1956 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001957 << " from the start of ";
1958 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1959 os << "memory allocated by " << AllocNameOs.str();
1960 else
1961 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001962
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001963 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001964 R->markInteresting(MR->getBaseRegion());
1965 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001966 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001967}
1968
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001969void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1970 SymbolRef Sym) const {
1971
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001972 if (!ChecksEnabled[CK_MallocChecker] &&
1973 !ChecksEnabled[CK_NewDeleteChecker])
1974 return;
1975
1976 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001977 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001978 return;
1979
Devin Coughline39bd402015-09-16 22:03:05 +00001980 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001981 if (!BT_UseFree[*CheckKind])
1982 BT_UseFree[*CheckKind].reset(new BugType(
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001983 CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001984
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001985 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1986 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001987
1988 R->markInteresting(Sym);
1989 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001990 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001991 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001992 }
1993}
1994
1995void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001996 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001997 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001998
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001999 if (!ChecksEnabled[CK_MallocChecker] &&
2000 !ChecksEnabled[CK_NewDeleteChecker])
2001 return;
2002
2003 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002004 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00002005 return;
2006
Devin Coughline39bd402015-09-16 22:03:05 +00002007 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002008 if (!BT_DoubleFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002009 BT_DoubleFree[*CheckKind].reset(new BugType(
2010 CheckNames[*CheckKind], "Double free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002011
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002012 auto R = llvm::make_unique<BugReport>(
2013 *BT_DoubleFree[*CheckKind],
2014 (Released ? "Attempt to free released memory"
2015 : "Attempt to free non-owned memory"),
2016 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002017 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00002018 R->markInteresting(Sym);
2019 if (PrevSym)
2020 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00002021 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002022 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002023 }
2024}
2025
Jordan Rose656fdd52014-01-08 18:46:55 +00002026void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2027
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002028 if (!ChecksEnabled[CK_NewDeleteChecker])
2029 return;
2030
2031 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002032 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00002033 return;
2034
Devin Coughline39bd402015-09-16 22:03:05 +00002035 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00002036 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002037 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002038 "Double delete",
2039 categories::MemoryError));
Jordan Rose656fdd52014-01-08 18:46:55 +00002040
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002041 auto R = llvm::make_unique<BugReport>(
2042 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00002043
2044 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002045 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002046 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00002047 }
2048}
2049
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002050void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2051 SourceRange Range,
2052 SymbolRef Sym) const {
2053
2054 if (!ChecksEnabled[CK_MallocChecker] &&
2055 !ChecksEnabled[CK_NewDeleteChecker])
2056 return;
2057
2058 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2059
2060 if (!CheckKind.hasValue())
2061 return;
2062
Devin Coughline39bd402015-09-16 22:03:05 +00002063 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002064 if (!BT_UseZerroAllocated[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002065 BT_UseZerroAllocated[*CheckKind].reset(
2066 new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2067 categories::MemoryError));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002068
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002069 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2070 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002071
2072 R->addRange(Range);
2073 if (Sym) {
2074 R->markInteresting(Sym);
2075 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2076 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002077 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002078 }
2079}
2080
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002081void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2082 SourceRange Range,
2083 const Expr *FreeExpr) const {
2084 if (!ChecksEnabled[CK_MallocChecker])
2085 return;
2086
2087 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2088 if (!CheckKind.hasValue())
2089 return;
2090
2091 if (ExplodedNode *N = C.generateErrorNode()) {
2092 if (!BT_BadFree[*CheckKind])
Artem Dergachev9849f592018-02-08 23:28:29 +00002093 BT_BadFree[*CheckKind].reset(new BugType(
2094 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002095
2096 SmallString<100> Buf;
2097 llvm::raw_svector_ostream Os(Buf);
2098
2099 const MemRegion *MR = ArgVal.getAsRegion();
2100 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2101 MR = ER->getSuperRegion();
2102
2103 Os << "Argument to ";
2104 if (!printAllocDeallocName(Os, C, FreeExpr))
2105 Os << "deallocator";
2106
2107 Os << " is a function pointer";
2108
2109 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2110 R->markInteresting(MR);
2111 R->addRange(Range);
2112 C.emitReport(std::move(R));
2113 }
2114}
2115
Leslie Zhaie3986c52017-04-26 05:33:14 +00002116ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2117 const CallExpr *CE,
2118 bool FreesOnFail,
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002119 ProgramStateRef State,
Leslie Zhaie3986c52017-04-26 05:33:14 +00002120 bool SuffixWithN) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002121 if (!State)
2122 return nullptr;
2123
Leslie Zhaie3986c52017-04-26 05:33:14 +00002124 if (SuffixWithN && CE->getNumArgs() < 3)
2125 return nullptr;
2126 else if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002127 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002128
Ted Kremenek90af9092010-12-02 07:49:45 +00002129 const Expr *arg0Expr = CE->getArg(0);
George Karpenkovd703ec92018-01-17 20:27:29 +00002130 SVal Arg0Val = C.getSVal(arg0Expr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00002131 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002132 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00002133 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002134
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002135 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002136
Ted Kremenek90af9092010-12-02 07:49:45 +00002137 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002138 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002139
Leslie Zhaie3986c52017-04-26 05:33:14 +00002140 // Get the size argument.
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002141 const Expr *Arg1 = CE->getArg(1);
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002142
2143 // Get the value of the size argument.
George Karpenkovd703ec92018-01-17 20:27:29 +00002144 SVal TotalSize = C.getSVal(Arg1);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002145 if (SuffixWithN)
2146 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2147 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002148 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002149
2150 // Compare the size argument to 0.
2151 DefinedOrUnknownSVal SizeZero =
Leslie Zhaie3986c52017-04-26 05:33:14 +00002152 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002153 svalBuilder.makeIntValWithPtrWidth(0, false));
2154
Anna Zaksd56c8792012-02-13 18:05:39 +00002155 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002156 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00002157 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002158 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00002159 // We only assume exceptional states if they are definitely true; if the
2160 // state is under-constrained, assume regular realloc behavior.
2161 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2162 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2163
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002164 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002165 // malloc(size).
Leslie Zhaie3986c52017-04-26 05:33:14 +00002166 if (PrtIsNull && !SizeIsZero) {
2167 ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002168 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002169 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002170 }
2171
Anna Zaksd56c8792012-02-13 18:05:39 +00002172 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00002173 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002174
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002175 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00002176 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002177 SymbolRef FromPtr = arg0Val.getAsSymbol();
George Karpenkovd703ec92018-01-17 20:27:29 +00002178 SVal RetVal = C.getSVal(CE);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002179 SymbolRef ToPtr = RetVal.getAsSymbol();
2180 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00002181 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00002182
Anna Zaksfe6eb672012-08-24 02:28:20 +00002183 bool ReleasedAllocated = false;
2184
Anna Zaksd56c8792012-02-13 18:05:39 +00002185 // If the size is 0, free the memory.
2186 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00002187 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2188 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00002189 // The semantics of the return value are:
2190 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00002191 // to free() is returned. We just free the input pointer and do not add
2192 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00002193 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00002194 }
2195
2196 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00002197 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002198 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00002199
Leslie Zhaie3986c52017-04-26 05:33:14 +00002200 ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002201 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002202 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00002203 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00002204
Anna Zaks75cfbb62012-09-12 22:57:34 +00002205 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2206 if (FreesOnFail)
2207 Kind = RPIsFreeOnFailure;
2208 else if (!ReleasedAllocated)
2209 Kind = RPDoNotTrackAfterFailure;
2210
Anna Zaksfe6eb672012-08-24 02:28:20 +00002211 // Record the info about the reallocated symbol so that we could properly
2212 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00002213 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00002214 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00002215 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00002216 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002217 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002218 }
Craig Topper0dbb7832014-05-27 02:45:47 +00002219 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00002220}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002221
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002222ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002223 ProgramStateRef State) {
2224 if (!State)
2225 return nullptr;
2226
Anna Zaksb508d292012-04-10 23:41:11 +00002227 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002228 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002229
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002230 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek90af9092010-12-02 07:49:45 +00002231 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002232 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002233
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002234 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002235}
2236
Anna Zaksfc2e1532012-03-21 19:45:08 +00002237LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002238MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2239 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002240 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002241 // Walk the ExplodedGraph backwards and find the first node that referred to
2242 // the tracked symbol.
2243 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002244 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002245
2246 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002247 ProgramStateRef State = N->getState();
2248 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002249 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002250
2251 // Find the most recent expression bound to the symbol in the current
2252 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002253 if (!ReferenceRegion) {
2254 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2255 SVal Val = State->getSVal(MR);
2256 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002257 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002258 // Do not show local variables belonging to a function other than
2259 // where the error is reported.
2260 if (!VR ||
2261 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2262 ReferenceRegion = MR;
2263 }
2264 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002265 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002266
Anna Zaks486a0ff2015-02-05 01:02:53 +00002267 // Allocation node, is the last node in the current or parent context in
2268 // which the symbol was tracked.
2269 const LocationContext *NContext = N->getLocationContext();
2270 if (NContext == LeakContext ||
2271 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002272 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002273 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002274 }
2275
Anna Zaksa043d0c2013-01-08 00:25:29 +00002276 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002277}
2278
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002279void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2280 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002281
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002282 if (!ChecksEnabled[CK_MallocChecker] &&
2283 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002284 return;
2285
Anton Yartsev9907fc92015-03-04 23:18:21 +00002286 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002287 assert(RS && "cannot leak an untracked symbol");
2288 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002289
2290 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002291 return;
2292
Anton Yartsev2487dd62015-03-10 22:24:21 +00002293 Optional<MallocChecker::CheckKind>
2294 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002295
Anton Yartsev2487dd62015-03-10 22:24:21 +00002296 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002297 return;
2298
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002299 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002300 if (!BT_Leak[*CheckKind]) {
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002301 BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2302 categories::MemoryError));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002303 // Leaks should not be reported if they are post-dominated by a sink:
2304 // (1) Sinks are higher importance bugs.
2305 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2306 // with __noreturn functions such as assert() or exit(). We choose not
2307 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002308 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002309 }
2310
Anna Zaksdf901a42012-02-23 21:38:21 +00002311 // Most bug reports are cached at the location where they occurred.
2312 // With leaks, we want to unique them by the location where they were
2313 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002314 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002315 const ExplodedNode *AllocNode = nullptr;
2316 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002317 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002318
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002319 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
Anton Yartsev6e499252013-04-05 02:25:02 +00002320 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002321 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2322 C.getSourceManager(),
2323 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002324
Anna Zaksfc2e1532012-03-21 19:45:08 +00002325 SmallString<200> buf;
2326 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002327 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002328 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002329 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002330 } else {
2331 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002332 }
2333
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002334 auto R = llvm::make_unique<BugReport>(
2335 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2336 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002337 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002338 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002339 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002340}
2341
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002342void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2343 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002344{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002345 if (!SymReaper.hasDeadSymbols())
2346 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002347
Ted Kremenek49b1e382012-01-26 21:29:00 +00002348 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002349 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002350 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002351
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002352 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002353 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2354 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002355 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002356 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002357 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002358 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002359
Zhongxing Xuc7460962009-11-13 07:48:11 +00002360 }
2361 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002362
Anna Zaksd56c8792012-02-13 18:05:39 +00002363 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002364 ReallocPairsTy RP = state->get<ReallocPairs>();
2365 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002366 if (SymReaper.isDead(I->first) ||
2367 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002368 state = state->remove<ReallocPairs>(I->first);
2369 }
2370 }
2371
Anna Zaks67291b92012-11-13 03:18:01 +00002372 // Cleanup the FreeReturnValue Map.
2373 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2374 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2375 if (SymReaper.isDead(I->first) ||
2376 SymReaper.isDead(I->second)) {
2377 state = state->remove<FreeReturnValue>(I->first);
2378 }
2379 }
2380
Anna Zaksdf901a42012-02-23 21:38:21 +00002381 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002382 ExplodedNode *N = C.getPredecessor();
2383 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002384 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002385 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2386 if (N) {
2387 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002388 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002389 reportLeak(*I, N, C);
2390 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002391 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002392 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002393
Anna Zaksdf901a42012-02-23 21:38:21 +00002394 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002395}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002396
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002397void MallocChecker::checkPreCall(const CallEvent &Call,
2398 CheckerContext &C) const {
2399
Jordan Rose656fdd52014-01-08 18:46:55 +00002400 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2401 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2402 if (!Sym || checkDoubleDelete(Sym, C))
2403 return;
2404 }
2405
Anna Zaks46d01602012-05-18 01:16:10 +00002406 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002407 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2408 const FunctionDecl *FD = FC->getDecl();
2409 if (!FD)
2410 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002411
Anna Zaksd79b8402014-10-03 21:48:59 +00002412 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002413 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002414 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2415 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2416 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002417 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002418
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002419 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002420 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002421 return;
2422 }
2423
2424 // Check if the callee of a method is deleted.
2425 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2426 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2427 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2428 return;
2429 }
2430
2431 // Check arguments for being used after free.
2432 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2433 SVal ArgSVal = Call.getArgSVal(I);
2434 if (ArgSVal.getAs<Loc>()) {
2435 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002436 if (!Sym)
2437 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002438 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002439 return;
2440 }
2441 }
2442}
2443
Anna Zaksa1b227b2012-02-08 23:16:56 +00002444void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2445 const Expr *E = S->getRetValue();
2446 if (!E)
2447 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002448
2449 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002450 ProgramStateRef State = C.getState();
George Karpenkovd703ec92018-01-17 20:27:29 +00002451 SVal RetVal = C.getSVal(E);
Anna Zaks4ca45b12012-02-22 02:36:01 +00002452 SymbolRef Sym = RetVal.getAsSymbol();
2453 if (!Sym)
2454 // If we are returning a field of the allocated struct or an array element,
2455 // the callee could still free the memory.
2456 // TODO: This logic should be a part of generic symbol escape callback.
2457 if (const MemRegion *MR = RetVal.getAsRegion())
2458 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2459 if (const SymbolicRegion *BMR =
2460 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2461 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002462
Anna Zaks3aa52252012-02-11 21:44:39 +00002463 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002464 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002465 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002466}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002467
Anna Zaks9fe80982012-03-22 00:57:20 +00002468// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002469// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002470// needed.
2471void MallocChecker::checkPostStmt(const BlockExpr *BE,
2472 CheckerContext &C) const {
2473
2474 // Scan the BlockDecRefExprs for any object the retain count checker
2475 // may be tracking.
2476 if (!BE->getBlockDecl()->hasCaptures())
2477 return;
2478
2479 ProgramStateRef state = C.getState();
2480 const BlockDataRegion *R =
George Karpenkovd703ec92018-01-17 20:27:29 +00002481 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
Anna Zaks9fe80982012-03-22 00:57:20 +00002482
2483 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2484 E = R->referenced_vars_end();
2485
2486 if (I == E)
2487 return;
2488
2489 SmallVector<const MemRegion*, 10> Regions;
2490 const LocationContext *LC = C.getLocationContext();
2491 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2492
2493 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002494 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002495 if (VR->getSuperRegion() == R) {
2496 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2497 }
2498 Regions.push_back(VR);
2499 }
2500
2501 state =
2502 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2503 Regions.data() + Regions.size()).getState();
2504 C.addTransition(state);
2505}
2506
Anna Zaks46d01602012-05-18 01:16:10 +00002507bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002508 assert(Sym);
2509 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002510 return (RS && RS->isReleased());
2511}
2512
2513bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2514 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002515
Jordan Rose656fdd52014-01-08 18:46:55 +00002516 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002517 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2518 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002519 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002520
Anna Zaksa1b227b2012-02-08 23:16:56 +00002521 return false;
2522}
2523
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002524void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2525 const Stmt *S) const {
2526 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002527
Devin Coughlin81771732015-09-22 22:47:14 +00002528 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2529 if (RS->isAllocatedOfSizeZero())
2530 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2531 }
2532 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2533 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2534 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002535}
2536
Jordan Rose656fdd52014-01-08 18:46:55 +00002537bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2538
2539 if (isReleased(Sym, C)) {
2540 ReportDoubleDelete(C, Sym);
2541 return true;
2542 }
2543 return false;
2544}
2545
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002546// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002547void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2548 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002549 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002550 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002551 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002552 checkUseZeroAllocated(Sym, C, S);
2553 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002554}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002555
Anna Zaksbb1ef902012-02-11 21:02:35 +00002556// If a symbolic region is assumed to NULL (or another constant), stop tracking
2557// it - assuming that allocation failed on this path.
2558ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2559 SVal Cond,
2560 bool Assumption) const {
2561 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002562 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002563 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002564 ConstraintManager &CMgr = state->getConstraintManager();
2565 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2566 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002567 state = state->remove<RegionState>(I.getKey());
2568 }
2569
Anna Zaksd56c8792012-02-13 18:05:39 +00002570 // Realloc returns 0 when reallocation fails, which means that we should
2571 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002572 ReallocPairsTy RP = state->get<ReallocPairs>();
2573 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002574 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002575 ConstraintManager &CMgr = state->getConstraintManager();
2576 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002577 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002578 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002579
Anna Zaks75cfbb62012-09-12 22:57:34 +00002580 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2581 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2582 if (RS->isReleased()) {
2583 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002584 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002585 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002586 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2587 state = state->remove<RegionState>(ReallocSym);
2588 else
2589 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002590 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002591 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002592 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002593 }
2594
Anna Zaksbb1ef902012-02-11 21:02:35 +00002595 return state;
2596}
2597
Anna Zaks8ebeb642013-06-08 00:29:29 +00002598bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002599 const CallEvent *Call,
2600 ProgramStateRef State,
2601 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002602 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002603 EscapingSymbol = nullptr;
2604
Jordan Rose2a833ca2014-01-15 17:25:15 +00002605 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002606 // TODO: If we want to be more optimistic here, we'll need to make sure that
2607 // regions escape to C++ containers. They seem to do that even now, but for
2608 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002609 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002610 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002611
Jordan Rose742920c2012-07-02 19:27:35 +00002612 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002613 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002614 // If it's not a framework call, or if it takes a callback, assume it
2615 // can free memory.
Anna Zaksfe1eca52015-10-27 20:19:45 +00002616 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002617 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002618
Jordan Rose613f3c02013-03-09 00:59:10 +00002619 // If it's a method we know about, handle it explicitly post-call.
2620 // This should happen before the "freeWhenDone" check below.
2621 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002622 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002623
Jordan Rose613f3c02013-03-09 00:59:10 +00002624 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2625 // about, we can't be sure that the object will use free() to deallocate the
2626 // memory, so we can't model it explicitly. The best we can do is use it to
2627 // decide whether the pointer escapes.
2628 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002629 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002630
Jordan Rose613f3c02013-03-09 00:59:10 +00002631 // If the first selector piece ends with "NoCopy", and there is no
2632 // "freeWhenDone" parameter set to zero, we know ownership is being
2633 // transferred. Again, though, we can't be sure that the object will use
2634 // free() to deallocate the memory, so we can't model it explicitly.
2635 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002636 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002637 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002638
Anna Zaks42908c72012-06-19 05:10:32 +00002639 // If the first selector starts with addPointer, insertPointer,
2640 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2641 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002642 // that the pointers get freed by following the container itself.
2643 if (FirstSlot.startswith("addPointer") ||
2644 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002645 FirstSlot.startswith("replacePointer") ||
2646 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002647 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002648 }
2649
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002650 // We should escape receiver on call to 'init'. This is especially relevant
2651 // to the receiver, as the corresponding symbol is usually not referenced
2652 // after the call.
2653 if (Msg->getMethodFamily() == OMF_init) {
2654 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2655 return true;
2656 }
Anna Zaks737926b2013-05-31 22:39:13 +00002657
Jordan Rose742920c2012-07-02 19:27:35 +00002658 // Otherwise, assume that the method does not free memory.
2659 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002660 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002661 }
2662
Jordan Rose742920c2012-07-02 19:27:35 +00002663 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002664 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002665 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002666 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002667
Jordan Rose742920c2012-07-02 19:27:35 +00002668 ASTContext &ASTC = State->getStateManager().getContext();
2669
2670 // If it's one of the allocation functions we can reason about, we model
2671 // its behavior explicitly.
2672 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002673 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002674
2675 // If it's not a system call, assume it frees memory.
2676 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002677 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002678
2679 // White list the system functions whose arguments escape.
2680 const IdentifierInfo *II = FD->getIdentifier();
2681 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002682 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002683 StringRef FName = II->getName();
2684
Jordan Rose742920c2012-07-02 19:27:35 +00002685 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002686 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002687 if (FName.endswith("NoCopy")) {
2688 // Look for the deallocator argument. We know that the memory ownership
2689 // is not transferred only if the deallocator argument is
2690 // 'kCFAllocatorNull'.
2691 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2692 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2693 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2694 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2695 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002696 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002697 }
2698 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002699 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002700 }
2701
Jordan Rose742920c2012-07-02 19:27:35 +00002702 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002703 // 'closefn' is specified (and if that function does free memory),
2704 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002705 // Currently, we do not inspect the 'closefn' function (PR12101).
2706 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002707 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002708 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002709
2710 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2711 // these leaks might be intentional when setting the buffer for stdio.
2712 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2713 if (FName == "setbuf" || FName =="setbuffer" ||
2714 FName == "setlinebuf" || FName == "setvbuf") {
2715 if (Call->getNumArgs() >= 1) {
2716 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2717 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2718 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2719 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002720 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002721 }
2722 }
2723
2724 // A bunch of other functions which either take ownership of a pointer or
2725 // wrap the result up in a struct or object, meaning it can be freed later.
2726 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2727 // but the Malloc checker cannot differentiate between them. The right way
2728 // of doing this would be to implement a pointer escapes callback.
2729 if (FName == "CGBitmapContextCreate" ||
2730 FName == "CGBitmapContextCreateWithData" ||
2731 FName == "CVPixelBufferCreateWithBytes" ||
2732 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2733 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002734 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002735 }
2736
Anna Zaks03f48332016-01-06 00:32:56 +00002737 if (FName == "postEvent" &&
2738 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2739 return true;
2740 }
2741
2742 if (FName == "postEvent" &&
2743 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2744 return true;
2745 }
2746
Artem Dergachev85c92112016-12-16 12:21:55 +00002747 if (FName == "connectImpl" &&
2748 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2749 return true;
2750 }
2751
Jordan Rose7ab01822012-07-02 19:27:51 +00002752 // Handle cases where we know a buffer's /address/ can escape.
2753 // Note that the above checks handle some special cases where we know that
2754 // even though the address escapes, it's still our responsibility to free the
2755 // buffer.
2756 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002757 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002758
2759 // Otherwise, assume that the function does not free memory.
2760 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002761 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002762}
2763
Anna Zaks333481b2013-03-28 23:15:29 +00002764static bool retTrue(const RefState *RS) {
2765 return true;
2766}
2767
2768static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2769 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2770 RS->getAllocationFamily() == AF_CXXNew);
2771}
2772
Anna Zaksdc154152012-12-20 00:38:25 +00002773ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2774 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002775 const CallEvent *Call,
2776 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002777 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2778}
2779
2780ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2781 const InvalidatedSymbols &Escaped,
2782 const CallEvent *Call,
2783 PointerEscapeKind Kind) const {
2784 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2785 &checkIfNewOrNewArrayFamily);
2786}
2787
2788ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2789 const InvalidatedSymbols &Escaped,
2790 const CallEvent *Call,
2791 PointerEscapeKind Kind,
2792 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002793 // If we know that the call does not free memory, or we want to process the
2794 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002795 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002796 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002797 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2798 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002799 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002800 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002801 }
Anna Zaks3d348342012-02-14 21:55:24 +00002802
Anna Zaksdc154152012-12-20 00:38:25 +00002803 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002804 E = Escaped.end();
2805 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002806 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002807
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002808 if (EscapingSymbol && EscapingSymbol != sym)
2809 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002810
Anna Zaks0d6989b2012-06-22 02:04:31 +00002811 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002812 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2813 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002814 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002815 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2816 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002817 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002818 }
Anna Zaks3d348342012-02-14 21:55:24 +00002819 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002820}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002821
Jordy Rosebf38f202012-03-18 07:43:35 +00002822static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2823 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002824 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2825 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002826
Jordan Rose0c153cb2012-11-02 01:54:06 +00002827 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002828 I != E; ++I) {
2829 SymbolRef sym = I.getKey();
2830 if (!currMap.lookup(sym))
2831 return sym;
2832 }
2833
Craig Topper0dbb7832014-05-27 02:45:47 +00002834 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002835}
2836
Artem Dergachevff1fc212018-03-21 00:49:47 +00002837static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) {
2838 if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
2839 StringRef N = II->getName();
2840 if (N.contains_lower("ptr") || N.contains_lower("pointer")) {
2841 if (N.contains_lower("ref") || N.contains_lower("cnt") ||
2842 N.contains_lower("intrusive") || N.contains_lower("shared")) {
2843 return true;
2844 }
2845 }
2846 }
2847 return false;
2848}
2849
David Blaikie0a0c2752017-01-05 17:26:53 +00002850std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2851 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2852 BugReport &BR) {
Artem Dergachev5337efc2018-02-27 21:19:33 +00002853 const Stmt *S = PathDiagnosticLocation::getStmt(N);
2854 if (!S)
2855 return nullptr;
2856
2857 const LocationContext *CurrentLC = N->getLocationContext();
2858
2859 // If we find an atomic fetch_add or fetch_sub within the destructor in which
2860 // the pointer was released (before the release), this is likely a destructor
2861 // of a shared pointer.
2862 // Because we don't model atomics, and also because we don't know that the
2863 // original reference count is positive, we should not report use-after-frees
2864 // on objects deleted in such destructors. This can probably be improved
2865 // through better shared pointer modeling.
2866 if (ReleaseDestructorLC) {
2867 if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
2868 AtomicExpr::AtomicOp Op = AE->getOp();
2869 if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
2870 Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
2871 if (ReleaseDestructorLC == CurrentLC ||
2872 ReleaseDestructorLC->isParentOf(CurrentLC)) {
2873 BR.markInvalid(getTag(), S);
2874 }
2875 }
2876 }
2877 }
2878
Jordy Rosebf38f202012-03-18 07:43:35 +00002879 ProgramStateRef state = N->getState();
2880 ProgramStateRef statePrev = PrevN->getState();
2881
2882 const RefState *RS = state->get<RegionState>(Sym);
2883 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002884 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002885 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002886
Jordan Rose681cce92012-07-10 22:07:42 +00002887 // FIXME: We will eventually need to handle non-statement-based events
2888 // (__attribute__((cleanup))).
2889
Anna Zaks2b5bb972012-02-09 06:25:51 +00002890 // Find out if this is an interesting point and what is the kind.
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002891 const char *Msg = nullptr;
2892 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002893 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002894 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002895 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002896 StackHint = new StackHintGeneratorForSymbol(Sym,
2897 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002898 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002899 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002900 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002901 "Returning; memory was released");
Artem Dergachev5337efc2018-02-27 21:19:33 +00002902
Artem Dergachevff1fc212018-03-21 00:49:47 +00002903 // See if we're releasing memory while inlining a destructor
2904 // (or one of its callees). This turns on various common
2905 // false positive suppressions.
2906 bool FoundAnyDestructor = false;
Artem Dergachev5337efc2018-02-27 21:19:33 +00002907 for (const LocationContext *LC = CurrentLC; LC; LC = LC->getParent()) {
Artem Dergachevff1fc212018-03-21 00:49:47 +00002908 if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
2909 if (isReferenceCountingPointerDestructor(DD)) {
2910 // This immediately looks like a reference-counting destructor.
2911 // We're bad at guessing the original reference count of the object,
2912 // so suppress the report for now.
2913 BR.markInvalid(getTag(), DD);
2914 } else if (!FoundAnyDestructor) {
2915 assert(!ReleaseDestructorLC &&
2916 "There can be only one release point!");
2917 // Suspect that it's a reference counting pointer destructor.
2918 // On one of the next nodes might find out that it has atomic
2919 // reference counting operations within it (see the code above),
2920 // and if so, we'd conclude that it likely is a reference counting
2921 // pointer destructor.
2922 ReleaseDestructorLC = LC->getCurrentStackFrame();
2923 // It is unlikely that releasing memory is delegated to a destructor
2924 // inside a destructor of a shared pointer, because it's fairly hard
2925 // to pass the information that the pointer indeed needs to be
2926 // released into it. So we're only interested in the innermost
2927 // destructor.
2928 FoundAnyDestructor = true;
2929 }
Artem Dergachev5337efc2018-02-27 21:19:33 +00002930 }
2931 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002932 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002933 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002934 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002935 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002936 Mode = ReallocationFailed;
2937 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002938 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002939 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002940
Jordy Rose21ff76e2012-03-24 03:15:09 +00002941 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2942 // Is it possible to fail two reallocs WITHOUT testing in between?
2943 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2944 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002945 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002946 FailedReallocSymbol = sym;
2947 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002948 }
2949
2950 // We are in a special mode if a reallocation failed later in the path.
2951 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002952 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002953
Jordy Rose21ff76e2012-03-24 03:15:09 +00002954 // Is this is the first appearance of the reallocated symbol?
2955 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002956 // We're at the reallocation point.
2957 Msg = "Attempt to reallocate memory";
2958 StackHint = new StackHintGeneratorForSymbol(Sym,
2959 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002960 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002961 Mode = Normal;
2962 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002963 }
2964
Anna Zaks2b5bb972012-02-09 06:25:51 +00002965 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002966 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002967 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002968
2969 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002970 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002971 N->getLocationContext());
David Blaikie0a0c2752017-01-05 17:26:53 +00002972 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002973}
2974
Anna Zaks263b7e02012-05-02 00:05:20 +00002975void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2976 const char *NL, const char *Sep) const {
2977
2978 RegionStateTy RS = State->get<RegionState>();
2979
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002980 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002981 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002982 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002983 const RefState *RefS = State->get<RegionState>(I.getKey());
2984 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002985 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002986 if (!CheckKind.hasValue())
2987 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002988
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002989 I.getKey()->dumpToStream(Out);
2990 Out << " : ";
2991 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002992 if (CheckKind.hasValue())
2993 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002994 Out << NL;
2995 }
2996 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002997}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002998
Reka Kovacs18775fc2018-06-09 13:03:49 +00002999namespace clang {
3000namespace ento {
3001namespace allocation_state {
3002
3003ProgramStateRef
3004markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
3005 AllocationFamily Family = AF_InternalBuffer;
3006 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3007}
3008
3009} // end namespace allocation_state
3010} // end namespace ento
3011} // end namespace clang
3012
Anna Zakse4cfcd42013-04-16 00:22:55 +00003013void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
3014 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003015 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00003016 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
3017 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003018 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
3019 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
3020 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003021 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00003022 // checker.
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00003023 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003024 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00003025 // FIXME: This does not set the correct name, but without this workaround
3026 // no name will be set at all.
3027 checker->CheckNames[MallocChecker::CK_NewDeleteChecker] =
3028 mgr.getCurrentCheckName();
3029 }
Anna Zakse4cfcd42013-04-16 00:22:55 +00003030}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00003031
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003032#define REGISTER_CHECKER(name) \
3033 void ento::register##name(CheckerManager &mgr) { \
3034 registerCStringCheckerBasic(mgr); \
3035 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00003036 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
3037 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003038 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
3039 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
3040 }
Anna Zakscd37bf42012-02-08 23:16:52 +00003041
Gabor Horvathe40c71c2015-03-04 17:59:34 +00003042REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00003043REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00003044REGISTER_CHECKER(MismatchedDeallocatorChecker)