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