blob: c95b2fd7f4bcb759302c2b40687b42c2c6fb0bcf [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"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000023#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000029#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000030#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000032#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000033#include <climits>
34
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000035using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000036using namespace ento;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000037
38namespace {
39
Anton Yartsev05789592013-03-28 17:05:19 +000040// Used to check correspondence between allocators and deallocators.
41enum AllocationFamily {
42 AF_None,
43 AF_Malloc,
44 AF_CXXNew,
Anna Zaksd79b8402014-10-03 21:48:59 +000045 AF_CXXNewArray,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +000046 AF_IfNameIndex,
47 AF_Alloca
Anton Yartsev05789592013-03-28 17:05:19 +000048};
49
Zhongxing Xu1239de12009-12-11 00:55:44 +000050class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000051 enum Kind { // Reference to allocated memory.
52 Allocated,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000053 // Reference to zero-allocated memory.
54 AllocatedOfSizeZero,
Anna Zaks9050ffd2012-06-20 20:57:46 +000055 // Reference to released/freed memory.
56 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000057 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000058 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000059 Relinquished,
60 // We are no longer guaranteed to have observed all manipulations
61 // of this pointer/memory. For example, it could have been
62 // passed as a parameter to an opaque function.
63 Escaped
64 };
Anton Yartsev05789592013-03-28 17:05:19 +000065
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000066 const Stmt *S;
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000067 unsigned K : 3; // Kind enum, but stored as a bitfield.
Ted Kremenek3a0678e2015-09-08 03:50:52 +000068 unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
Anton Yartsev05789592013-03-28 17:05:19 +000069 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000070
Ted Kremenek3a0678e2015-09-08 03:50:52 +000071 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000072 : S(s), K(k), Family(family) {
73 assert(family != AF_None);
74 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000075public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000076 bool isAllocated() const { return K == Allocated; }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000077 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000078 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000079 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000080 bool isEscaped() const { return K == Escaped; }
81 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000082 return (AllocationFamily)Family;
83 }
Anna Zaksd56c8792012-02-13 18:05:39 +000084 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000085
86 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000087 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000088 }
89
Anton Yartsev05789592013-03-28 17:05:19 +000090 static RefState getAllocated(unsigned family, const Stmt *s) {
91 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000092 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +000093 static RefState getAllocatedOfSizeZero(const RefState *RS) {
94 return RefState(AllocatedOfSizeZero, RS->getStmt(),
95 RS->getAllocationFamily());
96 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +000097 static RefState getReleased(unsigned family, const Stmt *s) {
Anton Yartsev05789592013-03-28 17:05:19 +000098 return RefState(Released, s, family);
99 }
100 static RefState getRelinquished(unsigned family, const Stmt *s) {
101 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +0000102 }
Anna Zaks93a21a82013-04-09 00:30:28 +0000103 static RefState getEscaped(const RefState *RS) {
104 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
105 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000106
107 void Profile(llvm::FoldingSetNodeID &ID) const {
108 ID.AddInteger(K);
109 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +0000110 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000111 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000112
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000113 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000114 switch (static_cast<Kind>(K)) {
115#define CASE(ID) case ID: OS << #ID; break;
116 CASE(Allocated)
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000117 CASE(AllocatedOfSizeZero)
Jordan Rose6adadb92014-01-23 03:59:01 +0000118 CASE(Released)
119 CASE(Relinquished)
120 CASE(Escaped)
121 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000122 }
123
Alp Tokeref6b0072014-01-04 13:47:14 +0000124 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000125};
126
Anna Zaks75cfbb62012-09-12 22:57:34 +0000127enum ReallocPairKind {
128 RPToBeFreedAfterFailure,
129 // The symbol has been freed when reallocation failed.
130 RPIsFreeOnFailure,
131 // The symbol does not need to be freed after reallocation fails.
132 RPDoNotTrackAfterFailure
133};
134
Anna Zaksfe6eb672012-08-24 02:28:20 +0000135/// \class ReallocPair
136/// \brief Stores information about the symbol being reallocated by a call to
137/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000138struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000139 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000140 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000141 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000142
Anna Zaks75cfbb62012-09-12 22:57:34 +0000143 ReallocPair(SymbolRef S, ReallocPairKind K) :
144 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000145 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000146 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000147 ID.AddPointer(ReallocatedSym);
148 }
149 bool operator==(const ReallocPair &X) const {
150 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000151 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000152 }
153};
154
Anna Zaksa043d0c2013-01-08 00:25:29 +0000155typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000156
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000157class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000158 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000159 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000160 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000161 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000162 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000163 check::PostStmt<CXXNewExpr>,
164 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000165 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000166 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000167 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000168 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000169{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000170public:
Craig Topper0dbb7832014-05-27 02:45:47 +0000171 MallocChecker()
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000172 : II_alloca(nullptr), II_malloc(nullptr), II_free(nullptr),
Anton Yartsevc38d7952015-03-03 22:58:46 +0000173 II_realloc(nullptr), II_calloc(nullptr), II_valloc(nullptr),
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000174 II_reallocf(nullptr), II_strndup(nullptr), II_strdup(nullptr),
Anton Yartsevc38d7952015-03-03 22:58:46 +0000175 II_kmalloc(nullptr), II_if_nameindex(nullptr),
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000176 II_if_freenameindex(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000177
178 /// In pessimistic mode, the checker assumes that it does not know which
179 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000180 enum CheckKind {
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000181 CK_MallocChecker,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000182 CK_NewDeleteChecker,
183 CK_NewDeleteLeaksChecker,
184 CK_MismatchedDeallocatorChecker,
185 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000186 };
187
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000188 enum class MemoryOperationKind {
Anna Zaksd79b8402014-10-03 21:48:59 +0000189 MOK_Allocate,
190 MOK_Free,
191 MOK_Any
192 };
193
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000194 DefaultBool IsOptimistic;
195
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000196 DefaultBool ChecksEnabled[CK_NumCheckKinds];
197 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000198
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000199 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000200 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000201 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
202 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000203 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000204 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000205 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000206 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000207 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000208 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000209 void checkLocation(SVal l, bool isLoad, const Stmt *S,
210 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000211
212 ProgramStateRef checkPointerEscape(ProgramStateRef State,
213 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000214 const CallEvent *Call,
215 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000216 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
217 const InvalidatedSymbols &Escaped,
218 const CallEvent *Call,
219 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000220
Anna Zaks263b7e02012-05-02 00:05:20 +0000221 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000222 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000223
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000224private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000225 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
226 mutable std::unique_ptr<BugType> BT_DoubleDelete;
227 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
228 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
229 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000230 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000231 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
232 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000233 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
Anton Yartsevc38d7952015-03-03 22:58:46 +0000234 mutable IdentifierInfo *II_alloca, *II_malloc, *II_free, *II_realloc,
235 *II_calloc, *II_valloc, *II_reallocf, *II_strndup,
236 *II_strdup, *II_kmalloc, *II_if_nameindex,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000237 *II_if_freenameindex;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000238 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000239
Anna Zaks3d348342012-02-14 21:55:24 +0000240 void initIdentifierInfo(ASTContext &C) const;
241
Anton Yartsev05789592013-03-28 17:05:19 +0000242 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000243 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000244
245 /// \brief Print names of allocators and deallocators.
246 ///
247 /// \returns true on success.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000248 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000249 const Expr *E) const;
250
251 /// \brief Print expected name of an allocator based on the deallocator's
252 /// family derived from the DeallocExpr.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000253 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000254 const Expr *DeallocExpr) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000255 /// \brief Print expected name of a deallocator based on the allocator's
Anton Yartsev05789592013-03-28 17:05:19 +0000256 /// family.
257 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
258
Jordan Rose613f3c02013-03-09 00:59:10 +0000259 ///@{
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000260 /// Check if this is one of the functions which can allocate/reallocate memory
Anna Zaks3d348342012-02-14 21:55:24 +0000261 /// pointed to by one of its arguments.
262 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000263 bool isCMemFunction(const FunctionDecl *FD,
264 ASTContext &C,
265 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000266 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000267 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000268 ///@}
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000269
270 /// \brief Perform a zero-allocation check.
271 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
272 const unsigned AllocationSizeArg,
273 ProgramStateRef State) const;
274
Richard Smith852e9ce2013-11-27 01:46:48 +0000275 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
276 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000277 const OwnershipAttr* Att,
278 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000279 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000280 const Expr *SizeEx, SVal Init,
281 ProgramStateRef State,
282 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000283 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000284 SVal SizeEx, SVal Init,
285 ProgramStateRef State,
286 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000287
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000288 // Check if this malloc() for special flags. At present that means M_ZERO or
289 // __GFP_ZERO (in which case, treat it like calloc).
290 llvm::Optional<ProgramStateRef>
291 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
292 const ProgramStateRef &State) const;
293
Anna Zaks40a7eb32012-02-22 19:24:52 +0000294 /// Update the RefState to reflect the new memory allocation.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000295 static ProgramStateRef
Anton Yartsev05789592013-03-28 17:05:19 +0000296 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
297 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000298
299 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000300 const OwnershipAttr* Att,
301 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000302 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000303 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000304 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000305 bool &ReleasedAllocated,
306 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000307 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
308 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000309 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000310 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000311 bool &ReleasedAllocated,
312 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000313
Anna Zaks40a7eb32012-02-22 19:24:52 +0000314 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000315 bool FreesMemOnFailure,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000316 ProgramStateRef State) const;
317 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
318 ProgramStateRef State);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000319
Anna Zaks46d01602012-05-18 01:16:10 +0000320 ///\brief Check if the memory associated with this symbol was released.
321 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
322
Anton Yartsev13df0362013-03-25 01:35:45 +0000323 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000324
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000325 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000326 const Stmt *S) const;
327
Jordan Rose656fdd52014-01-08 18:46:55 +0000328 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
329
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000330 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000331 /// "interesting" and should be modeled explicitly.
332 ///
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000333 /// \param [out] EscapingSymbol A function might not free memory in general,
Anna Zaks8ebeb642013-06-08 00:29:29 +0000334 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000335 /// returned and the single escaping symbol is returned through the out
336 /// parameter.
337 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000338 /// We assume that pointers do not escape through calls to system functions
339 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000340 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000341 ProgramStateRef State,
342 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000343
Anna Zaks333481b2013-03-28 23:15:29 +0000344 // Implementation of the checkPointerEscape callabcks.
345 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
346 const InvalidatedSymbols &Escaped,
347 const CallEvent *Call,
348 PointerEscapeKind Kind,
349 bool(*CheckRefState)(const RefState*)) const;
350
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000351 ///@{
352 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000353 /// Sets CheckKind to the kind of the checker responsible for this
354 /// family/call/symbol.
Anton Yartsev2487dd62015-03-10 22:24:21 +0000355 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
356 bool IsALeakCheck = false) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000357 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000358 const Stmt *AllocDeallocStmt,
359 bool IsALeakCheck = false) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000360 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000361 bool IsALeakCheck = false) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000362 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000363 static bool SummarizeValue(raw_ostream &os, SVal V);
364 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000365 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +0000366 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000367 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
368 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000369 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000370 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000371 SymbolRef Sym, bool OwnershipTransferred) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000372 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
373 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000374 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000375 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
376 SymbolRef Sym) const;
377 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000378 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000379
Jordan Rose656fdd52014-01-08 18:46:55 +0000380 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
381
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000382 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
383 SymbolRef Sym) const;
384
Anna Zaksdf901a42012-02-23 21:38:21 +0000385 /// Find the location of the allocation for Sym on the path leading to the
386 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000387 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
388 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000389
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000390 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
391
Anna Zaks2b5bb972012-02-09 06:25:51 +0000392 /// The bug visitor which allows us to print extra diagnostics along the
393 /// BugReport path. For example, showing the allocation site of the leaked
394 /// region.
David Blaikie6951e3e2015-08-13 22:58:37 +0000395 class MallocBugVisitor final
396 : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000397 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000398 enum NotificationMode {
399 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000400 ReallocationFailed
401 };
402
Anna Zaks2b5bb972012-02-09 06:25:51 +0000403 // The allocated region symbol tracked by the main analysis.
404 SymbolRef Sym;
405
Anna Zaks62cce9e2012-05-10 01:37:40 +0000406 // The mode we are in, i.e. what kind of diagnostics will be emitted.
407 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000408
Anna Zaks62cce9e2012-05-10 01:37:40 +0000409 // A symbol from when the primary region should have been reallocated.
410 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000411
Anna Zaks62cce9e2012-05-10 01:37:40 +0000412 bool IsLeak;
413
414 public:
415 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000416 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000417
Craig Topperfb6b25b2014-03-15 04:29:04 +0000418 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000419 static int X = 0;
420 ID.AddPointer(&X);
421 ID.AddPointer(Sym);
422 }
423
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000424 inline bool isAllocated(const RefState *S, const RefState *SPrev,
425 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000426 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000427 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000428 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
429 (!SPrev || !(SPrev->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000430 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000431 }
432
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000433 inline bool isReleased(const RefState *S, const RefState *SPrev,
434 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000435 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000436 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000437 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
438 }
439
Anna Zaks0d6989b2012-06-22 02:04:31 +0000440 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
441 const Stmt *Stmt) {
442 // Did not track -> relinquished. Other state (allocated) -> relinquished.
443 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
444 isa<ObjCPropertyRefExpr>(Stmt)) &&
445 (S && S->isRelinquished()) &&
446 (!SPrev || !SPrev->isRelinquished()));
447 }
448
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000449 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
450 const Stmt *Stmt) {
451 // If the expression is not a call, and the state change is
452 // released -> allocated, it must be the realloc return value
453 // check. If we have to handle more cases here, it might be cleaner just
454 // to track this extra bit in the state itself.
455 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000456 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
457 (SPrev && !(SPrev->isAllocated() ||
458 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000459 }
460
461 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
462 const ExplodedNode *PrevN,
463 BugReporterContext &BRC,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000464 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000465
David Blaikied15481c2014-08-29 18:18:43 +0000466 std::unique_ptr<PathDiagnosticPiece>
467 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
468 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000469 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000470 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000471
472 PathDiagnosticLocation L =
473 PathDiagnosticLocation::createEndOfPath(EndPathNode,
474 BRC.getSourceManager());
475 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000476 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
477 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000478 }
479
Anna Zakscba4f292012-03-16 23:24:20 +0000480 private:
481 class StackHintGeneratorForReallocationFailed
482 : public StackHintGeneratorForSymbol {
483 public:
484 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
485 : StackHintGeneratorForSymbol(S, M) {}
486
Craig Topperfb6b25b2014-03-15 04:29:04 +0000487 std::string getMessageForArg(const Expr *ArgE,
488 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000489 // Printed parameters start at 1, not 0.
490 ++ArgIndex;
491
Anna Zakscba4f292012-03-16 23:24:20 +0000492 SmallString<200> buf;
493 llvm::raw_svector_ostream os(buf);
494
Jordan Rosec102b352012-09-22 01:24:42 +0000495 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
496 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000497
498 return os.str();
499 }
500
Craig Topperfb6b25b2014-03-15 04:29:04 +0000501 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000502 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000503 }
504 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000505 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000506};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000507} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000508
Jordan Rose0c153cb2012-11-02 01:54:06 +0000509REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
510REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000511
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000512// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000513// the free function.
514REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
515
Anna Zaksbb1ef902012-02-11 21:02:35 +0000516namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000517class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000518 ProgramStateRef state;
519public:
520 StopTrackingCallback(ProgramStateRef st) : state(st) {}
521 ProgramStateRef getState() const { return state; }
522
Craig Topperfb6b25b2014-03-15 04:29:04 +0000523 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000524 state = state->remove<RegionState>(sym);
525 return true;
526 }
527};
528} // end anonymous namespace
529
Anna Zaks3d348342012-02-14 21:55:24 +0000530void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000531 if (II_malloc)
532 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000533 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000534 II_malloc = &Ctx.Idents.get("malloc");
535 II_free = &Ctx.Idents.get("free");
536 II_realloc = &Ctx.Idents.get("realloc");
537 II_reallocf = &Ctx.Idents.get("reallocf");
538 II_calloc = &Ctx.Idents.get("calloc");
539 II_valloc = &Ctx.Idents.get("valloc");
540 II_strdup = &Ctx.Idents.get("strdup");
541 II_strndup = &Ctx.Idents.get("strndup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000542 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000543 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
544 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000545}
546
Anna Zaks3d348342012-02-14 21:55:24 +0000547bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000548 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000549 return true;
550
Anna Zaksd79b8402014-10-03 21:48:59 +0000551 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000552 return true;
553
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000554 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
555 return true;
556
Anton Yartsev13df0362013-03-25 01:35:45 +0000557 if (isStandardNewDelete(FD, C))
558 return true;
559
Anna Zaks46d01602012-05-18 01:16:10 +0000560 return false;
561}
562
Anna Zaksd79b8402014-10-03 21:48:59 +0000563bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
564 ASTContext &C,
565 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000566 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000567 if (!FD)
568 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000569
Anna Zaksd79b8402014-10-03 21:48:59 +0000570 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
571 MemKind == MemoryOperationKind::MOK_Free);
572 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
573 MemKind == MemoryOperationKind::MOK_Allocate);
574
Jordan Rose6cd16c52012-07-10 23:13:01 +0000575 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000576 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000577 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000578
Anna Zaksd79b8402014-10-03 21:48:59 +0000579 if (Family == AF_Malloc && CheckFree) {
580 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
581 return true;
582 }
583
584 if (Family == AF_Malloc && CheckAlloc) {
585 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
586 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
587 FunI == II_strndup || FunI == II_kmalloc)
588 return true;
589 }
590
591 if (Family == AF_IfNameIndex && CheckFree) {
592 if (FunI == II_if_freenameindex)
593 return true;
594 }
595
596 if (Family == AF_IfNameIndex && CheckAlloc) {
597 if (FunI == II_if_nameindex)
598 return true;
599 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000600
601 if (Family == AF_Alloca && CheckAlloc) {
Anton Yartsevc38d7952015-03-03 22:58:46 +0000602 if (FunI == II_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000603 return true;
604 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000605 }
Anna Zaks3d348342012-02-14 21:55:24 +0000606
Anna Zaksd79b8402014-10-03 21:48:59 +0000607 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000608 return false;
609
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000610 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000611 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
612 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
613 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
614 if (CheckFree)
615 return true;
616 } else if (OwnKind == OwnershipAttr::Returns) {
617 if (CheckAlloc)
618 return true;
619 }
620 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000621 }
Anna Zaks3d348342012-02-14 21:55:24 +0000622
Anna Zaks3d348342012-02-14 21:55:24 +0000623 return false;
624}
625
Anton Yartsev8b662702013-03-28 16:10:38 +0000626// Tells if the callee is one of the following:
627// 1) A global non-placement new/delete operator function.
628// 2) A global placement operator function with the single placement argument
629// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000630bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
631 ASTContext &C) const {
632 if (!FD)
633 return false;
634
635 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000636 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000637 Kind != OO_Delete && Kind != OO_Array_Delete)
638 return false;
639
Anton Yartsev8b662702013-03-28 16:10:38 +0000640 // Skip all operator new/delete methods.
641 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000642 return false;
643
644 // Return true if tested operator is a standard placement nothrow operator.
645 if (FD->getNumParams() == 2) {
646 QualType T = FD->getParamDecl(1)->getType();
647 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
648 return II->getName().equals("nothrow_t");
649 }
650
651 // Skip placement operators.
652 if (FD->getNumParams() != 1 || FD->isVariadic())
653 return false;
654
655 // One of the standard new/new[]/delete/delete[] non-placement operators.
656 return true;
657}
658
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000659llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
660 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
661 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
662 //
663 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
664 //
665 // One of the possible flags is M_ZERO, which means 'give me back an
666 // allocation which is already zeroed', like calloc.
667
668 // 2-argument kmalloc(), as used in the Linux kernel:
669 //
670 // void *kmalloc(size_t size, gfp_t flags);
671 //
672 // Has the similar flag value __GFP_ZERO.
673
674 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
675 // code could be shared.
676
677 ASTContext &Ctx = C.getASTContext();
678 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
679
680 if (!KernelZeroFlagVal.hasValue()) {
681 if (OS == llvm::Triple::FreeBSD)
682 KernelZeroFlagVal = 0x0100;
683 else if (OS == llvm::Triple::NetBSD)
684 KernelZeroFlagVal = 0x0002;
685 else if (OS == llvm::Triple::OpenBSD)
686 KernelZeroFlagVal = 0x0008;
687 else if (OS == llvm::Triple::Linux)
688 // __GFP_ZERO
689 KernelZeroFlagVal = 0x8000;
690 else
691 // FIXME: We need a more general way of getting the M_ZERO value.
692 // See also: O_CREAT in UnixAPIChecker.cpp.
693
694 // Fall back to normal malloc behavior on platforms where we don't
695 // know M_ZERO.
696 return None;
697 }
698
699 // We treat the last argument as the flags argument, and callers fall-back to
700 // normal malloc on a None return. This works for the FreeBSD kernel malloc
701 // as well as Linux kmalloc.
702 if (CE->getNumArgs() < 2)
703 return None;
704
705 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
706 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
707 if (!V.getAs<NonLoc>()) {
708 // The case where 'V' can be a location can only be due to a bad header,
709 // so in this case bail out.
710 return None;
711 }
712
713 NonLoc Flags = V.castAs<NonLoc>();
714 NonLoc ZeroFlag = C.getSValBuilder()
715 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
716 .castAs<NonLoc>();
717 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
718 Flags, ZeroFlag,
719 FlagsEx->getType());
720 if (MaskedFlagsUC.isUnknownOrUndef())
721 return None;
722 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
723
724 // Check if maskedFlags is non-zero.
725 ProgramStateRef TrueState, FalseState;
726 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
727
728 // If M_ZERO is set, treat this like calloc (initialized).
729 if (TrueState && !FalseState) {
730 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
731 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
732 }
733
734 return None;
735}
736
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000737void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000738 if (C.wasInlined)
739 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000740
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000741 const FunctionDecl *FD = C.getCalleeDecl(CE);
742 if (!FD)
743 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000744
Anna Zaks40a7eb32012-02-22 19:24:52 +0000745 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000746 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000747
748 if (FD->getKind() == Decl::Function) {
749 initIdentifierInfo(C.getASTContext());
750 IdentifierInfo *FunI = FD->getIdentifier();
751
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000752 if (FunI == II_malloc) {
753 if (CE->getNumArgs() < 1)
754 return;
755 if (CE->getNumArgs() < 3) {
756 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000757 if (CE->getNumArgs() == 1)
758 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000759 } else if (CE->getNumArgs() == 3) {
760 llvm::Optional<ProgramStateRef> MaybeState =
761 performKernelMalloc(CE, C, State);
762 if (MaybeState.hasValue())
763 State = MaybeState.getValue();
764 else
765 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
766 }
767 } else if (FunI == II_kmalloc) {
768 llvm::Optional<ProgramStateRef> MaybeState =
769 performKernelMalloc(CE, C, State);
770 if (MaybeState.hasValue())
771 State = MaybeState.getValue();
772 else
773 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
774 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000775 if (CE->getNumArgs() < 1)
776 return;
777 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000778 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000779 } else if (FunI == II_realloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000780 State = ReallocMem(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000781 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000782 } else if (FunI == II_reallocf) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000783 State = ReallocMem(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000784 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000785 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000786 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000787 State = ProcessZeroAllocation(C, CE, 0, State);
788 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000789 } else if (FunI == II_free) {
790 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
791 } else if (FunI == II_strdup) {
792 State = MallocUpdateRefState(C, CE, State);
793 } else if (FunI == II_strndup) {
794 State = MallocUpdateRefState(C, CE, State);
Anton Yartsevc38d7952015-03-03 22:58:46 +0000795 } else if (FunI == II_alloca) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000796 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
797 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000798 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000799 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000800 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000801 // as distinct from new/new[]/delete/delete[] expressions that are
802 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000803 // CXXDeleteExpr.
804 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000805 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000806 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
807 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000808 State = ProcessZeroAllocation(C, CE, 0, State);
809 }
810 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000811 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
812 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000813 State = ProcessZeroAllocation(C, CE, 0, State);
814 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000815 else if (K == OO_Delete || K == OO_Array_Delete)
816 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
817 else
818 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000819 } else if (FunI == II_if_nameindex) {
820 // Should we model this differently? We can allocate a fixed number of
821 // elements with zeros in the last one.
822 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
823 AF_IfNameIndex);
824 } else if (FunI == II_if_freenameindex) {
825 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000826 }
827 }
828
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000829 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000830 // Check all the attributes, if there are any.
831 // There can be multiple of these attributes.
832 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000833 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
834 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000835 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000836 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000837 break;
838 case OwnershipAttr::Takes:
839 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000840 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000841 break;
842 }
843 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000844 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000845 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000846}
847
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000848// Performs a 0-sized allocations check.
849ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
850 const Expr *E,
851 const unsigned AllocationSizeArg,
852 ProgramStateRef State) const {
853 if (!State)
854 return nullptr;
855
856 const Expr *Arg = nullptr;
857
858 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
859 Arg = CE->getArg(AllocationSizeArg);
860 }
861 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
862 if (NE->isArray())
863 Arg = NE->getArraySize();
864 else
865 return State;
866 }
867 else
868 llvm_unreachable("not a CallExpr or CXXNewExpr");
869
870 assert(Arg);
871
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000872 Optional<DefinedSVal> DefArgVal =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000873 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
874
875 if (!DefArgVal)
876 return State;
877
878 // Check if the allocation size is 0.
879 ProgramStateRef TrueState, FalseState;
880 SValBuilder &SvalBuilder = C.getSValBuilder();
881 DefinedSVal Zero =
882 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
883
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000884 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000885 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
886
887 if (TrueState && !FalseState) {
888 SVal retVal = State->getSVal(E, C.getLocationContext());
889 SymbolRef Sym = retVal.getAsLocSymbol();
890 if (!Sym)
891 return State;
892
893 const RefState *RS = State->get<RegionState>(Sym);
894 if (!RS)
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000895 return State; // TODO: change to assert(RS); after realloc() will
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000896 // guarantee have a RegionState attached.
897
898 if (!RS->isAllocated())
899 return State;
900
901 return TrueState->set<RegionState>(Sym,
902 RefState::getAllocatedOfSizeZero(RS));
903 }
904
905 // Assume the value is non-zero going forward.
906 assert(FalseState);
907 return FalseState;
908}
909
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000910static QualType getDeepPointeeType(QualType T) {
911 QualType Result = T, PointeeType = T->getPointeeType();
912 while (!PointeeType.isNull()) {
913 Result = PointeeType;
914 PointeeType = PointeeType->getPointeeType();
915 }
916 return Result;
917}
918
919static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
920
921 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
922 if (!ConstructE)
923 return false;
924
925 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
926 return false;
927
928 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
929
930 // Iterate over the constructor parameters.
931 for (const auto *CtorParam : CtorD->params()) {
932
933 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
934 if (CtorParamPointeeT.isNull())
935 continue;
936
937 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
938
939 if (CtorParamPointeeT->getAsCXXRecordDecl())
940 return true;
941 }
942
943 return false;
944}
945
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000946void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
Anton Yartsev13df0362013-03-25 01:35:45 +0000947 CheckerContext &C) const {
948
949 if (NE->getNumPlacementArgs())
950 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
951 E = NE->placement_arg_end(); I != E; ++I)
952 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
953 checkUseAfterFree(Sym, C, *I);
954
Anton Yartsev13df0362013-03-25 01:35:45 +0000955 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
956 return;
957
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000958 ParentMap &PM = C.getLocationContext()->getParentMap();
959 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
960 return;
961
Anton Yartsev13df0362013-03-25 01:35:45 +0000962 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000963 // The return value from operator new is bound to a specified initialization
964 // value (if any) and we don't want to loose this value. So we call
965 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +0000966 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000967 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Anton Yartsev05789592013-03-28 17:05:19 +0000968 : AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000969 State = ProcessZeroAllocation(C, NE, 0, State);
Anton Yartsev13df0362013-03-25 01:35:45 +0000970 C.addTransition(State);
971}
972
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000973void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +0000974 CheckerContext &C) const {
975
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000976 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +0000977 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
978 checkUseAfterFree(Sym, C, DE->getArgument());
979
Anton Yartsev13df0362013-03-25 01:35:45 +0000980 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
981 return;
982
983 ProgramStateRef State = C.getState();
984 bool ReleasedAllocated;
985 State = FreeMemAux(C, DE->getArgument(), DE, State,
986 /*Hold*/false, ReleasedAllocated);
987
988 C.addTransition(State);
989}
990
Jordan Rose613f3c02013-03-09 00:59:10 +0000991static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
992 // If the first selector piece is one of the names below, assume that the
993 // object takes ownership of the memory, promising to eventually deallocate it
994 // with free().
995 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
996 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
997 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
998 if (FirstSlot == "dataWithBytesNoCopy" ||
999 FirstSlot == "initWithBytesNoCopy" ||
1000 FirstSlot == "initWithCharactersNoCopy")
1001 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001002
1003 return false;
1004}
1005
Jordan Rose613f3c02013-03-09 00:59:10 +00001006static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1007 Selector S = Call.getSelector();
1008
1009 // FIXME: We should not rely on fully-constrained symbols being folded.
1010 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1011 if (S.getNameForSlot(i).equals("freeWhenDone"))
1012 return !Call.getArgSVal(i).isZeroConstant();
1013
1014 return None;
1015}
1016
Anna Zaks67291b92012-11-13 03:18:01 +00001017void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1018 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001019 if (C.wasInlined)
1020 return;
1021
Jordan Rose613f3c02013-03-09 00:59:10 +00001022 if (!isKnownDeallocObjCMethodName(Call))
1023 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001024
Jordan Rose613f3c02013-03-09 00:59:10 +00001025 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1026 if (!*FreeWhenDone)
1027 return;
1028
1029 bool ReleasedAllocatedMemory;
1030 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1031 Call.getOriginExpr(), C.getState(),
1032 /*Hold=*/true, ReleasedAllocatedMemory,
1033 /*RetNullOnFailure=*/true);
1034
1035 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001036}
1037
Richard Smith852e9ce2013-11-27 01:46:48 +00001038ProgramStateRef
1039MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001040 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001041 ProgramStateRef State) const {
1042 if (!State)
1043 return nullptr;
1044
Richard Smith852e9ce2013-11-27 01:46:48 +00001045 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001046 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001047
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001048 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001049 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001050 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001051 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001052 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1053}
1054
1055ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1056 const CallExpr *CE,
1057 const Expr *SizeEx, SVal Init,
1058 ProgramStateRef State,
1059 AllocationFamily Family) {
1060 if (!State)
1061 return nullptr;
1062
1063 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1064 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001065}
1066
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001067ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001068 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001069 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001070 ProgramStateRef State,
1071 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001072 if (!State)
1073 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001074
Jordan Rosef69e65f2014-09-05 16:33:51 +00001075 // We expect the malloc functions to return a pointer.
1076 if (!Loc::isLocType(CE->getType()))
1077 return nullptr;
1078
Anna Zaks3563fde2012-06-07 03:57:32 +00001079 // Bind the return value to the symbolic value from the heap region.
1080 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1081 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001082 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001083 SValBuilder &svalBuilder = C.getSValBuilder();
1084 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001085 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1086 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001087 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001088
Jordy Rose674bd552010-07-04 00:00:41 +00001089 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +00001090 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001091
Jordy Rose674bd552010-07-04 00:00:41 +00001092 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001093 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001094 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001095 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001096 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001097 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001098 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001099 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001100 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001101 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001102 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001103
Anton Yartsev05789592013-03-28 17:05:19 +00001104 State = State->assume(extentMatchesSize, true);
1105 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001106 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001107
Anton Yartsev05789592013-03-28 17:05:19 +00001108 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001109}
1110
1111ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001112 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001113 ProgramStateRef State,
1114 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001115 if (!State)
1116 return nullptr;
1117
Anna Zaks40a7eb32012-02-22 19:24:52 +00001118 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001119 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001120
1121 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001122 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001123 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001124
Ted Kremenek90af9092010-12-02 07:49:45 +00001125 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001126 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001127
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001128 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001129 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001130}
1131
Anna Zaks40a7eb32012-02-22 19:24:52 +00001132ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1133 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001134 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001135 ProgramStateRef State) const {
1136 if (!State)
1137 return nullptr;
1138
Richard Smith852e9ce2013-11-27 01:46:48 +00001139 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001140 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001141
Anna Zaksfe6eb672012-08-24 02:28:20 +00001142 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001143
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001144 for (const auto &Arg : Att->args()) {
1145 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001146 Att->getOwnKind() == OwnershipAttr::Holds,
1147 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001148 if (StateI)
1149 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001150 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001151 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001152}
1153
Ted Kremenek49b1e382012-01-26 21:29:00 +00001154ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001155 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001156 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001157 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001158 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001159 bool &ReleasedAllocated,
1160 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001161 if (!State)
1162 return nullptr;
1163
Anna Zaksb508d292012-04-10 23:41:11 +00001164 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001165 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001166
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001167 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001168 ReleasedAllocated, ReturnsNullOnFailure);
1169}
1170
Anna Zaksa14c1d02012-11-13 19:47:40 +00001171/// Checks if the previous call to free on the given symbol failed - if free
1172/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001173static bool didPreviousFreeFail(ProgramStateRef State,
1174 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001175 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001176 if (Ret) {
1177 assert(*Ret && "We should not store the null return symbol");
1178 ConstraintManager &CMgr = State->getConstraintManager();
1179 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001180 RetStatusSymbol = *Ret;
1181 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001182 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001183 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001184}
1185
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001186AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001187 const Stmt *S) const {
1188 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001189 return AF_None;
1190
Anton Yartseve3377fb2013-04-04 23:46:29 +00001191 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001192 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001193
1194 if (!FD)
1195 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1196
Anton Yartsev05789592013-03-28 17:05:19 +00001197 ASTContext &Ctx = C.getASTContext();
1198
Anna Zaksd79b8402014-10-03 21:48:59 +00001199 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001200 return AF_Malloc;
1201
1202 if (isStandardNewDelete(FD, Ctx)) {
1203 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001204 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001205 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001206 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001207 return AF_CXXNewArray;
1208 }
1209
Anna Zaksd79b8402014-10-03 21:48:59 +00001210 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1211 return AF_IfNameIndex;
1212
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001213 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1214 return AF_Alloca;
1215
Anton Yartsev05789592013-03-28 17:05:19 +00001216 return AF_None;
1217 }
1218
Anton Yartseve3377fb2013-04-04 23:46:29 +00001219 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1220 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1221
1222 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001223 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1224
Anton Yartseve3377fb2013-04-04 23:46:29 +00001225 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001226 return AF_Malloc;
1227
1228 return AF_None;
1229}
1230
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001231bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001232 const Expr *E) const {
1233 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1234 // FIXME: This doesn't handle indirect calls.
1235 const FunctionDecl *FD = CE->getDirectCallee();
1236 if (!FD)
1237 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001238
Anton Yartsev05789592013-03-28 17:05:19 +00001239 os << *FD;
1240 if (!FD->isOverloadedOperator())
1241 os << "()";
1242 return true;
1243 }
1244
1245 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1246 if (Msg->isInstanceMessage())
1247 os << "-";
1248 else
1249 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001250 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001251 return true;
1252 }
1253
1254 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001255 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001256 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1257 << "'";
1258 return true;
1259 }
1260
1261 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001262 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001263 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1264 << "'";
1265 return true;
1266 }
1267
1268 return false;
1269}
1270
1271void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1272 const Expr *E) const {
1273 AllocationFamily Family = getAllocationFamily(C, E);
1274
1275 switch(Family) {
1276 case AF_Malloc: os << "malloc()"; return;
1277 case AF_CXXNew: os << "'new'"; return;
1278 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001279 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001280 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001281 case AF_None: llvm_unreachable("not a deallocation expression");
1282 }
1283}
1284
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001285void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001286 AllocationFamily Family) const {
1287 switch(Family) {
1288 case AF_Malloc: os << "free()"; return;
1289 case AF_CXXNew: os << "'delete'"; return;
1290 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001291 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001292 case AF_Alloca:
1293 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001294 }
1295}
1296
Anna Zaks0d6989b2012-06-22 02:04:31 +00001297ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1298 const Expr *ArgExpr,
1299 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001300 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001301 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001302 bool &ReleasedAllocated,
1303 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001304
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001305 if (!State)
1306 return nullptr;
1307
Anna Zaks67291b92012-11-13 03:18:01 +00001308 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001309 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001310 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001311 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001312
1313 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001314 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001315 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001316
Anna Zaksad01ef52012-02-14 00:26:13 +00001317 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001318 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001319 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001320 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001321 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001322
Jordy Rose3597b212010-06-07 19:32:37 +00001323 // Unknown values could easily be okay
1324 // Undefined values are handled elsewhere
1325 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001326 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001327
Jordy Rose3597b212010-06-07 19:32:37 +00001328 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001329
Jordy Rose3597b212010-06-07 19:32:37 +00001330 // Nonlocs can't be freed, of course.
1331 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1332 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001333 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001334 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001335 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001336
Jordy Rose3597b212010-06-07 19:32:37 +00001337 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001338
Jordy Rose3597b212010-06-07 19:32:37 +00001339 // Blocks might show up as heap data, but should not be free()d
1340 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001341 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001342 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001343 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001344
Jordy Rose3597b212010-06-07 19:32:37 +00001345 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001346
1347 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001348 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001349 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1350 // FIXME: at the time this code was written, malloc() regions were
1351 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1352 // This means that there isn't actually anything from HeapSpaceRegion
1353 // that should be freed, even though we allow it here.
1354 // Of course, free() can work on memory allocated outside the current
1355 // function, so UnknownSpaceRegion is always a possibility.
1356 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001357
1358 if (isa<AllocaRegion>(R))
1359 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1360 else
1361 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1362
Craig Topper0dbb7832014-05-27 02:45:47 +00001363 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001364 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001365
1366 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001367 // Various cases could lead to non-symbol values here.
1368 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001369 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001370 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001371
Anna Zaksc89ad072013-02-07 23:05:47 +00001372 SymbolRef SymBase = SrBase->getSymbol();
1373 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001374 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001375
Anton Yartseve3377fb2013-04-04 23:46:29 +00001376 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001377
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001378 // Memory returned by alloca() shouldn't be freed.
1379 if (RsBase->getAllocationFamily() == AF_Alloca) {
1380 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1381 return nullptr;
1382 }
1383
Anna Zaks93a21a82013-04-09 00:30:28 +00001384 // Check for double free first.
1385 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001386 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1387 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1388 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001389 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001390
Anna Zaks93a21a82013-04-09 00:30:28 +00001391 // If the pointer is allocated or escaped, but we are now trying to free it,
1392 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001393 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001394 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001395
1396 // Check if an expected deallocation function matches the real one.
1397 bool DeallocMatchesAlloc =
1398 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1399 if (!DeallocMatchesAlloc) {
1400 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001401 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001402 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001403 }
1404
1405 // Check if the memory location being freed is the actual location
1406 // allocated, or an offset.
1407 RegionOffset Offset = R->getAsOffset();
1408 if (Offset.isValid() &&
1409 !Offset.hasSymbolicOffset() &&
1410 Offset.getOffset() != 0) {
1411 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001412 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001413 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001414 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001415 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001416 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001417 }
1418
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001419 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001420 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001421
Anna Zaksa14c1d02012-11-13 19:47:40 +00001422 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001423 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001424
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001425 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001426 // failed.
1427 if (ReturnsNullOnFailure) {
1428 SVal RetVal = C.getSVal(ParentExpr);
1429 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1430 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001431 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1432 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001433 }
1434 }
1435
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001436 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1437 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001438 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001439 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001440 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001441 RefState::getRelinquished(Family,
1442 ParentExpr));
1443
1444 return State->set<RegionState>(SymBase,
1445 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001446}
1447
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001448Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001449MallocChecker::getCheckIfTracked(AllocationFamily Family,
1450 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001451 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001452 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001453 case AF_Alloca:
1454 case AF_IfNameIndex: {
1455 if (ChecksEnabled[CK_MallocChecker])
1456 return CK_MallocChecker;
1457
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001458 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001459 }
1460 case AF_CXXNew:
1461 case AF_CXXNewArray: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001462 if (IsALeakCheck) {
1463 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1464 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001465 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001466 else {
1467 if (ChecksEnabled[CK_NewDeleteChecker])
1468 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001469 }
1470 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001471 }
1472 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001473 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001474 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001475 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001476 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001477}
1478
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001479Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001480MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001481 const Stmt *AllocDeallocStmt,
1482 bool IsALeakCheck) const {
1483 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1484 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001485}
1486
1487Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001488MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1489 bool IsALeakCheck) const {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001490 const RefState *RS = C.getState()->get<RegionState>(Sym);
1491 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001492 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001493}
1494
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001495bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001496 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001497 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001498 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001499 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001500 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001501 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001502 else
1503 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001504
Jordy Rose3597b212010-06-07 19:32:37 +00001505 return true;
1506}
1507
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001508bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001509 const MemRegion *MR) {
1510 switch (MR->getKind()) {
1511 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001512 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001513 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001514 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001515 else
1516 os << "the address of a function";
1517 return true;
1518 }
1519 case MemRegion::BlockTextRegionKind:
1520 os << "block text";
1521 return true;
1522 case MemRegion::BlockDataRegionKind:
1523 // FIXME: where the block came from?
1524 os << "a block";
1525 return true;
1526 default: {
1527 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001528
Anna Zaks8158ef02012-01-04 23:54:01 +00001529 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001530 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1531 const VarDecl *VD;
1532 if (VR)
1533 VD = VR->getDecl();
1534 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001535 VD = nullptr;
1536
Jordy Rose3597b212010-06-07 19:32:37 +00001537 if (VD)
1538 os << "the address of the local variable '" << VD->getName() << "'";
1539 else
1540 os << "the address of a local stack variable";
1541 return true;
1542 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001543
1544 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001545 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1546 const VarDecl *VD;
1547 if (VR)
1548 VD = VR->getDecl();
1549 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001550 VD = nullptr;
1551
Jordy Rose3597b212010-06-07 19:32:37 +00001552 if (VD)
1553 os << "the address of the parameter '" << VD->getName() << "'";
1554 else
1555 os << "the address of a parameter";
1556 return true;
1557 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001558
1559 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001560 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1561 const VarDecl *VD;
1562 if (VR)
1563 VD = VR->getDecl();
1564 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001565 VD = nullptr;
1566
Jordy Rose3597b212010-06-07 19:32:37 +00001567 if (VD) {
1568 if (VD->isStaticLocal())
1569 os << "the address of the static variable '" << VD->getName() << "'";
1570 else
1571 os << "the address of the global variable '" << VD->getName() << "'";
1572 } else
1573 os << "the address of a global variable";
1574 return true;
1575 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001576
1577 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001578 }
1579 }
1580}
1581
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001582void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1583 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001584 const Expr *DeallocExpr) const {
1585
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001586 if (!ChecksEnabled[CK_MallocChecker] &&
1587 !ChecksEnabled[CK_NewDeleteChecker])
1588 return;
1589
1590 Optional<MallocChecker::CheckKind> CheckKind =
1591 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001592 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001593 return;
1594
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001595 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001596 if (!BT_BadFree[*CheckKind])
1597 BT_BadFree[*CheckKind].reset(
1598 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1599
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001600 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001601 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001602
Jordy Rose3597b212010-06-07 19:32:37 +00001603 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001604 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1605 MR = ER->getSuperRegion();
1606
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001607 os << "Argument to ";
1608 if (!printAllocDeallocName(os, C, DeallocExpr))
1609 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001610
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001611 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001612 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001613 : SummarizeValue(os, ArgVal);
1614 if (Summarized)
1615 os << ", which is not memory allocated by ";
1616 else
1617 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001618
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001619 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001620
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001621 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001622 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001623 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001624 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001625 }
1626}
1627
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001628void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001629 SourceRange Range) const {
1630
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001631 Optional<MallocChecker::CheckKind> CheckKind;
1632
1633 if (ChecksEnabled[CK_MallocChecker])
1634 CheckKind = CK_MallocChecker;
1635 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1636 CheckKind = CK_MismatchedDeallocatorChecker;
1637 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001638 return;
1639
1640 if (ExplodedNode *N = C.generateSink()) {
1641 if (!BT_FreeAlloca[*CheckKind])
1642 BT_FreeAlloca[*CheckKind].reset(
1643 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1644
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001645 auto R = llvm::make_unique<BugReport>(
1646 *BT_FreeAlloca[*CheckKind],
1647 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001648 R->markInteresting(ArgVal.getAsRegion());
1649 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001650 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001651 }
1652}
1653
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001654void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001655 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001656 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001657 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001658 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001659 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001660
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001661 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001662 return;
1663
1664 if (ExplodedNode *N = C.generateSink()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001665 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001666 BT_MismatchedDealloc.reset(
1667 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1668 "Bad deallocator", "Memory Error"));
1669
Anton Yartsev05789592013-03-28 17:05:19 +00001670 SmallString<100> buf;
1671 llvm::raw_svector_ostream os(buf);
1672
1673 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1674 SmallString<20> AllocBuf;
1675 llvm::raw_svector_ostream AllocOs(AllocBuf);
1676 SmallString<20> DeallocBuf;
1677 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1678
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001679 if (OwnershipTransferred) {
1680 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1681 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001682 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001683 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001684
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001685 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001686
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001687 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1688 os << " allocated by " << AllocOs.str();
1689 } else {
1690 os << "Memory";
1691 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1692 os << " allocated by " << AllocOs.str();
1693
1694 os << " should be deallocated by ";
1695 printExpectedDeallocName(os, RS->getAllocationFamily());
1696
1697 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1698 os << ", not " << DeallocOs.str();
1699 }
Anton Yartsev05789592013-03-28 17:05:19 +00001700
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001701 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001702 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001703 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001704 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001705 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001706 }
1707}
1708
Anna Zaksc89ad072013-02-07 23:05:47 +00001709void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001710 SourceRange Range, const Expr *DeallocExpr,
1711 const Expr *AllocExpr) const {
1712
Anton Yartsev05789592013-03-28 17:05:19 +00001713
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001714 if (!ChecksEnabled[CK_MallocChecker] &&
1715 !ChecksEnabled[CK_NewDeleteChecker])
1716 return;
1717
1718 Optional<MallocChecker::CheckKind> CheckKind =
1719 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001720 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001721 return;
1722
Anna Zaksc89ad072013-02-07 23:05:47 +00001723 ExplodedNode *N = C.generateSink();
Craig Topper0dbb7832014-05-27 02:45:47 +00001724 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001725 return;
1726
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001727 if (!BT_OffsetFree[*CheckKind])
1728 BT_OffsetFree[*CheckKind].reset(
1729 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001730
1731 SmallString<100> buf;
1732 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001733 SmallString<20> AllocNameBuf;
1734 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001735
1736 const MemRegion *MR = ArgVal.getAsRegion();
1737 assert(MR && "Only MemRegion based symbols can have offset free errors");
1738
1739 RegionOffset Offset = MR->getAsOffset();
1740 assert((Offset.isValid() &&
1741 !Offset.hasSymbolicOffset() &&
1742 Offset.getOffset() != 0) &&
1743 "Only symbols with a valid offset can have offset free errors");
1744
1745 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1746
Anton Yartsev05789592013-03-28 17:05:19 +00001747 os << "Argument to ";
1748 if (!printAllocDeallocName(os, C, DeallocExpr))
1749 os << "deallocator";
1750 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001751 << offsetBytes
1752 << " "
1753 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001754 << " from the start of ";
1755 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1756 os << "memory allocated by " << AllocNameOs.str();
1757 else
1758 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001759
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001760 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001761 R->markInteresting(MR->getBaseRegion());
1762 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001763 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001764}
1765
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001766void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1767 SymbolRef Sym) const {
1768
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001769 if (!ChecksEnabled[CK_MallocChecker] &&
1770 !ChecksEnabled[CK_NewDeleteChecker])
1771 return;
1772
1773 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001774 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001775 return;
1776
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001777 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001778 if (!BT_UseFree[*CheckKind])
1779 BT_UseFree[*CheckKind].reset(new BugType(
1780 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001781
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001782 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1783 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001784
1785 R->markInteresting(Sym);
1786 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001787 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001788 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001789 }
1790}
1791
1792void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001793 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001794 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001795
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001796 if (!ChecksEnabled[CK_MallocChecker] &&
1797 !ChecksEnabled[CK_NewDeleteChecker])
1798 return;
1799
1800 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001801 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001802 return;
1803
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001804 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001805 if (!BT_DoubleFree[*CheckKind])
1806 BT_DoubleFree[*CheckKind].reset(
1807 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001808
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001809 auto R = llvm::make_unique<BugReport>(
1810 *BT_DoubleFree[*CheckKind],
1811 (Released ? "Attempt to free released memory"
1812 : "Attempt to free non-owned memory"),
1813 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001814 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001815 R->markInteresting(Sym);
1816 if (PrevSym)
1817 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001818 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001819 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001820 }
1821}
1822
Jordan Rose656fdd52014-01-08 18:46:55 +00001823void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1824
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001825 if (!ChecksEnabled[CK_NewDeleteChecker])
1826 return;
1827
1828 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001829 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001830 return;
1831
1832 if (ExplodedNode *N = C.generateSink()) {
1833 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001834 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1835 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001836
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001837 auto R = llvm::make_unique<BugReport>(
1838 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00001839
1840 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001841 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001842 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00001843 }
1844}
1845
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001846void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1847 SourceRange Range,
1848 SymbolRef Sym) const {
1849
1850 if (!ChecksEnabled[CK_MallocChecker] &&
1851 !ChecksEnabled[CK_NewDeleteChecker])
1852 return;
1853
1854 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1855
1856 if (!CheckKind.hasValue())
1857 return;
1858
1859 if (ExplodedNode *N = C.generateSink()) {
1860 if (!BT_UseZerroAllocated[*CheckKind])
1861 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
1862 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
1863
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001864 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
1865 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001866
1867 R->addRange(Range);
1868 if (Sym) {
1869 R->markInteresting(Sym);
1870 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1871 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001872 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001873 }
1874}
1875
Anna Zaks40a7eb32012-02-22 19:24:52 +00001876ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1877 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001878 bool FreesOnFail,
1879 ProgramStateRef State) const {
1880 if (!State)
1881 return nullptr;
1882
Anna Zaksb508d292012-04-10 23:41:11 +00001883 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001884 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001885
Ted Kremenek90af9092010-12-02 07:49:45 +00001886 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001887 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001888 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001889 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001890 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001891 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001892
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001893 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001894
Ted Kremenek90af9092010-12-02 07:49:45 +00001895 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001896 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001897
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001898 // Get the size argument. If there is no size arg then give up.
1899 const Expr *Arg1 = CE->getArg(1);
1900 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00001901 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001902
1903 // Get the value of the size argument.
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001904 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001905 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001906 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001907 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001908
1909 // Compare the size argument to 0.
1910 DefinedOrUnknownSVal SizeZero =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001911 svalBuilder.evalEQ(State, Arg1Val,
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001912 svalBuilder.makeIntValWithPtrWidth(0, false));
1913
Anna Zaksd56c8792012-02-13 18:05:39 +00001914 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001915 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001916 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001917 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001918 // We only assume exceptional states if they are definitely true; if the
1919 // state is under-constrained, assume regular realloc behavior.
1920 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1921 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1922
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001923 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001924 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001925 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001926 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001927 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001928 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001929 }
1930
Anna Zaksd56c8792012-02-13 18:05:39 +00001931 if (PrtIsNull && SizeIsZero)
Craig Topper0dbb7832014-05-27 02:45:47 +00001932 return nullptr;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001933
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001934 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001935 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001936 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001937 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001938 SymbolRef ToPtr = RetVal.getAsSymbol();
1939 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00001940 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00001941
Anna Zaksfe6eb672012-08-24 02:28:20 +00001942 bool ReleasedAllocated = false;
1943
Anna Zaksd56c8792012-02-13 18:05:39 +00001944 // If the size is 0, free the memory.
1945 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001946 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1947 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001948 // The semantics of the return value are:
1949 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001950 // to free() is returned. We just free the input pointer and do not add
1951 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001952 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001953 }
1954
1955 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001956 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001957 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00001958
Anna Zaksd56c8792012-02-13 18:05:39 +00001959 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1960 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001961 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001962 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001963
Anna Zaks75cfbb62012-09-12 22:57:34 +00001964 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1965 if (FreesOnFail)
1966 Kind = RPIsFreeOnFailure;
1967 else if (!ReleasedAllocated)
1968 Kind = RPDoNotTrackAfterFailure;
1969
Anna Zaksfe6eb672012-08-24 02:28:20 +00001970 // Record the info about the reallocated symbol so that we could properly
1971 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001972 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001973 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001974 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001975 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001976 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001977 }
Craig Topper0dbb7832014-05-27 02:45:47 +00001978 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001979}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001980
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001981ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001982 ProgramStateRef State) {
1983 if (!State)
1984 return nullptr;
1985
Anna Zaksb508d292012-04-10 23:41:11 +00001986 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001987 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001988
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001989 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001990 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001991 SVal count = State->getSVal(CE->getArg(0), LCtx);
1992 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1993 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001994 svalBuilder.getContext().getSizeType());
Ted Kremenek90af9092010-12-02 07:49:45 +00001995 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001996
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001997 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001998}
1999
Anna Zaksfc2e1532012-03-21 19:45:08 +00002000LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002001MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2002 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002003 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002004 // Walk the ExplodedGraph backwards and find the first node that referred to
2005 // the tracked symbol.
2006 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002007 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002008
2009 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002010 ProgramStateRef State = N->getState();
2011 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002012 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002013
2014 // Find the most recent expression bound to the symbol in the current
2015 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002016 if (!ReferenceRegion) {
2017 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2018 SVal Val = State->getSVal(MR);
2019 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002020 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002021 // Do not show local variables belonging to a function other than
2022 // where the error is reported.
2023 if (!VR ||
2024 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2025 ReferenceRegion = MR;
2026 }
2027 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002028 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002029
Anna Zaks486a0ff2015-02-05 01:02:53 +00002030 // Allocation node, is the last node in the current or parent context in
2031 // which the symbol was tracked.
2032 const LocationContext *NContext = N->getLocationContext();
2033 if (NContext == LeakContext ||
2034 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002035 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002036 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002037 }
2038
Anna Zaksa043d0c2013-01-08 00:25:29 +00002039 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002040}
2041
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002042void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2043 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002044
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002045 if (!ChecksEnabled[CK_MallocChecker] &&
2046 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002047 return;
2048
Anton Yartsev9907fc92015-03-04 23:18:21 +00002049 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002050 assert(RS && "cannot leak an untracked symbol");
2051 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002052
2053 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002054 return;
2055
Anton Yartsev2487dd62015-03-10 22:24:21 +00002056 Optional<MallocChecker::CheckKind>
2057 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002058
Anton Yartsev2487dd62015-03-10 22:24:21 +00002059 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002060 return;
2061
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002062 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002063 if (!BT_Leak[*CheckKind]) {
2064 BT_Leak[*CheckKind].reset(
2065 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002066 // Leaks should not be reported if they are post-dominated by a sink:
2067 // (1) Sinks are higher importance bugs.
2068 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2069 // with __noreturn functions such as assert() or exit(). We choose not
2070 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002071 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002072 }
2073
Anna Zaksdf901a42012-02-23 21:38:21 +00002074 // Most bug reports are cached at the location where they occurred.
2075 // With leaks, we want to unique them by the location where they were
2076 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002077 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002078 const ExplodedNode *AllocNode = nullptr;
2079 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002080 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002081
Anna Zaksa043d0c2013-01-08 00:25:29 +00002082 ProgramPoint P = AllocNode->getLocation();
Craig Topper0dbb7832014-05-27 02:45:47 +00002083 const Stmt *AllocationStmt = nullptr;
David Blaikie87396b92013-02-21 22:23:56 +00002084 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00002085 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002086 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00002087 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00002088 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002089 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2090 C.getSourceManager(),
2091 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002092
Anna Zaksfc2e1532012-03-21 19:45:08 +00002093 SmallString<200> buf;
2094 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002095 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002096 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002097 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002098 } else {
2099 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002100 }
2101
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002102 auto R = llvm::make_unique<BugReport>(
2103 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2104 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002105 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002106 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002107 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002108}
2109
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002110void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2111 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002112{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002113 if (!SymReaper.hasDeadSymbols())
2114 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002115
Ted Kremenek49b1e382012-01-26 21:29:00 +00002116 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002117 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002118 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002119
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002120 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002121 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2122 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002123 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002124 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002125 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002126 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002127
Zhongxing Xuc7460962009-11-13 07:48:11 +00002128 }
2129 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002130
Anna Zaksd56c8792012-02-13 18:05:39 +00002131 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002132 ReallocPairsTy RP = state->get<ReallocPairs>();
2133 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002134 if (SymReaper.isDead(I->first) ||
2135 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002136 state = state->remove<ReallocPairs>(I->first);
2137 }
2138 }
2139
Anna Zaks67291b92012-11-13 03:18:01 +00002140 // Cleanup the FreeReturnValue Map.
2141 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2142 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2143 if (SymReaper.isDead(I->first) ||
2144 SymReaper.isDead(I->second)) {
2145 state = state->remove<FreeReturnValue>(I->first);
2146 }
2147 }
2148
Anna Zaksdf901a42012-02-23 21:38:21 +00002149 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002150 ExplodedNode *N = C.getPredecessor();
2151 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002152 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002153 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper2341c0d2013-07-04 03:08:24 +00002154 for (SmallVectorImpl<SymbolRef>::iterator
2155 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002156 reportLeak(*I, N, C);
Anna Zaks78edc2f2012-02-09 06:48:19 +00002157 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002158 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002159
Anna Zaksdf901a42012-02-23 21:38:21 +00002160 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002161}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002162
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002163void MallocChecker::checkPreCall(const CallEvent &Call,
2164 CheckerContext &C) const {
2165
Jordan Rose656fdd52014-01-08 18:46:55 +00002166 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2167 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2168 if (!Sym || checkDoubleDelete(Sym, C))
2169 return;
2170 }
2171
Anna Zaks46d01602012-05-18 01:16:10 +00002172 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002173 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2174 const FunctionDecl *FD = FC->getDecl();
2175 if (!FD)
2176 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002177
Anna Zaksd79b8402014-10-03 21:48:59 +00002178 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002179 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002180 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2181 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2182 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002183 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002184
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002185 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002186 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002187 return;
2188 }
2189
2190 // Check if the callee of a method is deleted.
2191 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2192 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2193 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2194 return;
2195 }
2196
2197 // Check arguments for being used after free.
2198 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2199 SVal ArgSVal = Call.getArgSVal(I);
2200 if (ArgSVal.getAs<Loc>()) {
2201 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002202 if (!Sym)
2203 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002204 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002205 return;
2206 }
2207 }
2208}
2209
Anna Zaksa1b227b2012-02-08 23:16:56 +00002210void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2211 const Expr *E = S->getRetValue();
2212 if (!E)
2213 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002214
2215 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002216 ProgramStateRef State = C.getState();
2217 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002218 SymbolRef Sym = RetVal.getAsSymbol();
2219 if (!Sym)
2220 // If we are returning a field of the allocated struct or an array element,
2221 // the callee could still free the memory.
2222 // TODO: This logic should be a part of generic symbol escape callback.
2223 if (const MemRegion *MR = RetVal.getAsRegion())
2224 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2225 if (const SymbolicRegion *BMR =
2226 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2227 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002228
Anna Zaks3aa52252012-02-11 21:44:39 +00002229 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002230 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002231 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002232}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002233
Anna Zaks9fe80982012-03-22 00:57:20 +00002234// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002235// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002236// needed.
2237void MallocChecker::checkPostStmt(const BlockExpr *BE,
2238 CheckerContext &C) const {
2239
2240 // Scan the BlockDecRefExprs for any object the retain count checker
2241 // may be tracking.
2242 if (!BE->getBlockDecl()->hasCaptures())
2243 return;
2244
2245 ProgramStateRef state = C.getState();
2246 const BlockDataRegion *R =
2247 cast<BlockDataRegion>(state->getSVal(BE,
2248 C.getLocationContext()).getAsRegion());
2249
2250 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2251 E = R->referenced_vars_end();
2252
2253 if (I == E)
2254 return;
2255
2256 SmallVector<const MemRegion*, 10> Regions;
2257 const LocationContext *LC = C.getLocationContext();
2258 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2259
2260 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002261 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002262 if (VR->getSuperRegion() == R) {
2263 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2264 }
2265 Regions.push_back(VR);
2266 }
2267
2268 state =
2269 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2270 Regions.data() + Regions.size()).getState();
2271 C.addTransition(state);
2272}
2273
Anna Zaks46d01602012-05-18 01:16:10 +00002274bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002275 assert(Sym);
2276 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002277 return (RS && RS->isReleased());
2278}
2279
2280bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2281 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002282
Jordan Rose656fdd52014-01-08 18:46:55 +00002283 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002284 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2285 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002286 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002287
Anna Zaksa1b227b2012-02-08 23:16:56 +00002288 return false;
2289}
2290
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002291void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2292 const Stmt *S) const {
2293 assert(Sym);
2294 const RefState *RS = C.getState()->get<RegionState>(Sym);
2295
2296 if (RS && RS->isAllocatedOfSizeZero())
2297 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2298}
2299
Jordan Rose656fdd52014-01-08 18:46:55 +00002300bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2301
2302 if (isReleased(Sym, C)) {
2303 ReportDoubleDelete(C, Sym);
2304 return true;
2305 }
2306 return false;
2307}
2308
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002309// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002310void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2311 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002312 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002313 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002314 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002315 checkUseZeroAllocated(Sym, C, S);
2316 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002317}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002318
Anna Zaksbb1ef902012-02-11 21:02:35 +00002319// If a symbolic region is assumed to NULL (or another constant), stop tracking
2320// it - assuming that allocation failed on this path.
2321ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2322 SVal Cond,
2323 bool Assumption) const {
2324 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002325 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002326 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002327 ConstraintManager &CMgr = state->getConstraintManager();
2328 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2329 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002330 state = state->remove<RegionState>(I.getKey());
2331 }
2332
Anna Zaksd56c8792012-02-13 18:05:39 +00002333 // Realloc returns 0 when reallocation fails, which means that we should
2334 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002335 ReallocPairsTy RP = state->get<ReallocPairs>();
2336 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002337 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002338 ConstraintManager &CMgr = state->getConstraintManager();
2339 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002340 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002341 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002342
Anna Zaks75cfbb62012-09-12 22:57:34 +00002343 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2344 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2345 if (RS->isReleased()) {
2346 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002347 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002348 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002349 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2350 state = state->remove<RegionState>(ReallocSym);
2351 else
2352 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002353 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002354 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002355 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002356 }
2357
Anna Zaksbb1ef902012-02-11 21:02:35 +00002358 return state;
2359}
2360
Anna Zaks8ebeb642013-06-08 00:29:29 +00002361bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002362 const CallEvent *Call,
2363 ProgramStateRef State,
2364 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002365 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002366 EscapingSymbol = nullptr;
2367
Jordan Rose2a833ca2014-01-15 17:25:15 +00002368 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002369 // TODO: If we want to be more optimistic here, we'll need to make sure that
2370 // regions escape to C++ containers. They seem to do that even now, but for
2371 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002372 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002373 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002374
Jordan Rose742920c2012-07-02 19:27:35 +00002375 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002376 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002377 // If it's not a framework call, or if it takes a callback, assume it
2378 // can free memory.
2379 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002380 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002381
Jordan Rose613f3c02013-03-09 00:59:10 +00002382 // If it's a method we know about, handle it explicitly post-call.
2383 // This should happen before the "freeWhenDone" check below.
2384 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002385 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002386
Jordan Rose613f3c02013-03-09 00:59:10 +00002387 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2388 // about, we can't be sure that the object will use free() to deallocate the
2389 // memory, so we can't model it explicitly. The best we can do is use it to
2390 // decide whether the pointer escapes.
2391 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002392 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002393
Jordan Rose613f3c02013-03-09 00:59:10 +00002394 // If the first selector piece ends with "NoCopy", and there is no
2395 // "freeWhenDone" parameter set to zero, we know ownership is being
2396 // transferred. Again, though, we can't be sure that the object will use
2397 // free() to deallocate the memory, so we can't model it explicitly.
2398 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002399 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002400 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002401
Anna Zaks42908c72012-06-19 05:10:32 +00002402 // If the first selector starts with addPointer, insertPointer,
2403 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2404 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002405 // that the pointers get freed by following the container itself.
2406 if (FirstSlot.startswith("addPointer") ||
2407 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002408 FirstSlot.startswith("replacePointer") ||
2409 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002410 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002411 }
2412
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002413 // We should escape receiver on call to 'init'. This is especially relevant
2414 // to the receiver, as the corresponding symbol is usually not referenced
2415 // after the call.
2416 if (Msg->getMethodFamily() == OMF_init) {
2417 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2418 return true;
2419 }
Anna Zaks737926b2013-05-31 22:39:13 +00002420
Jordan Rose742920c2012-07-02 19:27:35 +00002421 // Otherwise, assume that the method does not free memory.
2422 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002423 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002424 }
2425
Jordan Rose742920c2012-07-02 19:27:35 +00002426 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002427 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002428 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002429 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002430
Jordan Rose742920c2012-07-02 19:27:35 +00002431 ASTContext &ASTC = State->getStateManager().getContext();
2432
2433 // If it's one of the allocation functions we can reason about, we model
2434 // its behavior explicitly.
2435 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002436 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002437
2438 // If it's not a system call, assume it frees memory.
2439 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002440 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002441
2442 // White list the system functions whose arguments escape.
2443 const IdentifierInfo *II = FD->getIdentifier();
2444 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002445 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002446 StringRef FName = II->getName();
2447
Jordan Rose742920c2012-07-02 19:27:35 +00002448 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002449 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002450 if (FName.endswith("NoCopy")) {
2451 // Look for the deallocator argument. We know that the memory ownership
2452 // is not transferred only if the deallocator argument is
2453 // 'kCFAllocatorNull'.
2454 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2455 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2456 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2457 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2458 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002459 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002460 }
2461 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002462 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002463 }
2464
Jordan Rose742920c2012-07-02 19:27:35 +00002465 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002466 // 'closefn' is specified (and if that function does free memory),
2467 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002468 // Currently, we do not inspect the 'closefn' function (PR12101).
2469 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002470 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002471 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002472
2473 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2474 // these leaks might be intentional when setting the buffer for stdio.
2475 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2476 if (FName == "setbuf" || FName =="setbuffer" ||
2477 FName == "setlinebuf" || FName == "setvbuf") {
2478 if (Call->getNumArgs() >= 1) {
2479 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2480 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2481 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2482 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002483 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002484 }
2485 }
2486
2487 // A bunch of other functions which either take ownership of a pointer or
2488 // wrap the result up in a struct or object, meaning it can be freed later.
2489 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2490 // but the Malloc checker cannot differentiate between them. The right way
2491 // of doing this would be to implement a pointer escapes callback.
2492 if (FName == "CGBitmapContextCreate" ||
2493 FName == "CGBitmapContextCreateWithData" ||
2494 FName == "CVPixelBufferCreateWithBytes" ||
2495 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2496 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002497 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002498 }
2499
Jordan Rose7ab01822012-07-02 19:27:51 +00002500 // Handle cases where we know a buffer's /address/ can escape.
2501 // Note that the above checks handle some special cases where we know that
2502 // even though the address escapes, it's still our responsibility to free the
2503 // buffer.
2504 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002505 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002506
2507 // Otherwise, assume that the function does not free memory.
2508 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002509 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002510}
2511
Anna Zaks333481b2013-03-28 23:15:29 +00002512static bool retTrue(const RefState *RS) {
2513 return true;
2514}
2515
2516static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2517 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2518 RS->getAllocationFamily() == AF_CXXNew);
2519}
2520
Anna Zaksdc154152012-12-20 00:38:25 +00002521ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2522 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002523 const CallEvent *Call,
2524 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002525 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2526}
2527
2528ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2529 const InvalidatedSymbols &Escaped,
2530 const CallEvent *Call,
2531 PointerEscapeKind Kind) const {
2532 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2533 &checkIfNewOrNewArrayFamily);
2534}
2535
2536ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2537 const InvalidatedSymbols &Escaped,
2538 const CallEvent *Call,
2539 PointerEscapeKind Kind,
2540 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002541 // If we know that the call does not free memory, or we want to process the
2542 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002543 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002544 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002545 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2546 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002547 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002548 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002549 }
Anna Zaks3d348342012-02-14 21:55:24 +00002550
Anna Zaksdc154152012-12-20 00:38:25 +00002551 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002552 E = Escaped.end();
2553 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002554 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002555
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002556 if (EscapingSymbol && EscapingSymbol != sym)
2557 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002558
Anna Zaks0d6989b2012-06-22 02:04:31 +00002559 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002560 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2561 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002562 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002563 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2564 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002565 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002566 }
Anna Zaks3d348342012-02-14 21:55:24 +00002567 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002568}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002569
Jordy Rosebf38f202012-03-18 07:43:35 +00002570static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2571 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002572 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2573 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002574
Jordan Rose0c153cb2012-11-02 01:54:06 +00002575 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002576 I != E; ++I) {
2577 SymbolRef sym = I.getKey();
2578 if (!currMap.lookup(sym))
2579 return sym;
2580 }
2581
Craig Topper0dbb7832014-05-27 02:45:47 +00002582 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002583}
2584
Anna Zaks2b5bb972012-02-09 06:25:51 +00002585PathDiagnosticPiece *
2586MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2587 const ExplodedNode *PrevN,
2588 BugReporterContext &BRC,
2589 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002590 ProgramStateRef state = N->getState();
2591 ProgramStateRef statePrev = PrevN->getState();
2592
2593 const RefState *RS = state->get<RegionState>(Sym);
2594 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002595 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002596 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002597
Craig Topper0dbb7832014-05-27 02:45:47 +00002598 const Stmt *S = nullptr;
2599 const char *Msg = nullptr;
2600 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002601
2602 // Retrieve the associated statement.
2603 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002604 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002605 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002606 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002607 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002608 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002609 // If an assumption was made on a branch, it should be caught
2610 // here by looking at the state transition.
2611 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002612 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002613
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002614 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002615 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002616
Jordan Rose681cce92012-07-10 22:07:42 +00002617 // FIXME: We will eventually need to handle non-statement-based events
2618 // (__attribute__((cleanup))).
2619
Anna Zaks2b5bb972012-02-09 06:25:51 +00002620 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002621 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002622 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002623 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002624 StackHint = new StackHintGeneratorForSymbol(Sym,
2625 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002626 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002627 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002628 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002629 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002630 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002631 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002632 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002633 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002634 Mode = ReallocationFailed;
2635 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002636 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002637 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002638
Jordy Rose21ff76e2012-03-24 03:15:09 +00002639 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2640 // Is it possible to fail two reallocs WITHOUT testing in between?
2641 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2642 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002643 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002644 FailedReallocSymbol = sym;
2645 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002646 }
2647
2648 // We are in a special mode if a reallocation failed later in the path.
2649 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002650 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002651
Jordy Rose21ff76e2012-03-24 03:15:09 +00002652 // Is this is the first appearance of the reallocated symbol?
2653 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002654 // We're at the reallocation point.
2655 Msg = "Attempt to reallocate memory";
2656 StackHint = new StackHintGeneratorForSymbol(Sym,
2657 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002658 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002659 Mode = Normal;
2660 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002661 }
2662
Anna Zaks2b5bb972012-02-09 06:25:51 +00002663 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002664 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002665 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002666
2667 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002668 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002669 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002670 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002671}
2672
Anna Zaks263b7e02012-05-02 00:05:20 +00002673void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2674 const char *NL, const char *Sep) const {
2675
2676 RegionStateTy RS = State->get<RegionState>();
2677
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002678 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002679 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002680 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002681 const RefState *RefS = State->get<RegionState>(I.getKey());
2682 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002683 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002684 if (!CheckKind.hasValue())
2685 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002686
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002687 I.getKey()->dumpToStream(Out);
2688 Out << " : ";
2689 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002690 if (CheckKind.hasValue())
2691 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002692 Out << NL;
2693 }
2694 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002695}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002696
Anna Zakse4cfcd42013-04-16 00:22:55 +00002697void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2698 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002699 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002700 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2701 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002702 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2703 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2704 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002705 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00002706 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002707 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002708 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002709}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002710
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002711#define REGISTER_CHECKER(name) \
2712 void ento::register##name(CheckerManager &mgr) { \
2713 registerCStringCheckerBasic(mgr); \
2714 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002715 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2716 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002717 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2718 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2719 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002720
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002721REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002722REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002723REGISTER_CHECKER(MismatchedDeallocatorChecker)