blob: 2ab817a1ccb29eb52a24224b672fd6a57e8e10db [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.
David Blaikie6951e3e2015-08-13 22:58:37 +0000434 class MallocBugVisitor final
435 : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000436 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000437 enum NotificationMode {
438 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000439 ReallocationFailed
440 };
441
Anna Zaks2b5bb972012-02-09 06:25:51 +0000442 // The allocated region symbol tracked by the main analysis.
443 SymbolRef Sym;
444
Anna Zaks62cce9e2012-05-10 01:37:40 +0000445 // The mode we are in, i.e. what kind of diagnostics will be emitted.
446 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000447
Anna Zaks62cce9e2012-05-10 01:37:40 +0000448 // A symbol from when the primary region should have been reallocated.
449 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000450
Artem Dergachev5337efc2018-02-27 21:19:33 +0000451 // A C++ destructor stack frame in which memory was released. Used for
452 // miscellaneous false positive suppression.
453 const StackFrameContext *ReleaseDestructorLC;
454
Anna Zaks62cce9e2012-05-10 01:37:40 +0000455 bool IsLeak;
456
457 public:
458 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Artem Dergachev5337efc2018-02-27 21:19:33 +0000459 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr),
460 ReleaseDestructorLC(nullptr), IsLeak(isLeak) {}
461
462 static void *getTag() {
463 static int Tag = 0;
464 return &Tag;
465 }
Jordy Rose21ff76e2012-03-24 03:15:09 +0000466
Craig Topperfb6b25b2014-03-15 04:29:04 +0000467 void Profile(llvm::FoldingSetNodeID &ID) const override {
Artem Dergachev5337efc2018-02-27 21:19:33 +0000468 ID.AddPointer(getTag());
Anna Zaks2b5bb972012-02-09 06:25:51 +0000469 ID.AddPointer(Sym);
470 }
471
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000472 inline bool isAllocated(const RefState *S, const RefState *SPrev,
473 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000474 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000475 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000476 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
477 (!SPrev || !(SPrev->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000478 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000479 }
480
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000481 inline bool isReleased(const RefState *S, const RefState *SPrev,
482 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000483 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000484 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000485 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
486 }
487
Anna Zaks0d6989b2012-06-22 02:04:31 +0000488 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
489 const Stmt *Stmt) {
490 // Did not track -> relinquished. Other state (allocated) -> relinquished.
491 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
492 isa<ObjCPropertyRefExpr>(Stmt)) &&
493 (S && S->isRelinquished()) &&
494 (!SPrev || !SPrev->isRelinquished()));
495 }
496
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000497 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
498 const Stmt *Stmt) {
499 // If the expression is not a call, and the state change is
500 // released -> allocated, it must be the realloc return value
501 // check. If we have to handle more cases here, it might be cleaner just
502 // to track this extra bit in the state itself.
503 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000504 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
505 (SPrev && !(SPrev->isAllocated() ||
506 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000507 }
508
David Blaikie0a0c2752017-01-05 17:26:53 +0000509 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
510 const ExplodedNode *PrevN,
511 BugReporterContext &BRC,
512 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000513
David Blaikied15481c2014-08-29 18:18:43 +0000514 std::unique_ptr<PathDiagnosticPiece>
515 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
516 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000517 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000518 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000519
520 PathDiagnosticLocation L =
521 PathDiagnosticLocation::createEndOfPath(EndPathNode,
522 BRC.getSourceManager());
523 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000524 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
525 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000526 }
527
Anna Zakscba4f292012-03-16 23:24:20 +0000528 private:
529 class StackHintGeneratorForReallocationFailed
530 : public StackHintGeneratorForSymbol {
531 public:
532 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
533 : StackHintGeneratorForSymbol(S, M) {}
534
Craig Topperfb6b25b2014-03-15 04:29:04 +0000535 std::string getMessageForArg(const Expr *ArgE,
536 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000537 // Printed parameters start at 1, not 0.
538 ++ArgIndex;
539
Anna Zakscba4f292012-03-16 23:24:20 +0000540 SmallString<200> buf;
541 llvm::raw_svector_ostream os(buf);
542
Jordan Rosec102b352012-09-22 01:24:42 +0000543 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
544 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000545
546 return os.str();
547 }
548
Craig Topperfb6b25b2014-03-15 04:29:04 +0000549 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000550 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000551 }
552 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000553 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000554};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000555} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000556
Jordan Rose0c153cb2012-11-02 01:54:06 +0000557REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
558REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Devin Coughlin81771732015-09-22 22:47:14 +0000559REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000560
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000561// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000562// the free function.
563REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
564
Anna Zaksbb1ef902012-02-11 21:02:35 +0000565namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000566class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000567 ProgramStateRef state;
568public:
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000569 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
Anna Zaksbb1ef902012-02-11 21:02:35 +0000570 ProgramStateRef getState() const { return state; }
571
Craig Topperfb6b25b2014-03-15 04:29:04 +0000572 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000573 state = state->remove<RegionState>(sym);
574 return true;
575 }
576};
577} // end anonymous namespace
578
Anna Zaks3d348342012-02-14 21:55:24 +0000579void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000580 if (II_malloc)
581 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000582 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000583 II_malloc = &Ctx.Idents.get("malloc");
584 II_free = &Ctx.Idents.get("free");
585 II_realloc = &Ctx.Idents.get("realloc");
586 II_reallocf = &Ctx.Idents.get("reallocf");
587 II_calloc = &Ctx.Idents.get("calloc");
588 II_valloc = &Ctx.Idents.get("valloc");
589 II_strdup = &Ctx.Idents.get("strdup");
590 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaks30d46682016-03-08 01:21:51 +0000591 II_wcsdup = &Ctx.Idents.get("wcsdup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000592 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000593 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
594 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaks30d46682016-03-08 01:21:51 +0000595
596 //MSVC uses `_`-prefixed instead, so we check for them too.
597 II_win_strdup = &Ctx.Idents.get("_strdup");
598 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
599 II_win_alloca = &Ctx.Idents.get("_alloca");
Anna Zaksbbec97c2017-03-09 00:01:01 +0000600
601 // Glib
602 II_g_malloc = &Ctx.Idents.get("g_malloc");
603 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
604 II_g_realloc = &Ctx.Idents.get("g_realloc");
605 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
606 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
607 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
608 II_g_free = &Ctx.Idents.get("g_free");
609 II_g_memdup = &Ctx.Idents.get("g_memdup");
Leslie Zhaie3986c52017-04-26 05:33:14 +0000610 II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
611 II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
612 II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
613 II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
614 II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
615 II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000616}
617
Anna Zaks3d348342012-02-14 21:55:24 +0000618bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000619 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000620 return true;
621
Anna Zaksd79b8402014-10-03 21:48:59 +0000622 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000623 return true;
624
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000625 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
626 return true;
627
Anton Yartsev13df0362013-03-25 01:35:45 +0000628 if (isStandardNewDelete(FD, C))
629 return true;
630
Anna Zaks46d01602012-05-18 01:16:10 +0000631 return false;
632}
633
Anna Zaksd79b8402014-10-03 21:48:59 +0000634bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
635 ASTContext &C,
636 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000637 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000638 if (!FD)
639 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000640
Anna Zaksd79b8402014-10-03 21:48:59 +0000641 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
642 MemKind == MemoryOperationKind::MOK_Free);
643 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
644 MemKind == MemoryOperationKind::MOK_Allocate);
645
Jordan Rose6cd16c52012-07-10 23:13:01 +0000646 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000647 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000648 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000649
Anna Zaksd79b8402014-10-03 21:48:59 +0000650 if (Family == AF_Malloc && CheckFree) {
Anna Zaksbbec97c2017-03-09 00:01:01 +0000651 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
652 FunI == II_g_free)
Anna Zaksd79b8402014-10-03 21:48:59 +0000653 return true;
654 }
655
656 if (Family == AF_Malloc && CheckAlloc) {
657 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
658 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
Anna Zaks30d46682016-03-08 01:21:51 +0000659 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
Anna Zaksbbec97c2017-03-09 00:01:01 +0000660 FunI == II_win_wcsdup || FunI == II_kmalloc ||
661 FunI == II_g_malloc || FunI == II_g_malloc0 ||
662 FunI == II_g_realloc || FunI == II_g_try_malloc ||
663 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
Leslie Zhaie3986c52017-04-26 05:33:14 +0000664 FunI == II_g_memdup || FunI == II_g_malloc_n ||
665 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
666 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
667 FunI == II_g_try_realloc_n)
Anna Zaksd79b8402014-10-03 21:48:59 +0000668 return true;
669 }
670
671 if (Family == AF_IfNameIndex && CheckFree) {
672 if (FunI == II_if_freenameindex)
673 return true;
674 }
675
676 if (Family == AF_IfNameIndex && CheckAlloc) {
677 if (FunI == II_if_nameindex)
678 return true;
679 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000680
681 if (Family == AF_Alloca && CheckAlloc) {
Anna Zaks30d46682016-03-08 01:21:51 +0000682 if (FunI == II_alloca || FunI == II_win_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000683 return true;
684 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000685 }
Anna Zaks3d348342012-02-14 21:55:24 +0000686
Anna Zaksd79b8402014-10-03 21:48:59 +0000687 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000688 return false;
689
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000690 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000691 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
692 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
693 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
694 if (CheckFree)
695 return true;
696 } else if (OwnKind == OwnershipAttr::Returns) {
697 if (CheckAlloc)
698 return true;
699 }
700 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000701 }
Anna Zaks3d348342012-02-14 21:55:24 +0000702
Anna Zaks3d348342012-02-14 21:55:24 +0000703 return false;
704}
705
Anton Yartsev8b662702013-03-28 16:10:38 +0000706// Tells if the callee is one of the following:
707// 1) A global non-placement new/delete operator function.
708// 2) A global placement operator function with the single placement argument
709// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000710bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
711 ASTContext &C) const {
712 if (!FD)
713 return false;
714
715 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000716 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000717 Kind != OO_Delete && Kind != OO_Array_Delete)
718 return false;
719
Anton Yartsev8b662702013-03-28 16:10:38 +0000720 // Skip all operator new/delete methods.
721 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000722 return false;
723
724 // Return true if tested operator is a standard placement nothrow operator.
725 if (FD->getNumParams() == 2) {
726 QualType T = FD->getParamDecl(1)->getType();
727 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
728 return II->getName().equals("nothrow_t");
729 }
730
731 // Skip placement operators.
732 if (FD->getNumParams() != 1 || FD->isVariadic())
733 return false;
734
735 // One of the standard new/new[]/delete/delete[] non-placement operators.
736 return true;
737}
738
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000739llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
740 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
741 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
742 //
743 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
744 //
745 // One of the possible flags is M_ZERO, which means 'give me back an
746 // allocation which is already zeroed', like calloc.
747
748 // 2-argument kmalloc(), as used in the Linux kernel:
749 //
750 // void *kmalloc(size_t size, gfp_t flags);
751 //
752 // Has the similar flag value __GFP_ZERO.
753
754 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
755 // code could be shared.
756
757 ASTContext &Ctx = C.getASTContext();
758 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
759
760 if (!KernelZeroFlagVal.hasValue()) {
761 if (OS == llvm::Triple::FreeBSD)
762 KernelZeroFlagVal = 0x0100;
763 else if (OS == llvm::Triple::NetBSD)
764 KernelZeroFlagVal = 0x0002;
765 else if (OS == llvm::Triple::OpenBSD)
766 KernelZeroFlagVal = 0x0008;
767 else if (OS == llvm::Triple::Linux)
768 // __GFP_ZERO
769 KernelZeroFlagVal = 0x8000;
770 else
771 // FIXME: We need a more general way of getting the M_ZERO value.
772 // See also: O_CREAT in UnixAPIChecker.cpp.
773
774 // Fall back to normal malloc behavior on platforms where we don't
775 // know M_ZERO.
776 return None;
777 }
778
779 // We treat the last argument as the flags argument, and callers fall-back to
780 // normal malloc on a None return. This works for the FreeBSD kernel malloc
781 // as well as Linux kmalloc.
782 if (CE->getNumArgs() < 2)
783 return None;
784
785 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
George Karpenkovd703ec92018-01-17 20:27:29 +0000786 const SVal V = C.getSVal(FlagsEx);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000787 if (!V.getAs<NonLoc>()) {
788 // The case where 'V' can be a location can only be due to a bad header,
789 // so in this case bail out.
790 return None;
791 }
792
793 NonLoc Flags = V.castAs<NonLoc>();
794 NonLoc ZeroFlag = C.getSValBuilder()
795 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
796 .castAs<NonLoc>();
797 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
798 Flags, ZeroFlag,
799 FlagsEx->getType());
800 if (MaskedFlagsUC.isUnknownOrUndef())
801 return None;
802 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
803
804 // Check if maskedFlags is non-zero.
805 ProgramStateRef TrueState, FalseState;
806 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
807
808 // If M_ZERO is set, treat this like calloc (initialized).
809 if (TrueState && !FalseState) {
810 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
811 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
812 }
813
814 return None;
815}
816
Leslie Zhaie3986c52017-04-26 05:33:14 +0000817SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
818 const Expr *BlockBytes) {
819 SValBuilder &SB = C.getSValBuilder();
820 SVal BlocksVal = C.getSVal(Blocks);
821 SVal BlockBytesVal = C.getSVal(BlockBytes);
822 ProgramStateRef State = C.getState();
823 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
824 SB.getContext().getSizeType());
825 return TotalSize;
826}
827
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000828void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000829 if (C.wasInlined)
830 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000831
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000832 const FunctionDecl *FD = C.getCalleeDecl(CE);
833 if (!FD)
834 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000835
Anna Zaks40a7eb32012-02-22 19:24:52 +0000836 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000837 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000838
839 if (FD->getKind() == Decl::Function) {
840 initIdentifierInfo(C.getASTContext());
841 IdentifierInfo *FunI = FD->getIdentifier();
842
Anna Zaksbbec97c2017-03-09 00:01:01 +0000843 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000844 if (CE->getNumArgs() < 1)
845 return;
846 if (CE->getNumArgs() < 3) {
847 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000848 if (CE->getNumArgs() == 1)
849 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000850 } else if (CE->getNumArgs() == 3) {
851 llvm::Optional<ProgramStateRef> MaybeState =
852 performKernelMalloc(CE, C, State);
853 if (MaybeState.hasValue())
854 State = MaybeState.getValue();
855 else
856 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
857 }
858 } else if (FunI == II_kmalloc) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000859 if (CE->getNumArgs() < 1)
860 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000861 llvm::Optional<ProgramStateRef> MaybeState =
862 performKernelMalloc(CE, C, State);
863 if (MaybeState.hasValue())
864 State = MaybeState.getValue();
865 else
866 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
867 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000868 if (CE->getNumArgs() < 1)
869 return;
870 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000871 State = ProcessZeroAllocation(C, CE, 0, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000872 } else if (FunI == II_realloc || FunI == II_g_realloc ||
873 FunI == II_g_try_realloc) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000874 State = ReallocMemAux(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000875 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000876 } else if (FunI == II_reallocf) {
Leslie Zhaie3986c52017-04-26 05:33:14 +0000877 State = ReallocMemAux(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000878 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000879 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000880 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000881 State = ProcessZeroAllocation(C, CE, 0, State);
882 State = ProcessZeroAllocation(C, CE, 1, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000883 } else if (FunI == II_free || FunI == II_g_free) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000884 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaks30d46682016-03-08 01:21:51 +0000885 } else if (FunI == II_strdup || FunI == II_win_strdup ||
886 FunI == II_wcsdup || FunI == II_win_wcsdup) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000887 State = MallocUpdateRefState(C, CE, State);
888 } else if (FunI == II_strndup) {
889 State = MallocUpdateRefState(C, CE, State);
Anna Zaks30d46682016-03-08 01:21:51 +0000890 } else if (FunI == II_alloca || FunI == II_win_alloca) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000891 if (CE->getNumArgs() < 1)
892 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000893 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
894 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000895 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000896 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000897 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000898 // as distinct from new/new[]/delete/delete[] expressions that are
899 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000900 // CXXDeleteExpr.
901 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000902 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000903 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
904 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000905 State = ProcessZeroAllocation(C, CE, 0, State);
906 }
907 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000908 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
909 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000910 State = ProcessZeroAllocation(C, CE, 0, State);
911 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000912 else if (K == OO_Delete || K == OO_Array_Delete)
913 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
914 else
915 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000916 } else if (FunI == II_if_nameindex) {
917 // Should we model this differently? We can allocate a fixed number of
918 // elements with zeros in the last one.
919 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
920 AF_IfNameIndex);
921 } else if (FunI == II_if_freenameindex) {
922 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000923 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
924 if (CE->getNumArgs() < 1)
925 return;
926 SValBuilder &svalBuilder = C.getSValBuilder();
927 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
928 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
929 State = ProcessZeroAllocation(C, CE, 0, State);
930 } else if (FunI == II_g_memdup) {
931 if (CE->getNumArgs() < 2)
932 return;
933 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
934 State = ProcessZeroAllocation(C, CE, 1, State);
Leslie Zhaie3986c52017-04-26 05:33:14 +0000935 } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
936 FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
937 if (CE->getNumArgs() < 2)
938 return;
939 SVal Init = UndefinedVal();
940 if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
941 SValBuilder &SB = C.getSValBuilder();
942 Init = SB.makeZeroVal(SB.getContext().CharTy);
943 }
944 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
945 State = MallocMemAux(C, CE, TotalSize, Init, State);
946 State = ProcessZeroAllocation(C, CE, 0, State);
947 State = ProcessZeroAllocation(C, CE, 1, State);
948 } else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
949 if (CE->getNumArgs() < 3)
950 return;
951 State = ReallocMemAux(C, CE, false, State, true);
952 State = ProcessZeroAllocation(C, CE, 1, State);
953 State = ProcessZeroAllocation(C, CE, 2, State);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000954 }
955 }
956
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000957 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000958 // Check all the attributes, if there are any.
959 // There can be multiple of these attributes.
960 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000961 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
962 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000963 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000964 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000965 break;
966 case OwnershipAttr::Takes:
967 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000968 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000969 break;
970 }
971 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000972 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000973 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000974}
975
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000976// Performs a 0-sized allocations check.
Artem Dergachev13b20262018-01-17 23:46:13 +0000977ProgramStateRef MallocChecker::ProcessZeroAllocation(
978 CheckerContext &C, const Expr *E, const unsigned AllocationSizeArg,
979 ProgramStateRef State, Optional<SVal> RetVal) const {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000980 if (!State)
981 return nullptr;
982
Artem Dergachev13b20262018-01-17 23:46:13 +0000983 if (!RetVal)
984 RetVal = C.getSVal(E);
985
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000986 const Expr *Arg = nullptr;
987
988 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
989 Arg = CE->getArg(AllocationSizeArg);
990 }
991 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
992 if (NE->isArray())
993 Arg = NE->getArraySize();
994 else
995 return State;
996 }
997 else
998 llvm_unreachable("not a CallExpr or CXXNewExpr");
999
1000 assert(Arg);
1001
George Karpenkovd703ec92018-01-17 20:27:29 +00001002 Optional<DefinedSVal> DefArgVal = C.getSVal(Arg).getAs<DefinedSVal>();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001003
1004 if (!DefArgVal)
1005 return State;
1006
1007 // Check if the allocation size is 0.
1008 ProgramStateRef TrueState, FalseState;
1009 SValBuilder &SvalBuilder = C.getSValBuilder();
1010 DefinedSVal Zero =
1011 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1012
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001013 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001014 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1015
1016 if (TrueState && !FalseState) {
Artem Dergachev13b20262018-01-17 23:46:13 +00001017 SymbolRef Sym = RetVal->getAsLocSymbol();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001018 if (!Sym)
1019 return State;
1020
1021 const RefState *RS = State->get<RegionState>(Sym);
Devin Coughlin81771732015-09-22 22:47:14 +00001022 if (RS) {
1023 if (RS->isAllocated())
1024 return TrueState->set<RegionState>(Sym,
1025 RefState::getAllocatedOfSizeZero(RS));
1026 else
1027 return State;
1028 } else {
1029 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1030 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1031 // tracked. Add zero-reallocated Sym to the state to catch references
1032 // to zero-allocated memory.
1033 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1034 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001035 }
1036
1037 // Assume the value is non-zero going forward.
1038 assert(FalseState);
1039 return FalseState;
1040}
1041
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001042static QualType getDeepPointeeType(QualType T) {
1043 QualType Result = T, PointeeType = T->getPointeeType();
1044 while (!PointeeType.isNull()) {
1045 Result = PointeeType;
1046 PointeeType = PointeeType->getPointeeType();
1047 }
1048 return Result;
1049}
1050
1051static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1052
1053 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1054 if (!ConstructE)
1055 return false;
1056
1057 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1058 return false;
1059
1060 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1061
1062 // Iterate over the constructor parameters.
David Majnemer59f77922016-06-24 04:05:48 +00001063 for (const auto *CtorParam : CtorD->parameters()) {
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001064
1065 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1066 if (CtorParamPointeeT.isNull())
1067 continue;
1068
1069 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1070
1071 if (CtorParamPointeeT->getAsCXXRecordDecl())
1072 return true;
1073 }
1074
1075 return false;
1076}
1077
Artem Dergachev13b20262018-01-17 23:46:13 +00001078void MallocChecker::processNewAllocation(const CXXNewExpr *NE,
1079 CheckerContext &C,
1080 SVal Target) const {
Anton Yartsev13df0362013-03-25 01:35:45 +00001081 if (NE->getNumPlacementArgs())
1082 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1083 E = NE->placement_arg_end(); I != E; ++I)
1084 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1085 checkUseAfterFree(Sym, C, *I);
1086
Anton Yartsev13df0362013-03-25 01:35:45 +00001087 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1088 return;
1089
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001090 ParentMap &PM = C.getLocationContext()->getParentMap();
1091 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1092 return;
1093
Anton Yartsev13df0362013-03-25 01:35:45 +00001094 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001095 // The return value from operator new is bound to a specified initialization
1096 // value (if any) and we don't want to loose this value. So we call
1097 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +00001098 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001099 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Artem Dergachev13b20262018-01-17 23:46:13 +00001100 : AF_CXXNew, Target);
1101 State = addExtentSize(C, NE, State, Target);
1102 State = ProcessZeroAllocation(C, NE, 0, State, Target);
Anton Yartsev13df0362013-03-25 01:35:45 +00001103 C.addTransition(State);
1104}
1105
Artem Dergachev13b20262018-01-17 23:46:13 +00001106void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1107 CheckerContext &C) const {
1108 if (!C.getAnalysisManager().getAnalyzerOptions().mayInlineCXXAllocator())
1109 processNewAllocation(NE, C, C.getSVal(NE));
1110}
1111
1112void MallocChecker::checkNewAllocator(const CXXNewExpr *NE, SVal Target,
1113 CheckerContext &C) const {
1114 if (!C.wasInlined)
1115 processNewAllocation(NE, C, Target);
1116}
1117
Gabor Horvath73040272016-09-19 20:39:52 +00001118// Sets the extent value of the MemRegion allocated by
1119// new expression NE to its size in Bytes.
1120//
1121ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1122 const CXXNewExpr *NE,
Artem Dergachev13b20262018-01-17 23:46:13 +00001123 ProgramStateRef State,
1124 SVal Target) {
Gabor Horvath73040272016-09-19 20:39:52 +00001125 if (!State)
1126 return nullptr;
1127 SValBuilder &svalBuilder = C.getSValBuilder();
1128 SVal ElementCount;
Gabor Horvath73040272016-09-19 20:39:52 +00001129 const SubRegion *Region;
1130 if (NE->isArray()) {
1131 const Expr *SizeExpr = NE->getArraySize();
George Karpenkovd703ec92018-01-17 20:27:29 +00001132 ElementCount = C.getSVal(SizeExpr);
Gabor Horvath73040272016-09-19 20:39:52 +00001133 // Store the extent size for the (symbolic)region
1134 // containing the elements.
Artem Dergachev13b20262018-01-17 23:46:13 +00001135 Region = Target.getAsRegion()
Gabor Horvath73040272016-09-19 20:39:52 +00001136 ->getAs<SubRegion>()
Artem Dergachev13b20262018-01-17 23:46:13 +00001137 ->StripCasts()
Gabor Horvath73040272016-09-19 20:39:52 +00001138 ->getAs<SubRegion>();
1139 } else {
1140 ElementCount = svalBuilder.makeIntVal(1, true);
Artem Dergachev13b20262018-01-17 23:46:13 +00001141 Region = Target.getAsRegion()->getAs<SubRegion>();
Gabor Horvath73040272016-09-19 20:39:52 +00001142 }
1143 assert(Region);
1144
1145 // Set the region's extent equal to the Size in Bytes.
1146 QualType ElementType = NE->getAllocatedType();
1147 ASTContext &AstContext = C.getASTContext();
1148 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1149
Devin Coughline3b75de2016-12-16 18:41:40 +00001150 if (ElementCount.getAs<NonLoc>()) {
Gabor Horvath73040272016-09-19 20:39:52 +00001151 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1152 // size in Bytes = ElementCount*TypeSize
1153 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1154 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1155 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1156 svalBuilder.getArrayIndexType());
1157 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1158 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1159 State = State->assume(extentMatchesSize, true);
1160 }
1161 return State;
1162}
1163
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001164void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001165 CheckerContext &C) const {
1166
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001167 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +00001168 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1169 checkUseAfterFree(Sym, C, DE->getArgument());
1170
Anton Yartsev13df0362013-03-25 01:35:45 +00001171 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1172 return;
1173
1174 ProgramStateRef State = C.getState();
1175 bool ReleasedAllocated;
1176 State = FreeMemAux(C, DE->getArgument(), DE, State,
1177 /*Hold*/false, ReleasedAllocated);
1178
1179 C.addTransition(State);
1180}
1181
Jordan Rose613f3c02013-03-09 00:59:10 +00001182static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1183 // If the first selector piece is one of the names below, assume that the
1184 // object takes ownership of the memory, promising to eventually deallocate it
1185 // with free().
1186 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1187 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1188 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
Alexander Kornienko9c104902015-12-28 13:06:58 +00001189 return FirstSlot == "dataWithBytesNoCopy" ||
1190 FirstSlot == "initWithBytesNoCopy" ||
1191 FirstSlot == "initWithCharactersNoCopy";
Anna Zaks0d6989b2012-06-22 02:04:31 +00001192}
1193
Jordan Rose613f3c02013-03-09 00:59:10 +00001194static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1195 Selector S = Call.getSelector();
1196
1197 // FIXME: We should not rely on fully-constrained symbols being folded.
1198 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1199 if (S.getNameForSlot(i).equals("freeWhenDone"))
1200 return !Call.getArgSVal(i).isZeroConstant();
1201
1202 return None;
1203}
1204
Anna Zaks67291b92012-11-13 03:18:01 +00001205void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1206 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001207 if (C.wasInlined)
1208 return;
1209
Jordan Rose613f3c02013-03-09 00:59:10 +00001210 if (!isKnownDeallocObjCMethodName(Call))
1211 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001212
Jordan Rose613f3c02013-03-09 00:59:10 +00001213 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1214 if (!*FreeWhenDone)
1215 return;
1216
1217 bool ReleasedAllocatedMemory;
1218 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1219 Call.getOriginExpr(), C.getState(),
1220 /*Hold=*/true, ReleasedAllocatedMemory,
1221 /*RetNullOnFailure=*/true);
1222
1223 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001224}
1225
Richard Smith852e9ce2013-11-27 01:46:48 +00001226ProgramStateRef
1227MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001228 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001229 ProgramStateRef State) const {
1230 if (!State)
1231 return nullptr;
1232
Richard Smith852e9ce2013-11-27 01:46:48 +00001233 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001234 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001235
Joel E. Dennya6555112018-04-02 19:43:34 +00001236 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001237 if (I != E) {
Joel E. Denny81508102018-03-13 14:51:22 +00001238 return MallocMemAux(C, CE, CE->getArg(I->getASTIndex()), UndefinedVal(),
1239 State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001240 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001241 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1242}
1243
1244ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1245 const CallExpr *CE,
1246 const Expr *SizeEx, SVal Init,
1247 ProgramStateRef State,
1248 AllocationFamily Family) {
1249 if (!State)
1250 return nullptr;
1251
George Karpenkovd703ec92018-01-17 20:27:29 +00001252 return MallocMemAux(C, CE, C.getSVal(SizeEx), Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001253}
1254
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001255ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001256 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001257 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001258 ProgramStateRef State,
1259 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001260 if (!State)
1261 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001262
Jordan Rosef69e65f2014-09-05 16:33:51 +00001263 // We expect the malloc functions to return a pointer.
1264 if (!Loc::isLocType(CE->getType()))
1265 return nullptr;
1266
Anna Zaks3563fde2012-06-07 03:57:32 +00001267 // Bind the return value to the symbolic value from the heap region.
1268 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1269 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001270 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001271 SValBuilder &svalBuilder = C.getSValBuilder();
1272 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001273 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1274 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001275 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001276
Jordy Rose674bd552010-07-04 00:00:41 +00001277 // Fill the region with the initialization value.
Artem Dergachev806486c2018-05-04 21:56:51 +00001278 State = State->bindDefaultInitial(RetVal, Init, LCtx);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001279
Jordy Rose674bd552010-07-04 00:00:41 +00001280 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001281 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001282 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001283 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001284 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001285 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001286 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001287 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001288 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001289 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001290 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001291
Anton Yartsev05789592013-03-28 17:05:19 +00001292 State = State->assume(extentMatchesSize, true);
1293 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001294 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001295
Anton Yartsev05789592013-03-28 17:05:19 +00001296 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001297}
1298
1299ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001300 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001301 ProgramStateRef State,
Artem Dergachev13b20262018-01-17 23:46:13 +00001302 AllocationFamily Family,
1303 Optional<SVal> RetVal) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001304 if (!State)
1305 return nullptr;
1306
Anna Zaks40a7eb32012-02-22 19:24:52 +00001307 // Get the return value.
Artem Dergachev13b20262018-01-17 23:46:13 +00001308 if (!RetVal)
1309 RetVal = C.getSVal(E);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001310
1311 // We expect the malloc functions to return a pointer.
Artem Dergachev13b20262018-01-17 23:46:13 +00001312 if (!RetVal->getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001313 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001314
Artem Dergachev13b20262018-01-17 23:46:13 +00001315 SymbolRef Sym = RetVal->getAsLocSymbol();
1316 // This is a return value of a function that was not inlined, such as malloc()
1317 // or new(). We've checked that in the caller. Therefore, it must be a symbol.
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001318 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001319
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001320 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001321 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001322}
1323
Anna Zaks40a7eb32012-02-22 19:24:52 +00001324ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1325 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001326 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001327 ProgramStateRef State) const {
1328 if (!State)
1329 return nullptr;
1330
Richard Smith852e9ce2013-11-27 01:46:48 +00001331 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001332 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001333
Anna Zaksfe6eb672012-08-24 02:28:20 +00001334 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001335
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001336 for (const auto &Arg : Att->args()) {
Joel E. Denny81508102018-03-13 14:51:22 +00001337 ProgramStateRef StateI = FreeMemAux(
1338 C, CE, State, Arg.getASTIndex(),
1339 Att->getOwnKind() == OwnershipAttr::Holds, ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001340 if (StateI)
1341 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001342 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001343 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001344}
1345
Ted Kremenek49b1e382012-01-26 21:29:00 +00001346ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001347 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001348 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001349 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001350 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001351 bool &ReleasedAllocated,
1352 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001353 if (!State)
1354 return nullptr;
1355
Anna Zaksb508d292012-04-10 23:41:11 +00001356 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001357 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001358
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001359 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001360 ReleasedAllocated, ReturnsNullOnFailure);
1361}
1362
Anna Zaksa14c1d02012-11-13 19:47:40 +00001363/// Checks if the previous call to free on the given symbol failed - if free
1364/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001365static bool didPreviousFreeFail(ProgramStateRef State,
1366 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001367 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001368 if (Ret) {
1369 assert(*Ret && "We should not store the null return symbol");
1370 ConstraintManager &CMgr = State->getConstraintManager();
1371 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001372 RetStatusSymbol = *Ret;
1373 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001374 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001375 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001376}
1377
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001378AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001379 const Stmt *S) const {
1380 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001381 return AF_None;
1382
Anton Yartseve3377fb2013-04-04 23:46:29 +00001383 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001384 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001385
1386 if (!FD)
1387 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1388
Anton Yartsev05789592013-03-28 17:05:19 +00001389 ASTContext &Ctx = C.getASTContext();
1390
Anna Zaksd79b8402014-10-03 21:48:59 +00001391 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001392 return AF_Malloc;
1393
1394 if (isStandardNewDelete(FD, Ctx)) {
1395 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001396 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001397 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001398 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001399 return AF_CXXNewArray;
1400 }
1401
Anna Zaksd79b8402014-10-03 21:48:59 +00001402 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1403 return AF_IfNameIndex;
1404
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001405 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1406 return AF_Alloca;
1407
Anton Yartsev05789592013-03-28 17:05:19 +00001408 return AF_None;
1409 }
1410
Anton Yartseve3377fb2013-04-04 23:46:29 +00001411 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1412 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1413
1414 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001415 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1416
Anton Yartseve3377fb2013-04-04 23:46:29 +00001417 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001418 return AF_Malloc;
1419
1420 return AF_None;
1421}
1422
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001423bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001424 const Expr *E) const {
1425 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1426 // FIXME: This doesn't handle indirect calls.
1427 const FunctionDecl *FD = CE->getDirectCallee();
1428 if (!FD)
1429 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001430
Anton Yartsev05789592013-03-28 17:05:19 +00001431 os << *FD;
1432 if (!FD->isOverloadedOperator())
1433 os << "()";
1434 return true;
1435 }
1436
1437 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1438 if (Msg->isInstanceMessage())
1439 os << "-";
1440 else
1441 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001442 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001443 return true;
1444 }
1445
1446 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001447 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001448 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1449 << "'";
1450 return true;
1451 }
1452
1453 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001454 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001455 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1456 << "'";
1457 return true;
1458 }
1459
1460 return false;
1461}
1462
1463void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1464 const Expr *E) const {
1465 AllocationFamily Family = getAllocationFamily(C, E);
1466
1467 switch(Family) {
1468 case AF_Malloc: os << "malloc()"; return;
1469 case AF_CXXNew: os << "'new'"; return;
1470 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001471 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Reka Kovacs18775fc2018-06-09 13:03:49 +00001472 case AF_InternalBuffer: os << "container-specific allocator"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001473 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001474 case AF_None: llvm_unreachable("not a deallocation expression");
1475 }
1476}
1477
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001478void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001479 AllocationFamily Family) const {
1480 switch(Family) {
1481 case AF_Malloc: os << "free()"; return;
1482 case AF_CXXNew: os << "'delete'"; return;
1483 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001484 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Reka Kovacs18775fc2018-06-09 13:03:49 +00001485 case AF_InternalBuffer: os << "container-specific deallocator"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001486 case AF_Alloca:
1487 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001488 }
1489}
1490
Anna Zaks0d6989b2012-06-22 02:04:31 +00001491ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1492 const Expr *ArgExpr,
1493 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001494 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001495 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001496 bool &ReleasedAllocated,
1497 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001498
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001499 if (!State)
1500 return nullptr;
1501
George Karpenkovd703ec92018-01-17 20:27:29 +00001502 SVal ArgVal = C.getSVal(ArgExpr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001503 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001504 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001505 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001506
1507 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001508 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001509 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001510
Anna Zaksad01ef52012-02-14 00:26:13 +00001511 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001512 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001513 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001514 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001515 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001516
Jordy Rose3597b212010-06-07 19:32:37 +00001517 // Unknown values could easily be okay
1518 // Undefined values are handled elsewhere
1519 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001520 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001521
Jordy Rose3597b212010-06-07 19:32:37 +00001522 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001523
Jordy Rose3597b212010-06-07 19:32:37 +00001524 // Nonlocs can't be freed, of course.
1525 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1526 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001527 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001528 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001529 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001530
Jordy Rose3597b212010-06-07 19:32:37 +00001531 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001532
Jordy Rose3597b212010-06-07 19:32:37 +00001533 // Blocks might show up as heap data, but should not be free()d
1534 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001535 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001536 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001537 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001538
Jordy Rose3597b212010-06-07 19:32:37 +00001539 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001540
1541 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001542 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001543 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1544 // FIXME: at the time this code was written, malloc() regions were
1545 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1546 // This means that there isn't actually anything from HeapSpaceRegion
1547 // that should be freed, even though we allow it here.
1548 // Of course, free() can work on memory allocated outside the current
1549 // function, so UnknownSpaceRegion is always a possibility.
1550 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001551
1552 if (isa<AllocaRegion>(R))
1553 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1554 else
1555 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1556
Craig Topper0dbb7832014-05-27 02:45:47 +00001557 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001558 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001559
1560 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001561 // Various cases could lead to non-symbol values here.
1562 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001563 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001564 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001565
Anna Zaksc89ad072013-02-07 23:05:47 +00001566 SymbolRef SymBase = SrBase->getSymbol();
1567 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001568 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001569
Anton Yartseve3377fb2013-04-04 23:46:29 +00001570 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001571
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001572 // Memory returned by alloca() shouldn't be freed.
1573 if (RsBase->getAllocationFamily() == AF_Alloca) {
1574 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1575 return nullptr;
1576 }
1577
Anna Zaks93a21a82013-04-09 00:30:28 +00001578 // Check for double free first.
1579 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001580 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1581 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1582 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001583 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001584
Anna Zaks93a21a82013-04-09 00:30:28 +00001585 // If the pointer is allocated or escaped, but we are now trying to free it,
1586 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001587 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001588 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001589
1590 // Check if an expected deallocation function matches the real one.
1591 bool DeallocMatchesAlloc =
1592 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1593 if (!DeallocMatchesAlloc) {
1594 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001595 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001596 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001597 }
1598
1599 // Check if the memory location being freed is the actual location
1600 // allocated, or an offset.
1601 RegionOffset Offset = R->getAsOffset();
1602 if (Offset.isValid() &&
1603 !Offset.hasSymbolicOffset() &&
1604 Offset.getOffset() != 0) {
1605 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001606 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001607 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001608 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001609 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001610 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001611 }
1612
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00001613 if (SymBase->getType()->isFunctionPointerType()) {
1614 ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1615 return nullptr;
1616 }
1617
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001618 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001619 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001620
Anna Zaksa14c1d02012-11-13 19:47:40 +00001621 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001622 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001623
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001624 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001625 // failed.
1626 if (ReturnsNullOnFailure) {
1627 SVal RetVal = C.getSVal(ParentExpr);
1628 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1629 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001630 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1631 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001632 }
1633 }
1634
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001635 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1636 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001637 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001638 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001639 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001640 RefState::getRelinquished(Family,
1641 ParentExpr));
1642
1643 return State->set<RegionState>(SymBase,
1644 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001645}
1646
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001647Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001648MallocChecker::getCheckIfTracked(AllocationFamily Family,
1649 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001650 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001651 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001652 case AF_Alloca:
1653 case AF_IfNameIndex: {
1654 if (ChecksEnabled[CK_MallocChecker])
1655 return CK_MallocChecker;
1656
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001657 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001658 }
1659 case AF_CXXNew:
Reka Kovacs18775fc2018-06-09 13:03:49 +00001660 case AF_CXXNewArray:
1661 // FIXME: Add new CheckKind for AF_InternalBuffer.
1662 case AF_InternalBuffer: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001663 if (IsALeakCheck) {
1664 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1665 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001666 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001667 else {
1668 if (ChecksEnabled[CK_NewDeleteChecker])
1669 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001670 }
1671 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001672 }
1673 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001674 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001675 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001676 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001677 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001678}
1679
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001680Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001681MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001682 const Stmt *AllocDeallocStmt,
1683 bool IsALeakCheck) const {
1684 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1685 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001686}
1687
1688Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001689MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1690 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001691 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1692 return CK_MallocChecker;
1693
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001694 const RefState *RS = C.getState()->get<RegionState>(Sym);
1695 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001696 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001697}
1698
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001699bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001700 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001701 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001702 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001703 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001704 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001705 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001706 else
1707 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001708
Jordy Rose3597b212010-06-07 19:32:37 +00001709 return true;
1710}
1711
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001712bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001713 const MemRegion *MR) {
1714 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +00001715 case MemRegion::FunctionCodeRegionKind: {
1716 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001717 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001718 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001719 else
1720 os << "the address of a function";
1721 return true;
1722 }
Artem Dergachev73f018e2016-01-13 13:49:29 +00001723 case MemRegion::BlockCodeRegionKind:
Jordy Rose3597b212010-06-07 19:32:37 +00001724 os << "block text";
1725 return true;
1726 case MemRegion::BlockDataRegionKind:
1727 // FIXME: where the block came from?
1728 os << "a block";
1729 return true;
1730 default: {
1731 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001732
Anna Zaks8158ef02012-01-04 23:54:01 +00001733 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001734 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1735 const VarDecl *VD;
1736 if (VR)
1737 VD = VR->getDecl();
1738 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001739 VD = nullptr;
1740
Jordy Rose3597b212010-06-07 19:32:37 +00001741 if (VD)
1742 os << "the address of the local variable '" << VD->getName() << "'";
1743 else
1744 os << "the address of a local stack variable";
1745 return true;
1746 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001747
1748 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001749 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1750 const VarDecl *VD;
1751 if (VR)
1752 VD = VR->getDecl();
1753 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001754 VD = nullptr;
1755
Jordy Rose3597b212010-06-07 19:32:37 +00001756 if (VD)
1757 os << "the address of the parameter '" << VD->getName() << "'";
1758 else
1759 os << "the address of a parameter";
1760 return true;
1761 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001762
1763 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001764 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1765 const VarDecl *VD;
1766 if (VR)
1767 VD = VR->getDecl();
1768 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001769 VD = nullptr;
1770
Jordy Rose3597b212010-06-07 19:32:37 +00001771 if (VD) {
1772 if (VD->isStaticLocal())
1773 os << "the address of the static variable '" << VD->getName() << "'";
1774 else
1775 os << "the address of the global variable '" << VD->getName() << "'";
1776 } else
1777 os << "the address of a global variable";
1778 return true;
1779 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001780
1781 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001782 }
1783 }
1784}
1785
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001786void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1787 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001788 const Expr *DeallocExpr) const {
1789
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001790 if (!ChecksEnabled[CK_MallocChecker] &&
1791 !ChecksEnabled[CK_NewDeleteChecker])
1792 return;
1793
1794 Optional<MallocChecker::CheckKind> CheckKind =
1795 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001796 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001797 return;
1798
Devin Coughline39bd402015-09-16 22:03:05 +00001799 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001800 if (!BT_BadFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001801 BT_BadFree[*CheckKind].reset(new BugType(
1802 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001803
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001804 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001805 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001806
Jordy Rose3597b212010-06-07 19:32:37 +00001807 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001808 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1809 MR = ER->getSuperRegion();
1810
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001811 os << "Argument to ";
1812 if (!printAllocDeallocName(os, C, DeallocExpr))
1813 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001814
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001815 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001816 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001817 : SummarizeValue(os, ArgVal);
1818 if (Summarized)
1819 os << ", which is not memory allocated by ";
1820 else
1821 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001822
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001823 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001824
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001825 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001826 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001827 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001828 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001829 }
1830}
1831
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001832void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001833 SourceRange Range) const {
1834
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001835 Optional<MallocChecker::CheckKind> CheckKind;
1836
1837 if (ChecksEnabled[CK_MallocChecker])
1838 CheckKind = CK_MallocChecker;
1839 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1840 CheckKind = CK_MismatchedDeallocatorChecker;
1841 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001842 return;
1843
Devin Coughline39bd402015-09-16 22:03:05 +00001844 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001845 if (!BT_FreeAlloca[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001846 BT_FreeAlloca[*CheckKind].reset(new BugType(
1847 CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001848
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001849 auto R = llvm::make_unique<BugReport>(
1850 *BT_FreeAlloca[*CheckKind],
1851 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001852 R->markInteresting(ArgVal.getAsRegion());
1853 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001854 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001855 }
1856}
1857
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001858void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001859 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001860 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001861 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001862 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001863 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001864
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001865 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001866 return;
1867
Devin Coughline39bd402015-09-16 22:03:05 +00001868 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001869 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001870 BT_MismatchedDealloc.reset(
1871 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001872 "Bad deallocator", categories::MemoryError));
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001873
Anton Yartsev05789592013-03-28 17:05:19 +00001874 SmallString<100> buf;
1875 llvm::raw_svector_ostream os(buf);
1876
1877 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1878 SmallString<20> AllocBuf;
1879 llvm::raw_svector_ostream AllocOs(AllocBuf);
1880 SmallString<20> DeallocBuf;
1881 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1882
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001883 if (OwnershipTransferred) {
1884 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1885 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001886 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001887 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001888
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001889 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001890
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001891 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1892 os << " allocated by " << AllocOs.str();
1893 } else {
1894 os << "Memory";
1895 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1896 os << " allocated by " << AllocOs.str();
1897
1898 os << " should be deallocated by ";
1899 printExpectedDeallocName(os, RS->getAllocationFamily());
1900
1901 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1902 os << ", not " << DeallocOs.str();
1903 }
Anton Yartsev05789592013-03-28 17:05:19 +00001904
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001905 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001906 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001907 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001908 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001909 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001910 }
1911}
1912
Anna Zaksc89ad072013-02-07 23:05:47 +00001913void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001914 SourceRange Range, const Expr *DeallocExpr,
1915 const Expr *AllocExpr) const {
1916
Anton Yartsev05789592013-03-28 17:05:19 +00001917
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001918 if (!ChecksEnabled[CK_MallocChecker] &&
1919 !ChecksEnabled[CK_NewDeleteChecker])
1920 return;
1921
1922 Optional<MallocChecker::CheckKind> CheckKind =
1923 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001924 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001925 return;
1926
Devin Coughline39bd402015-09-16 22:03:05 +00001927 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001928 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001929 return;
1930
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001931 if (!BT_OffsetFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001932 BT_OffsetFree[*CheckKind].reset(new BugType(
1933 CheckNames[*CheckKind], "Offset free", categories::MemoryError));
Anna Zaksc89ad072013-02-07 23:05:47 +00001934
1935 SmallString<100> buf;
1936 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001937 SmallString<20> AllocNameBuf;
1938 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001939
1940 const MemRegion *MR = ArgVal.getAsRegion();
1941 assert(MR && "Only MemRegion based symbols can have offset free errors");
1942
1943 RegionOffset Offset = MR->getAsOffset();
1944 assert((Offset.isValid() &&
1945 !Offset.hasSymbolicOffset() &&
1946 Offset.getOffset() != 0) &&
1947 "Only symbols with a valid offset can have offset free errors");
1948
1949 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1950
Anton Yartsev05789592013-03-28 17:05:19 +00001951 os << "Argument to ";
1952 if (!printAllocDeallocName(os, C, DeallocExpr))
1953 os << "deallocator";
1954 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001955 << offsetBytes
1956 << " "
1957 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001958 << " from the start of ";
1959 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1960 os << "memory allocated by " << AllocNameOs.str();
1961 else
1962 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001963
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001964 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001965 R->markInteresting(MR->getBaseRegion());
1966 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001967 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001968}
1969
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001970void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1971 SymbolRef Sym) const {
1972
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001973 if (!ChecksEnabled[CK_MallocChecker] &&
1974 !ChecksEnabled[CK_NewDeleteChecker])
1975 return;
1976
1977 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001978 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001979 return;
1980
Devin Coughline39bd402015-09-16 22:03:05 +00001981 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001982 if (!BT_UseFree[*CheckKind])
1983 BT_UseFree[*CheckKind].reset(new BugType(
Artem Dergachevb6a513d2017-05-03 11:47:13 +00001984 CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001985
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001986 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1987 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001988
1989 R->markInteresting(Sym);
1990 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001991 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001992 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001993 }
1994}
1995
1996void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001997 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001998 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001999
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002000 if (!ChecksEnabled[CK_MallocChecker] &&
2001 !ChecksEnabled[CK_NewDeleteChecker])
2002 return;
2003
2004 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002005 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00002006 return;
2007
Devin Coughline39bd402015-09-16 22:03:05 +00002008 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002009 if (!BT_DoubleFree[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002010 BT_DoubleFree[*CheckKind].reset(new BugType(
2011 CheckNames[*CheckKind], "Double free", categories::MemoryError));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002012
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002013 auto R = llvm::make_unique<BugReport>(
2014 *BT_DoubleFree[*CheckKind],
2015 (Released ? "Attempt to free released memory"
2016 : "Attempt to free non-owned memory"),
2017 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002018 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00002019 R->markInteresting(Sym);
2020 if (PrevSym)
2021 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00002022 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002023 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002024 }
2025}
2026
Jordan Rose656fdd52014-01-08 18:46:55 +00002027void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2028
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002029 if (!ChecksEnabled[CK_NewDeleteChecker])
2030 return;
2031
2032 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002033 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00002034 return;
2035
Devin Coughline39bd402015-09-16 22:03:05 +00002036 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00002037 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002038 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002039 "Double delete",
2040 categories::MemoryError));
Jordan Rose656fdd52014-01-08 18:46:55 +00002041
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002042 auto R = llvm::make_unique<BugReport>(
2043 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00002044
2045 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002046 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002047 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00002048 }
2049}
2050
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002051void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2052 SourceRange Range,
2053 SymbolRef Sym) const {
2054
2055 if (!ChecksEnabled[CK_MallocChecker] &&
2056 !ChecksEnabled[CK_NewDeleteChecker])
2057 return;
2058
2059 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2060
2061 if (!CheckKind.hasValue())
2062 return;
2063
Devin Coughline39bd402015-09-16 22:03:05 +00002064 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002065 if (!BT_UseZerroAllocated[*CheckKind])
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002066 BT_UseZerroAllocated[*CheckKind].reset(
2067 new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2068 categories::MemoryError));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002069
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002070 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2071 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002072
2073 R->addRange(Range);
2074 if (Sym) {
2075 R->markInteresting(Sym);
2076 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2077 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002078 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002079 }
2080}
2081
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002082void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2083 SourceRange Range,
2084 const Expr *FreeExpr) const {
2085 if (!ChecksEnabled[CK_MallocChecker])
2086 return;
2087
2088 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2089 if (!CheckKind.hasValue())
2090 return;
2091
2092 if (ExplodedNode *N = C.generateErrorNode()) {
2093 if (!BT_BadFree[*CheckKind])
Artem Dergachev9849f592018-02-08 23:28:29 +00002094 BT_BadFree[*CheckKind].reset(new BugType(
2095 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002096
2097 SmallString<100> Buf;
2098 llvm::raw_svector_ostream Os(Buf);
2099
2100 const MemRegion *MR = ArgVal.getAsRegion();
2101 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2102 MR = ER->getSuperRegion();
2103
2104 Os << "Argument to ";
2105 if (!printAllocDeallocName(Os, C, FreeExpr))
2106 Os << "deallocator";
2107
2108 Os << " is a function pointer";
2109
2110 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2111 R->markInteresting(MR);
2112 R->addRange(Range);
2113 C.emitReport(std::move(R));
2114 }
2115}
2116
Leslie Zhaie3986c52017-04-26 05:33:14 +00002117ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2118 const CallExpr *CE,
2119 bool FreesOnFail,
Daniel Marjamakia43a8f52017-05-02 11:46:12 +00002120 ProgramStateRef State,
Leslie Zhaie3986c52017-04-26 05:33:14 +00002121 bool SuffixWithN) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002122 if (!State)
2123 return nullptr;
2124
Leslie Zhaie3986c52017-04-26 05:33:14 +00002125 if (SuffixWithN && CE->getNumArgs() < 3)
2126 return nullptr;
2127 else if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002128 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002129
Ted Kremenek90af9092010-12-02 07:49:45 +00002130 const Expr *arg0Expr = CE->getArg(0);
George Karpenkovd703ec92018-01-17 20:27:29 +00002131 SVal Arg0Val = C.getSVal(arg0Expr);
David Blaikie2fdacbc2013-02-20 05:52:05 +00002132 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002133 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00002134 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002135
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002136 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002137
Ted Kremenek90af9092010-12-02 07:49:45 +00002138 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002139 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002140
Leslie Zhaie3986c52017-04-26 05:33:14 +00002141 // Get the size argument.
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002142 const Expr *Arg1 = CE->getArg(1);
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002143
2144 // Get the value of the size argument.
George Karpenkovd703ec92018-01-17 20:27:29 +00002145 SVal TotalSize = C.getSVal(Arg1);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002146 if (SuffixWithN)
2147 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2148 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002149 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002150
2151 // Compare the size argument to 0.
2152 DefinedOrUnknownSVal SizeZero =
Leslie Zhaie3986c52017-04-26 05:33:14 +00002153 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002154 svalBuilder.makeIntValWithPtrWidth(0, false));
2155
Anna Zaksd56c8792012-02-13 18:05:39 +00002156 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002157 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00002158 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002159 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00002160 // We only assume exceptional states if they are definitely true; if the
2161 // state is under-constrained, assume regular realloc behavior.
2162 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2163 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2164
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002165 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002166 // malloc(size).
Leslie Zhaie3986c52017-04-26 05:33:14 +00002167 if (PrtIsNull && !SizeIsZero) {
2168 ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002169 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002170 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002171 }
2172
Anna Zaksd56c8792012-02-13 18:05:39 +00002173 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00002174 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002175
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002176 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00002177 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002178 SymbolRef FromPtr = arg0Val.getAsSymbol();
George Karpenkovd703ec92018-01-17 20:27:29 +00002179 SVal RetVal = C.getSVal(CE);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002180 SymbolRef ToPtr = RetVal.getAsSymbol();
2181 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00002182 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00002183
Anna Zaksfe6eb672012-08-24 02:28:20 +00002184 bool ReleasedAllocated = false;
2185
Anna Zaksd56c8792012-02-13 18:05:39 +00002186 // If the size is 0, free the memory.
2187 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00002188 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2189 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00002190 // The semantics of the return value are:
2191 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00002192 // to free() is returned. We just free the input pointer and do not add
2193 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00002194 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00002195 }
2196
2197 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00002198 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002199 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00002200
Leslie Zhaie3986c52017-04-26 05:33:14 +00002201 ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
Anna Zaksd56c8792012-02-13 18:05:39 +00002202 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002203 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00002204 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00002205
Anna Zaks75cfbb62012-09-12 22:57:34 +00002206 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2207 if (FreesOnFail)
2208 Kind = RPIsFreeOnFailure;
2209 else if (!ReleasedAllocated)
2210 Kind = RPDoNotTrackAfterFailure;
2211
Anna Zaksfe6eb672012-08-24 02:28:20 +00002212 // Record the info about the reallocated symbol so that we could properly
2213 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00002214 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00002215 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00002216 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00002217 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002218 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002219 }
Craig Topper0dbb7832014-05-27 02:45:47 +00002220 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00002221}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002222
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002223ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002224 ProgramStateRef State) {
2225 if (!State)
2226 return nullptr;
2227
Anna Zaksb508d292012-04-10 23:41:11 +00002228 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002229 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002230
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002231 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek90af9092010-12-02 07:49:45 +00002232 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Leslie Zhaie3986c52017-04-26 05:33:14 +00002233 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002234
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002235 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002236}
2237
Anna Zaksfc2e1532012-03-21 19:45:08 +00002238LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002239MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2240 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002241 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002242 // Walk the ExplodedGraph backwards and find the first node that referred to
2243 // the tracked symbol.
2244 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002245 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002246
2247 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002248 ProgramStateRef State = N->getState();
2249 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002250 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002251
2252 // Find the most recent expression bound to the symbol in the current
2253 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002254 if (!ReferenceRegion) {
2255 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2256 SVal Val = State->getSVal(MR);
2257 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002258 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002259 // Do not show local variables belonging to a function other than
2260 // where the error is reported.
2261 if (!VR ||
2262 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2263 ReferenceRegion = MR;
2264 }
2265 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002266 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002267
Anna Zaks486a0ff2015-02-05 01:02:53 +00002268 // Allocation node, is the last node in the current or parent context in
2269 // which the symbol was tracked.
2270 const LocationContext *NContext = N->getLocationContext();
2271 if (NContext == LeakContext ||
2272 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002273 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002274 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002275 }
2276
Anna Zaksa043d0c2013-01-08 00:25:29 +00002277 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002278}
2279
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002280void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2281 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002282
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002283 if (!ChecksEnabled[CK_MallocChecker] &&
2284 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002285 return;
2286
Anton Yartsev9907fc92015-03-04 23:18:21 +00002287 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002288 assert(RS && "cannot leak an untracked symbol");
2289 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002290
2291 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002292 return;
2293
Anton Yartsev2487dd62015-03-10 22:24:21 +00002294 Optional<MallocChecker::CheckKind>
2295 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002296
Anton Yartsev2487dd62015-03-10 22:24:21 +00002297 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002298 return;
2299
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002300 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002301 if (!BT_Leak[*CheckKind]) {
Artem Dergachevb6a513d2017-05-03 11:47:13 +00002302 BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2303 categories::MemoryError));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002304 // Leaks should not be reported if they are post-dominated by a sink:
2305 // (1) Sinks are higher importance bugs.
2306 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2307 // with __noreturn functions such as assert() or exit(). We choose not
2308 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002309 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002310 }
2311
Anna Zaksdf901a42012-02-23 21:38:21 +00002312 // Most bug reports are cached at the location where they occurred.
2313 // With leaks, we want to unique them by the location where they were
2314 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002315 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002316 const ExplodedNode *AllocNode = nullptr;
2317 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002318 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002319
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002320 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
Anton Yartsev6e499252013-04-05 02:25:02 +00002321 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002322 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2323 C.getSourceManager(),
2324 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002325
Anna Zaksfc2e1532012-03-21 19:45:08 +00002326 SmallString<200> buf;
2327 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002328 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002329 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002330 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002331 } else {
2332 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002333 }
2334
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002335 auto R = llvm::make_unique<BugReport>(
2336 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2337 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002338 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002339 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002340 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002341}
2342
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002343void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2344 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002345{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002346 if (!SymReaper.hasDeadSymbols())
2347 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002348
Ted Kremenek49b1e382012-01-26 21:29:00 +00002349 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002350 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002351 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002352
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002353 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002354 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2355 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002356 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002357 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002358 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002359 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002360
Zhongxing Xuc7460962009-11-13 07:48:11 +00002361 }
2362 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002363
Anna Zaksd56c8792012-02-13 18:05:39 +00002364 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002365 ReallocPairsTy RP = state->get<ReallocPairs>();
2366 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002367 if (SymReaper.isDead(I->first) ||
2368 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002369 state = state->remove<ReallocPairs>(I->first);
2370 }
2371 }
2372
Anna Zaks67291b92012-11-13 03:18:01 +00002373 // Cleanup the FreeReturnValue Map.
2374 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2375 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2376 if (SymReaper.isDead(I->first) ||
2377 SymReaper.isDead(I->second)) {
2378 state = state->remove<FreeReturnValue>(I->first);
2379 }
2380 }
2381
Anna Zaksdf901a42012-02-23 21:38:21 +00002382 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002383 ExplodedNode *N = C.getPredecessor();
2384 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002385 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002386 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2387 if (N) {
2388 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002389 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002390 reportLeak(*I, N, C);
2391 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002392 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002393 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002394
Anna Zaksdf901a42012-02-23 21:38:21 +00002395 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002396}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002397
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002398void MallocChecker::checkPreCall(const CallEvent &Call,
2399 CheckerContext &C) const {
2400
Jordan Rose656fdd52014-01-08 18:46:55 +00002401 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2402 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2403 if (!Sym || checkDoubleDelete(Sym, C))
2404 return;
2405 }
2406
Anna Zaks46d01602012-05-18 01:16:10 +00002407 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002408 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2409 const FunctionDecl *FD = FC->getDecl();
2410 if (!FD)
2411 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002412
Anna Zaksd79b8402014-10-03 21:48:59 +00002413 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002414 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002415 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2416 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2417 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002418 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002419
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002420 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002421 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002422 return;
2423 }
2424
2425 // Check if the callee of a method is deleted.
2426 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2427 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2428 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2429 return;
2430 }
2431
2432 // Check arguments for being used after free.
2433 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2434 SVal ArgSVal = Call.getArgSVal(I);
2435 if (ArgSVal.getAs<Loc>()) {
2436 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002437 if (!Sym)
2438 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002439 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002440 return;
2441 }
2442 }
2443}
2444
Anna Zaksa1b227b2012-02-08 23:16:56 +00002445void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2446 const Expr *E = S->getRetValue();
2447 if (!E)
2448 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002449
2450 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002451 ProgramStateRef State = C.getState();
George Karpenkovd703ec92018-01-17 20:27:29 +00002452 SVal RetVal = C.getSVal(E);
Anna Zaks4ca45b12012-02-22 02:36:01 +00002453 SymbolRef Sym = RetVal.getAsSymbol();
2454 if (!Sym)
2455 // If we are returning a field of the allocated struct or an array element,
2456 // the callee could still free the memory.
2457 // TODO: This logic should be a part of generic symbol escape callback.
2458 if (const MemRegion *MR = RetVal.getAsRegion())
2459 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2460 if (const SymbolicRegion *BMR =
2461 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2462 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002463
Anna Zaks3aa52252012-02-11 21:44:39 +00002464 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002465 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002466 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002467}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002468
Anna Zaks9fe80982012-03-22 00:57:20 +00002469// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002470// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002471// needed.
2472void MallocChecker::checkPostStmt(const BlockExpr *BE,
2473 CheckerContext &C) const {
2474
2475 // Scan the BlockDecRefExprs for any object the retain count checker
2476 // may be tracking.
2477 if (!BE->getBlockDecl()->hasCaptures())
2478 return;
2479
2480 ProgramStateRef state = C.getState();
2481 const BlockDataRegion *R =
George Karpenkovd703ec92018-01-17 20:27:29 +00002482 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
Anna Zaks9fe80982012-03-22 00:57:20 +00002483
2484 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2485 E = R->referenced_vars_end();
2486
2487 if (I == E)
2488 return;
2489
2490 SmallVector<const MemRegion*, 10> Regions;
2491 const LocationContext *LC = C.getLocationContext();
2492 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2493
2494 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002495 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002496 if (VR->getSuperRegion() == R) {
2497 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2498 }
2499 Regions.push_back(VR);
2500 }
2501
2502 state =
2503 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2504 Regions.data() + Regions.size()).getState();
2505 C.addTransition(state);
2506}
2507
Anna Zaks46d01602012-05-18 01:16:10 +00002508bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002509 assert(Sym);
2510 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002511 return (RS && RS->isReleased());
2512}
2513
2514bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2515 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002516
Jordan Rose656fdd52014-01-08 18:46:55 +00002517 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002518 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2519 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002520 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002521
Anna Zaksa1b227b2012-02-08 23:16:56 +00002522 return false;
2523}
2524
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002525void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2526 const Stmt *S) const {
2527 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002528
Devin Coughlin81771732015-09-22 22:47:14 +00002529 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2530 if (RS->isAllocatedOfSizeZero())
2531 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2532 }
2533 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2534 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2535 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002536}
2537
Jordan Rose656fdd52014-01-08 18:46:55 +00002538bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2539
2540 if (isReleased(Sym, C)) {
2541 ReportDoubleDelete(C, Sym);
2542 return true;
2543 }
2544 return false;
2545}
2546
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002547// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002548void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2549 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002550 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002551 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002552 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002553 checkUseZeroAllocated(Sym, C, S);
2554 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002555}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002556
Anna Zaksbb1ef902012-02-11 21:02:35 +00002557// If a symbolic region is assumed to NULL (or another constant), stop tracking
2558// it - assuming that allocation failed on this path.
2559ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2560 SVal Cond,
2561 bool Assumption) const {
2562 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002563 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002564 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002565 ConstraintManager &CMgr = state->getConstraintManager();
2566 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2567 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002568 state = state->remove<RegionState>(I.getKey());
2569 }
2570
Anna Zaksd56c8792012-02-13 18:05:39 +00002571 // Realloc returns 0 when reallocation fails, which means that we should
2572 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002573 ReallocPairsTy RP = state->get<ReallocPairs>();
2574 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002575 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002576 ConstraintManager &CMgr = state->getConstraintManager();
2577 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002578 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002579 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002580
Anna Zaks75cfbb62012-09-12 22:57:34 +00002581 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2582 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2583 if (RS->isReleased()) {
2584 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002585 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002586 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002587 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2588 state = state->remove<RegionState>(ReallocSym);
2589 else
2590 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002591 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002592 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002593 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002594 }
2595
Anna Zaksbb1ef902012-02-11 21:02:35 +00002596 return state;
2597}
2598
Anna Zaks8ebeb642013-06-08 00:29:29 +00002599bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002600 const CallEvent *Call,
2601 ProgramStateRef State,
2602 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002603 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002604 EscapingSymbol = nullptr;
2605
Jordan Rose2a833ca2014-01-15 17:25:15 +00002606 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002607 // TODO: If we want to be more optimistic here, we'll need to make sure that
2608 // regions escape to C++ containers. They seem to do that even now, but for
2609 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002610 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002611 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002612
Jordan Rose742920c2012-07-02 19:27:35 +00002613 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002614 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002615 // If it's not a framework call, or if it takes a callback, assume it
2616 // can free memory.
Anna Zaksfe1eca52015-10-27 20:19:45 +00002617 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002618 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002619
Jordan Rose613f3c02013-03-09 00:59:10 +00002620 // If it's a method we know about, handle it explicitly post-call.
2621 // This should happen before the "freeWhenDone" check below.
2622 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002623 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002624
Jordan Rose613f3c02013-03-09 00:59:10 +00002625 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2626 // about, we can't be sure that the object will use free() to deallocate the
2627 // memory, so we can't model it explicitly. The best we can do is use it to
2628 // decide whether the pointer escapes.
2629 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002630 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002631
Jordan Rose613f3c02013-03-09 00:59:10 +00002632 // If the first selector piece ends with "NoCopy", and there is no
2633 // "freeWhenDone" parameter set to zero, we know ownership is being
2634 // transferred. Again, though, we can't be sure that the object will use
2635 // free() to deallocate the memory, so we can't model it explicitly.
2636 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002637 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002638 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002639
Anna Zaks42908c72012-06-19 05:10:32 +00002640 // If the first selector starts with addPointer, insertPointer,
2641 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2642 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002643 // that the pointers get freed by following the container itself.
2644 if (FirstSlot.startswith("addPointer") ||
2645 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002646 FirstSlot.startswith("replacePointer") ||
2647 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002648 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002649 }
2650
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002651 // We should escape receiver on call to 'init'. This is especially relevant
2652 // to the receiver, as the corresponding symbol is usually not referenced
2653 // after the call.
2654 if (Msg->getMethodFamily() == OMF_init) {
2655 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2656 return true;
2657 }
Anna Zaks737926b2013-05-31 22:39:13 +00002658
Jordan Rose742920c2012-07-02 19:27:35 +00002659 // Otherwise, assume that the method does not free memory.
2660 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002661 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002662 }
2663
Jordan Rose742920c2012-07-02 19:27:35 +00002664 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002665 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002666 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002667 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002668
Jordan Rose742920c2012-07-02 19:27:35 +00002669 ASTContext &ASTC = State->getStateManager().getContext();
2670
2671 // If it's one of the allocation functions we can reason about, we model
2672 // its behavior explicitly.
2673 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002674 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002675
2676 // If it's not a system call, assume it frees memory.
2677 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002678 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002679
2680 // White list the system functions whose arguments escape.
2681 const IdentifierInfo *II = FD->getIdentifier();
2682 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002683 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002684 StringRef FName = II->getName();
2685
Jordan Rose742920c2012-07-02 19:27:35 +00002686 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002687 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002688 if (FName.endswith("NoCopy")) {
2689 // Look for the deallocator argument. We know that the memory ownership
2690 // is not transferred only if the deallocator argument is
2691 // 'kCFAllocatorNull'.
2692 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2693 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2694 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2695 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2696 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002697 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002698 }
2699 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002700 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002701 }
2702
Jordan Rose742920c2012-07-02 19:27:35 +00002703 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002704 // 'closefn' is specified (and if that function does free memory),
2705 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002706 // Currently, we do not inspect the 'closefn' function (PR12101).
2707 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002708 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002709 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002710
2711 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2712 // these leaks might be intentional when setting the buffer for stdio.
2713 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2714 if (FName == "setbuf" || FName =="setbuffer" ||
2715 FName == "setlinebuf" || FName == "setvbuf") {
2716 if (Call->getNumArgs() >= 1) {
2717 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2718 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2719 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2720 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002721 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002722 }
2723 }
2724
2725 // A bunch of other functions which either take ownership of a pointer or
2726 // wrap the result up in a struct or object, meaning it can be freed later.
2727 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2728 // but the Malloc checker cannot differentiate between them. The right way
2729 // of doing this would be to implement a pointer escapes callback.
2730 if (FName == "CGBitmapContextCreate" ||
2731 FName == "CGBitmapContextCreateWithData" ||
2732 FName == "CVPixelBufferCreateWithBytes" ||
2733 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2734 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002735 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002736 }
2737
Anna Zaks03f48332016-01-06 00:32:56 +00002738 if (FName == "postEvent" &&
2739 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2740 return true;
2741 }
2742
2743 if (FName == "postEvent" &&
2744 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2745 return true;
2746 }
2747
Artem Dergachev85c92112016-12-16 12:21:55 +00002748 if (FName == "connectImpl" &&
2749 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2750 return true;
2751 }
2752
Jordan Rose7ab01822012-07-02 19:27:51 +00002753 // Handle cases where we know a buffer's /address/ can escape.
2754 // Note that the above checks handle some special cases where we know that
2755 // even though the address escapes, it's still our responsibility to free the
2756 // buffer.
2757 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002758 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002759
2760 // Otherwise, assume that the function does not free memory.
2761 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002762 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002763}
2764
Anna Zaks333481b2013-03-28 23:15:29 +00002765static bool retTrue(const RefState *RS) {
2766 return true;
2767}
2768
2769static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2770 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2771 RS->getAllocationFamily() == AF_CXXNew);
2772}
2773
Anna Zaksdc154152012-12-20 00:38:25 +00002774ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2775 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002776 const CallEvent *Call,
2777 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002778 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2779}
2780
2781ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2782 const InvalidatedSymbols &Escaped,
2783 const CallEvent *Call,
2784 PointerEscapeKind Kind) const {
2785 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2786 &checkIfNewOrNewArrayFamily);
2787}
2788
2789ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2790 const InvalidatedSymbols &Escaped,
2791 const CallEvent *Call,
2792 PointerEscapeKind Kind,
2793 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002794 // If we know that the call does not free memory, or we want to process the
2795 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002796 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002797 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002798 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2799 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002800 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002801 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002802 }
Anna Zaks3d348342012-02-14 21:55:24 +00002803
Anna Zaksdc154152012-12-20 00:38:25 +00002804 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002805 E = Escaped.end();
2806 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002807 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002808
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002809 if (EscapingSymbol && EscapingSymbol != sym)
2810 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002811
Anna Zaks0d6989b2012-06-22 02:04:31 +00002812 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002813 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2814 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002815 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002816 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2817 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002818 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002819 }
Anna Zaks3d348342012-02-14 21:55:24 +00002820 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002821}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002822
Jordy Rosebf38f202012-03-18 07:43:35 +00002823static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2824 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002825 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2826 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002827
Jordan Rose0c153cb2012-11-02 01:54:06 +00002828 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002829 I != E; ++I) {
2830 SymbolRef sym = I.getKey();
2831 if (!currMap.lookup(sym))
2832 return sym;
2833 }
2834
Craig Topper0dbb7832014-05-27 02:45:47 +00002835 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002836}
2837
Artem Dergachevff1fc212018-03-21 00:49:47 +00002838static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) {
2839 if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
2840 StringRef N = II->getName();
2841 if (N.contains_lower("ptr") || N.contains_lower("pointer")) {
2842 if (N.contains_lower("ref") || N.contains_lower("cnt") ||
2843 N.contains_lower("intrusive") || N.contains_lower("shared")) {
2844 return true;
2845 }
2846 }
2847 }
2848 return false;
2849}
2850
David Blaikie0a0c2752017-01-05 17:26:53 +00002851std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2852 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2853 BugReport &BR) {
Artem Dergachev5337efc2018-02-27 21:19:33 +00002854 const Stmt *S = PathDiagnosticLocation::getStmt(N);
2855 if (!S)
2856 return nullptr;
2857
2858 const LocationContext *CurrentLC = N->getLocationContext();
2859
2860 // If we find an atomic fetch_add or fetch_sub within the destructor in which
2861 // the pointer was released (before the release), this is likely a destructor
2862 // of a shared pointer.
2863 // Because we don't model atomics, and also because we don't know that the
2864 // original reference count is positive, we should not report use-after-frees
2865 // on objects deleted in such destructors. This can probably be improved
2866 // through better shared pointer modeling.
2867 if (ReleaseDestructorLC) {
2868 if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
2869 AtomicExpr::AtomicOp Op = AE->getOp();
2870 if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
2871 Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
2872 if (ReleaseDestructorLC == CurrentLC ||
2873 ReleaseDestructorLC->isParentOf(CurrentLC)) {
2874 BR.markInvalid(getTag(), S);
2875 }
2876 }
2877 }
2878 }
2879
Jordy Rosebf38f202012-03-18 07:43:35 +00002880 ProgramStateRef state = N->getState();
2881 ProgramStateRef statePrev = PrevN->getState();
2882
2883 const RefState *RS = state->get<RegionState>(Sym);
2884 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002885 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002886 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002887
Jordan Rose681cce92012-07-10 22:07:42 +00002888 // FIXME: We will eventually need to handle non-statement-based events
2889 // (__attribute__((cleanup))).
2890
Anna Zaks2b5bb972012-02-09 06:25:51 +00002891 // Find out if this is an interesting point and what is the kind.
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002892 const char *Msg = nullptr;
2893 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002894 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002895 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002896 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002897 StackHint = new StackHintGeneratorForSymbol(Sym,
2898 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002899 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002900 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002901 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002902 "Returning; memory was released");
Artem Dergachev5337efc2018-02-27 21:19:33 +00002903
Artem Dergachevff1fc212018-03-21 00:49:47 +00002904 // See if we're releasing memory while inlining a destructor
2905 // (or one of its callees). This turns on various common
2906 // false positive suppressions.
2907 bool FoundAnyDestructor = false;
Artem Dergachev5337efc2018-02-27 21:19:33 +00002908 for (const LocationContext *LC = CurrentLC; LC; LC = LC->getParent()) {
Artem Dergachevff1fc212018-03-21 00:49:47 +00002909 if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
2910 if (isReferenceCountingPointerDestructor(DD)) {
2911 // This immediately looks like a reference-counting destructor.
2912 // We're bad at guessing the original reference count of the object,
2913 // so suppress the report for now.
2914 BR.markInvalid(getTag(), DD);
2915 } else if (!FoundAnyDestructor) {
2916 assert(!ReleaseDestructorLC &&
2917 "There can be only one release point!");
2918 // Suspect that it's a reference counting pointer destructor.
2919 // On one of the next nodes might find out that it has atomic
2920 // reference counting operations within it (see the code above),
2921 // and if so, we'd conclude that it likely is a reference counting
2922 // pointer destructor.
2923 ReleaseDestructorLC = LC->getCurrentStackFrame();
2924 // It is unlikely that releasing memory is delegated to a destructor
2925 // inside a destructor of a shared pointer, because it's fairly hard
2926 // to pass the information that the pointer indeed needs to be
2927 // released into it. So we're only interested in the innermost
2928 // destructor.
2929 FoundAnyDestructor = true;
2930 }
Artem Dergachev5337efc2018-02-27 21:19:33 +00002931 }
2932 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002933 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002934 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002935 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002936 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002937 Mode = ReallocationFailed;
2938 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002939 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002940 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002941
Jordy Rose21ff76e2012-03-24 03:15:09 +00002942 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2943 // Is it possible to fail two reallocs WITHOUT testing in between?
2944 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2945 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002946 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002947 FailedReallocSymbol = sym;
2948 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002949 }
2950
2951 // We are in a special mode if a reallocation failed later in the path.
2952 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002953 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002954
Jordy Rose21ff76e2012-03-24 03:15:09 +00002955 // Is this is the first appearance of the reallocated symbol?
2956 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002957 // We're at the reallocation point.
2958 Msg = "Attempt to reallocate memory";
2959 StackHint = new StackHintGeneratorForSymbol(Sym,
2960 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002961 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002962 Mode = Normal;
2963 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002964 }
2965
Anna Zaks2b5bb972012-02-09 06:25:51 +00002966 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002967 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002968 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002969
2970 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002971 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002972 N->getLocationContext());
David Blaikie0a0c2752017-01-05 17:26:53 +00002973 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002974}
2975
Anna Zaks263b7e02012-05-02 00:05:20 +00002976void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2977 const char *NL, const char *Sep) const {
2978
2979 RegionStateTy RS = State->get<RegionState>();
2980
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002981 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002982 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002983 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002984 const RefState *RefS = State->get<RegionState>(I.getKey());
2985 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002986 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002987 if (!CheckKind.hasValue())
2988 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002989
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002990 I.getKey()->dumpToStream(Out);
2991 Out << " : ";
2992 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002993 if (CheckKind.hasValue())
2994 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002995 Out << NL;
2996 }
2997 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002998}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002999
Reka Kovacs18775fc2018-06-09 13:03:49 +00003000namespace clang {
3001namespace ento {
3002namespace allocation_state {
3003
3004ProgramStateRef
3005markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
3006 AllocationFamily Family = AF_InternalBuffer;
3007 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3008}
3009
3010} // end namespace allocation_state
3011} // end namespace ento
3012} // end namespace clang
3013
Anna Zakse4cfcd42013-04-16 00:22:55 +00003014void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
3015 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003016 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00003017 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
3018 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003019 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
3020 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
3021 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00003022 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00003023 // checker.
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00003024 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003025 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Gabor Horvathb77bc6b2018-01-06 10:51:00 +00003026 // FIXME: This does not set the correct name, but without this workaround
3027 // no name will be set at all.
3028 checker->CheckNames[MallocChecker::CK_NewDeleteChecker] =
3029 mgr.getCurrentCheckName();
3030 }
Anna Zakse4cfcd42013-04-16 00:22:55 +00003031}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00003032
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003033#define REGISTER_CHECKER(name) \
3034 void ento::register##name(CheckerManager &mgr) { \
3035 registerCStringCheckerBasic(mgr); \
3036 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00003037 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
3038 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00003039 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
3040 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
3041 }
Anna Zakscd37bf42012-02-08 23:16:52 +00003042
Gabor Horvathe40c71c2015-03-04 17:59:34 +00003043REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00003044REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00003045REGISTER_CHECKER(MismatchedDeallocatorChecker)