blob: 6e9b7fefa3d060dae6dfffe18457e2775ced9689 [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"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000029#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000031#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000032#include <climits>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000033#include <utility>
Anna Zaks199e8e52012-02-22 03:14:20 +000034
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()
Anna Zaks30d46682016-03-08 01:21:51 +0000172 : II_alloca(nullptr), II_win_alloca(nullptr), II_malloc(nullptr),
173 II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
174 II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
175 II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr),
176 II_if_nameindex(nullptr), II_if_freenameindex(nullptr),
Anna Zaksbbec97c2017-03-09 00:01:01 +0000177 II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr),
178 II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr),
179 II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr),
180 II_g_free(nullptr), II_g_memdup(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000181
182 /// In pessimistic mode, the checker assumes that it does not know which
183 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000184 enum CheckKind {
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000185 CK_MallocChecker,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000186 CK_NewDeleteChecker,
187 CK_NewDeleteLeaksChecker,
188 CK_MismatchedDeallocatorChecker,
189 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000190 };
191
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000192 enum class MemoryOperationKind {
Anna Zaksd79b8402014-10-03 21:48:59 +0000193 MOK_Allocate,
194 MOK_Free,
195 MOK_Any
196 };
197
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000198 DefaultBool IsOptimistic;
199
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000200 DefaultBool ChecksEnabled[CK_NumCheckKinds];
201 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000202
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000203 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000204 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000205 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
206 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000207 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000208 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000209 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000210 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000211 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000212 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000213 void checkLocation(SVal l, bool isLoad, const Stmt *S,
214 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000215
216 ProgramStateRef checkPointerEscape(ProgramStateRef State,
217 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000218 const CallEvent *Call,
219 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000220 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
221 const InvalidatedSymbols &Escaped,
222 const CallEvent *Call,
223 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000224
Anna Zaks263b7e02012-05-02 00:05:20 +0000225 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000226 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000227
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000228private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000229 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
230 mutable std::unique_ptr<BugType> BT_DoubleDelete;
231 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
232 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
233 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000234 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000235 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
236 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000237 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
Anna Zaks30d46682016-03-08 01:21:51 +0000238 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
239 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
240 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
241 *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
Anna Zaksbbec97c2017-03-09 00:01:01 +0000242 *II_win_wcsdup, *II_g_malloc, *II_g_malloc0,
243 *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0,
244 *II_g_try_realloc, *II_g_free, *II_g_memdup;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000245 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000246
Anna Zaks3d348342012-02-14 21:55:24 +0000247 void initIdentifierInfo(ASTContext &C) const;
248
Anton Yartsev05789592013-03-28 17:05:19 +0000249 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000250 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000251
252 /// \brief Print names of allocators and deallocators.
253 ///
254 /// \returns true on success.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000255 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000256 const Expr *E) const;
257
258 /// \brief Print expected name of an allocator based on the deallocator's
259 /// family derived from the DeallocExpr.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000260 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +0000261 const Expr *DeallocExpr) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000262 /// \brief Print expected name of a deallocator based on the allocator's
Anton Yartsev05789592013-03-28 17:05:19 +0000263 /// family.
264 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
265
Jordan Rose613f3c02013-03-09 00:59:10 +0000266 ///@{
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000267 /// Check if this is one of the functions which can allocate/reallocate memory
Anna Zaks3d348342012-02-14 21:55:24 +0000268 /// pointed to by one of its arguments.
269 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000270 bool isCMemFunction(const FunctionDecl *FD,
271 ASTContext &C,
272 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000273 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000274 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000275 ///@}
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000276
277 /// \brief Perform a zero-allocation check.
278 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
279 const unsigned AllocationSizeArg,
280 ProgramStateRef State) const;
281
Richard Smith852e9ce2013-11-27 01:46:48 +0000282 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
283 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000284 const OwnershipAttr* Att,
285 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000286 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000287 const Expr *SizeEx, SVal Init,
288 ProgramStateRef State,
289 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000290 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000291 SVal SizeEx, SVal Init,
292 ProgramStateRef State,
293 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000294
Gabor Horvath73040272016-09-19 20:39:52 +0000295 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
296 ProgramStateRef State);
297
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000298 // Check if this malloc() for special flags. At present that means M_ZERO or
299 // __GFP_ZERO (in which case, treat it like calloc).
300 llvm::Optional<ProgramStateRef>
301 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
302 const ProgramStateRef &State) const;
303
Anna Zaks40a7eb32012-02-22 19:24:52 +0000304 /// Update the RefState to reflect the new memory allocation.
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000305 static ProgramStateRef
Anton Yartsev05789592013-03-28 17:05:19 +0000306 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
307 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000308
309 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000310 const OwnershipAttr* Att,
311 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000312 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000313 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000314 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000315 bool &ReleasedAllocated,
316 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000317 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
318 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000319 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000320 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000321 bool &ReleasedAllocated,
322 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000323
Anna Zaks40a7eb32012-02-22 19:24:52 +0000324 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000325 bool FreesMemOnFailure,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000326 ProgramStateRef State) const;
327 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
328 ProgramStateRef State);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000329
Anna Zaks46d01602012-05-18 01:16:10 +0000330 ///\brief Check if the memory associated with this symbol was released.
331 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
332
Anton Yartsev13df0362013-03-25 01:35:45 +0000333 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000334
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000335 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000336 const Stmt *S) const;
337
Jordan Rose656fdd52014-01-08 18:46:55 +0000338 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
339
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000340 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000341 /// "interesting" and should be modeled explicitly.
342 ///
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000343 /// \param [out] EscapingSymbol A function might not free memory in general,
Anna Zaks8ebeb642013-06-08 00:29:29 +0000344 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000345 /// returned and the single escaping symbol is returned through the out
346 /// parameter.
347 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000348 /// We assume that pointers do not escape through calls to system functions
349 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000350 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000351 ProgramStateRef State,
352 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000353
Anna Zaks333481b2013-03-28 23:15:29 +0000354 // Implementation of the checkPointerEscape callabcks.
355 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
356 const InvalidatedSymbols &Escaped,
357 const CallEvent *Call,
358 PointerEscapeKind Kind,
359 bool(*CheckRefState)(const RefState*)) const;
360
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000361 ///@{
362 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000363 /// Sets CheckKind to the kind of the checker responsible for this
364 /// family/call/symbol.
Anton Yartsev2487dd62015-03-10 22:24:21 +0000365 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
366 bool IsALeakCheck = false) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000367 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000368 const Stmt *AllocDeallocStmt,
369 bool IsALeakCheck = false) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000370 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000371 bool IsALeakCheck = false) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000372 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000373 static bool SummarizeValue(raw_ostream &os, SVal V);
374 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000375 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +0000376 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000377 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
378 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000379 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000380 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000381 SymbolRef Sym, bool OwnershipTransferred) const;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000382 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
383 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000384 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000385 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
386 SymbolRef Sym) const;
387 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000388 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000389
Jordan Rose656fdd52014-01-08 18:46:55 +0000390 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
391
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000392 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
393 SymbolRef Sym) const;
394
Anna Zaksdf901a42012-02-23 21:38:21 +0000395 /// Find the location of the allocation for Sym on the path leading to the
396 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000397 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
398 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000399
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000400 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
401
Anna Zaks2b5bb972012-02-09 06:25:51 +0000402 /// The bug visitor which allows us to print extra diagnostics along the
403 /// BugReport path. For example, showing the allocation site of the leaked
404 /// region.
David Blaikie6951e3e2015-08-13 22:58:37 +0000405 class MallocBugVisitor final
406 : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000407 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000408 enum NotificationMode {
409 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000410 ReallocationFailed
411 };
412
Anna Zaks2b5bb972012-02-09 06:25:51 +0000413 // The allocated region symbol tracked by the main analysis.
414 SymbolRef Sym;
415
Anna Zaks62cce9e2012-05-10 01:37:40 +0000416 // The mode we are in, i.e. what kind of diagnostics will be emitted.
417 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000418
Anna Zaks62cce9e2012-05-10 01:37:40 +0000419 // A symbol from when the primary region should have been reallocated.
420 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000421
Anna Zaks62cce9e2012-05-10 01:37:40 +0000422 bool IsLeak;
423
424 public:
425 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000426 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000427
Craig Topperfb6b25b2014-03-15 04:29:04 +0000428 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000429 static int X = 0;
430 ID.AddPointer(&X);
431 ID.AddPointer(Sym);
432 }
433
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000434 inline bool isAllocated(const RefState *S, const RefState *SPrev,
435 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000436 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000437 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000438 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
439 (!SPrev || !(SPrev->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000440 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000441 }
442
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000443 inline bool isReleased(const RefState *S, const RefState *SPrev,
444 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000445 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000446 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000447 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
448 }
449
Anna Zaks0d6989b2012-06-22 02:04:31 +0000450 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
451 const Stmt *Stmt) {
452 // Did not track -> relinquished. Other state (allocated) -> relinquished.
453 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
454 isa<ObjCPropertyRefExpr>(Stmt)) &&
455 (S && S->isRelinquished()) &&
456 (!SPrev || !SPrev->isRelinquished()));
457 }
458
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000459 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
460 const Stmt *Stmt) {
461 // If the expression is not a call, and the state change is
462 // released -> allocated, it must be the realloc return value
463 // check. If we have to handle more cases here, it might be cleaner just
464 // to track this extra bit in the state itself.
465 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000466 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
467 (SPrev && !(SPrev->isAllocated() ||
468 SPrev->isAllocatedOfSizeZero())));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000469 }
470
David Blaikie0a0c2752017-01-05 17:26:53 +0000471 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
472 const ExplodedNode *PrevN,
473 BugReporterContext &BRC,
474 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000475
David Blaikied15481c2014-08-29 18:18:43 +0000476 std::unique_ptr<PathDiagnosticPiece>
477 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
478 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000479 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000480 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000481
482 PathDiagnosticLocation L =
483 PathDiagnosticLocation::createEndOfPath(EndPathNode,
484 BRC.getSourceManager());
485 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000486 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
487 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000488 }
489
Anna Zakscba4f292012-03-16 23:24:20 +0000490 private:
491 class StackHintGeneratorForReallocationFailed
492 : public StackHintGeneratorForSymbol {
493 public:
494 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
495 : StackHintGeneratorForSymbol(S, M) {}
496
Craig Topperfb6b25b2014-03-15 04:29:04 +0000497 std::string getMessageForArg(const Expr *ArgE,
498 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000499 // Printed parameters start at 1, not 0.
500 ++ArgIndex;
501
Anna Zakscba4f292012-03-16 23:24:20 +0000502 SmallString<200> buf;
503 llvm::raw_svector_ostream os(buf);
504
Jordan Rosec102b352012-09-22 01:24:42 +0000505 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
506 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000507
508 return os.str();
509 }
510
Craig Topperfb6b25b2014-03-15 04:29:04 +0000511 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000512 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000513 }
514 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000515 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000516};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000517} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000518
Jordan Rose0c153cb2012-11-02 01:54:06 +0000519REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
520REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Devin Coughlin81771732015-09-22 22:47:14 +0000521REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000522
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000523// A map from the freed symbol to the symbol representing the return value of
Anna Zaks67291b92012-11-13 03:18:01 +0000524// the free function.
525REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
526
Anna Zaksbb1ef902012-02-11 21:02:35 +0000527namespace {
David Blaikie903c2932015-08-13 22:50:09 +0000528class StopTrackingCallback final : public SymbolVisitor {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000529 ProgramStateRef state;
530public:
Benjamin Kramercfeacf52016-05-27 14:27:13 +0000531 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
Anna Zaksbb1ef902012-02-11 21:02:35 +0000532 ProgramStateRef getState() const { return state; }
533
Craig Topperfb6b25b2014-03-15 04:29:04 +0000534 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000535 state = state->remove<RegionState>(sym);
536 return true;
537 }
538};
539} // end anonymous namespace
540
Anna Zaks3d348342012-02-14 21:55:24 +0000541void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000542 if (II_malloc)
543 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000544 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000545 II_malloc = &Ctx.Idents.get("malloc");
546 II_free = &Ctx.Idents.get("free");
547 II_realloc = &Ctx.Idents.get("realloc");
548 II_reallocf = &Ctx.Idents.get("reallocf");
549 II_calloc = &Ctx.Idents.get("calloc");
550 II_valloc = &Ctx.Idents.get("valloc");
551 II_strdup = &Ctx.Idents.get("strdup");
552 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaks30d46682016-03-08 01:21:51 +0000553 II_wcsdup = &Ctx.Idents.get("wcsdup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000554 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000555 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
556 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaks30d46682016-03-08 01:21:51 +0000557
558 //MSVC uses `_`-prefixed instead, so we check for them too.
559 II_win_strdup = &Ctx.Idents.get("_strdup");
560 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
561 II_win_alloca = &Ctx.Idents.get("_alloca");
Anna Zaksbbec97c2017-03-09 00:01:01 +0000562
563 // Glib
564 II_g_malloc = &Ctx.Idents.get("g_malloc");
565 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
566 II_g_realloc = &Ctx.Idents.get("g_realloc");
567 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
568 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
569 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
570 II_g_free = &Ctx.Idents.get("g_free");
571 II_g_memdup = &Ctx.Idents.get("g_memdup");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000572}
573
Anna Zaks3d348342012-02-14 21:55:24 +0000574bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000575 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000576 return true;
577
Anna Zaksd79b8402014-10-03 21:48:59 +0000578 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000579 return true;
580
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000581 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
582 return true;
583
Anton Yartsev13df0362013-03-25 01:35:45 +0000584 if (isStandardNewDelete(FD, C))
585 return true;
586
Anna Zaks46d01602012-05-18 01:16:10 +0000587 return false;
588}
589
Anna Zaksd79b8402014-10-03 21:48:59 +0000590bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
591 ASTContext &C,
592 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000593 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000594 if (!FD)
595 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000596
Anna Zaksd79b8402014-10-03 21:48:59 +0000597 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
598 MemKind == MemoryOperationKind::MOK_Free);
599 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
600 MemKind == MemoryOperationKind::MOK_Allocate);
601
Jordan Rose6cd16c52012-07-10 23:13:01 +0000602 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000603 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000604 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000605
Anna Zaksd79b8402014-10-03 21:48:59 +0000606 if (Family == AF_Malloc && CheckFree) {
Anna Zaksbbec97c2017-03-09 00:01:01 +0000607 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
608 FunI == II_g_free)
Anna Zaksd79b8402014-10-03 21:48:59 +0000609 return true;
610 }
611
612 if (Family == AF_Malloc && CheckAlloc) {
613 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
614 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
Anna Zaks30d46682016-03-08 01:21:51 +0000615 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
Anna Zaksbbec97c2017-03-09 00:01:01 +0000616 FunI == II_win_wcsdup || FunI == II_kmalloc ||
617 FunI == II_g_malloc || FunI == II_g_malloc0 ||
618 FunI == II_g_realloc || FunI == II_g_try_malloc ||
619 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
620 FunI == II_g_memdup)
Anna Zaksd79b8402014-10-03 21:48:59 +0000621 return true;
622 }
623
624 if (Family == AF_IfNameIndex && CheckFree) {
625 if (FunI == II_if_freenameindex)
626 return true;
627 }
628
629 if (Family == AF_IfNameIndex && CheckAlloc) {
630 if (FunI == II_if_nameindex)
631 return true;
632 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000633
634 if (Family == AF_Alloca && CheckAlloc) {
Anna Zaks30d46682016-03-08 01:21:51 +0000635 if (FunI == II_alloca || FunI == II_win_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000636 return true;
637 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000638 }
Anna Zaks3d348342012-02-14 21:55:24 +0000639
Anna Zaksd79b8402014-10-03 21:48:59 +0000640 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000641 return false;
642
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000643 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000644 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
645 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
646 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
647 if (CheckFree)
648 return true;
649 } else if (OwnKind == OwnershipAttr::Returns) {
650 if (CheckAlloc)
651 return true;
652 }
653 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000654 }
Anna Zaks3d348342012-02-14 21:55:24 +0000655
Anna Zaks3d348342012-02-14 21:55:24 +0000656 return false;
657}
658
Anton Yartsev8b662702013-03-28 16:10:38 +0000659// Tells if the callee is one of the following:
660// 1) A global non-placement new/delete operator function.
661// 2) A global placement operator function with the single placement argument
662// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000663bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
664 ASTContext &C) const {
665 if (!FD)
666 return false;
667
668 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000669 if (Kind != OO_New && Kind != OO_Array_New &&
Anton Yartsev13df0362013-03-25 01:35:45 +0000670 Kind != OO_Delete && Kind != OO_Array_Delete)
671 return false;
672
Anton Yartsev8b662702013-03-28 16:10:38 +0000673 // Skip all operator new/delete methods.
674 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000675 return false;
676
677 // Return true if tested operator is a standard placement nothrow operator.
678 if (FD->getNumParams() == 2) {
679 QualType T = FD->getParamDecl(1)->getType();
680 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
681 return II->getName().equals("nothrow_t");
682 }
683
684 // Skip placement operators.
685 if (FD->getNumParams() != 1 || FD->isVariadic())
686 return false;
687
688 // One of the standard new/new[]/delete/delete[] non-placement operators.
689 return true;
690}
691
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000692llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
693 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
694 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
695 //
696 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
697 //
698 // One of the possible flags is M_ZERO, which means 'give me back an
699 // allocation which is already zeroed', like calloc.
700
701 // 2-argument kmalloc(), as used in the Linux kernel:
702 //
703 // void *kmalloc(size_t size, gfp_t flags);
704 //
705 // Has the similar flag value __GFP_ZERO.
706
707 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
708 // code could be shared.
709
710 ASTContext &Ctx = C.getASTContext();
711 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
712
713 if (!KernelZeroFlagVal.hasValue()) {
714 if (OS == llvm::Triple::FreeBSD)
715 KernelZeroFlagVal = 0x0100;
716 else if (OS == llvm::Triple::NetBSD)
717 KernelZeroFlagVal = 0x0002;
718 else if (OS == llvm::Triple::OpenBSD)
719 KernelZeroFlagVal = 0x0008;
720 else if (OS == llvm::Triple::Linux)
721 // __GFP_ZERO
722 KernelZeroFlagVal = 0x8000;
723 else
724 // FIXME: We need a more general way of getting the M_ZERO value.
725 // See also: O_CREAT in UnixAPIChecker.cpp.
726
727 // Fall back to normal malloc behavior on platforms where we don't
728 // know M_ZERO.
729 return None;
730 }
731
732 // We treat the last argument as the flags argument, and callers fall-back to
733 // normal malloc on a None return. This works for the FreeBSD kernel malloc
734 // as well as Linux kmalloc.
735 if (CE->getNumArgs() < 2)
736 return None;
737
738 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
739 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
740 if (!V.getAs<NonLoc>()) {
741 // The case where 'V' can be a location can only be due to a bad header,
742 // so in this case bail out.
743 return None;
744 }
745
746 NonLoc Flags = V.castAs<NonLoc>();
747 NonLoc ZeroFlag = C.getSValBuilder()
748 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
749 .castAs<NonLoc>();
750 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
751 Flags, ZeroFlag,
752 FlagsEx->getType());
753 if (MaskedFlagsUC.isUnknownOrUndef())
754 return None;
755 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
756
757 // Check if maskedFlags is non-zero.
758 ProgramStateRef TrueState, FalseState;
759 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
760
761 // If M_ZERO is set, treat this like calloc (initialized).
762 if (TrueState && !FalseState) {
763 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
764 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
765 }
766
767 return None;
768}
769
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000770void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000771 if (C.wasInlined)
772 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000773
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000774 const FunctionDecl *FD = C.getCalleeDecl(CE);
775 if (!FD)
776 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000777
Anna Zaks40a7eb32012-02-22 19:24:52 +0000778 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000779 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000780
781 if (FD->getKind() == Decl::Function) {
782 initIdentifierInfo(C.getASTContext());
783 IdentifierInfo *FunI = FD->getIdentifier();
784
Anna Zaksbbec97c2017-03-09 00:01:01 +0000785 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000786 if (CE->getNumArgs() < 1)
787 return;
788 if (CE->getNumArgs() < 3) {
789 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000790 if (CE->getNumArgs() == 1)
791 State = ProcessZeroAllocation(C, CE, 0, State);
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000792 } else if (CE->getNumArgs() == 3) {
793 llvm::Optional<ProgramStateRef> MaybeState =
794 performKernelMalloc(CE, C, State);
795 if (MaybeState.hasValue())
796 State = MaybeState.getValue();
797 else
798 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
799 }
800 } else if (FunI == II_kmalloc) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000801 if (CE->getNumArgs() < 1)
802 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000803 llvm::Optional<ProgramStateRef> MaybeState =
804 performKernelMalloc(CE, C, State);
805 if (MaybeState.hasValue())
806 State = MaybeState.getValue();
807 else
808 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
809 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000810 if (CE->getNumArgs() < 1)
811 return;
812 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000813 State = ProcessZeroAllocation(C, CE, 0, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000814 } else if (FunI == II_realloc || FunI == II_g_realloc ||
815 FunI == II_g_try_realloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000816 State = ReallocMem(C, CE, false, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000817 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000818 } else if (FunI == II_reallocf) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000819 State = ReallocMem(C, CE, true, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000820 State = ProcessZeroAllocation(C, CE, 1, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000821 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000822 State = CallocMem(C, CE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000823 State = ProcessZeroAllocation(C, CE, 0, State);
824 State = ProcessZeroAllocation(C, CE, 1, State);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000825 } else if (FunI == II_free || FunI == II_g_free) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000826 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaks30d46682016-03-08 01:21:51 +0000827 } else if (FunI == II_strdup || FunI == II_win_strdup ||
828 FunI == II_wcsdup || FunI == II_win_wcsdup) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000829 State = MallocUpdateRefState(C, CE, State);
830 } else if (FunI == II_strndup) {
831 State = MallocUpdateRefState(C, CE, State);
Anna Zaks30d46682016-03-08 01:21:51 +0000832 } else if (FunI == II_alloca || FunI == II_win_alloca) {
Devin Coughlin684d19d2016-10-16 22:19:03 +0000833 if (CE->getNumArgs() < 1)
834 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000835 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
836 AF_Alloca);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000837 State = ProcessZeroAllocation(C, CE, 0, State);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000838 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000839 // Process direct calls to operator new/new[]/delete/delete[] functions
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000840 // as distinct from new/new[]/delete/delete[] expressions that are
841 // processed by the checkPostStmt callbacks for CXXNewExpr and
Anton Yartseve3377fb2013-04-04 23:46:29 +0000842 // CXXDeleteExpr.
843 OverloadedOperatorKind K = FD->getOverloadedOperator();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000844 if (K == OO_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000845 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
846 AF_CXXNew);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000847 State = ProcessZeroAllocation(C, CE, 0, State);
848 }
849 else if (K == OO_Array_New) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000850 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
851 AF_CXXNewArray);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000852 State = ProcessZeroAllocation(C, CE, 0, State);
853 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000854 else if (K == OO_Delete || K == OO_Array_Delete)
855 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
856 else
857 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000858 } else if (FunI == II_if_nameindex) {
859 // Should we model this differently? We can allocate a fixed number of
860 // elements with zeros in the last one.
861 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
862 AF_IfNameIndex);
863 } else if (FunI == II_if_freenameindex) {
864 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Anna Zaksbbec97c2017-03-09 00:01:01 +0000865 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
866 if (CE->getNumArgs() < 1)
867 return;
868 SValBuilder &svalBuilder = C.getSValBuilder();
869 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
870 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
871 State = ProcessZeroAllocation(C, CE, 0, State);
872 } else if (FunI == II_g_memdup) {
873 if (CE->getNumArgs() < 2)
874 return;
875 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
876 State = ProcessZeroAllocation(C, CE, 1, State);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000877 }
878 }
879
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000880 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000881 // Check all the attributes, if there are any.
882 // There can be multiple of these attributes.
883 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000884 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
885 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000886 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000887 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000888 break;
889 case OwnershipAttr::Takes:
890 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000891 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000892 break;
893 }
894 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000895 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000896 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000897}
898
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000899// Performs a 0-sized allocations check.
900ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
901 const Expr *E,
902 const unsigned AllocationSizeArg,
903 ProgramStateRef State) const {
904 if (!State)
905 return nullptr;
906
907 const Expr *Arg = nullptr;
908
909 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
910 Arg = CE->getArg(AllocationSizeArg);
911 }
912 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
913 if (NE->isArray())
914 Arg = NE->getArraySize();
915 else
916 return State;
917 }
918 else
919 llvm_unreachable("not a CallExpr or CXXNewExpr");
920
921 assert(Arg);
922
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000923 Optional<DefinedSVal> DefArgVal =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000924 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
925
926 if (!DefArgVal)
927 return State;
928
929 // Check if the allocation size is 0.
930 ProgramStateRef TrueState, FalseState;
931 SValBuilder &SvalBuilder = C.getSValBuilder();
932 DefinedSVal Zero =
933 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
934
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000935 std::tie(TrueState, FalseState) =
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000936 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
937
938 if (TrueState && !FalseState) {
939 SVal retVal = State->getSVal(E, C.getLocationContext());
940 SymbolRef Sym = retVal.getAsLocSymbol();
941 if (!Sym)
942 return State;
943
944 const RefState *RS = State->get<RegionState>(Sym);
Devin Coughlin81771732015-09-22 22:47:14 +0000945 if (RS) {
946 if (RS->isAllocated())
947 return TrueState->set<RegionState>(Sym,
948 RefState::getAllocatedOfSizeZero(RS));
949 else
950 return State;
951 } else {
952 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
953 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
954 // tracked. Add zero-reallocated Sym to the state to catch references
955 // to zero-allocated memory.
956 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
957 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +0000958 }
959
960 // Assume the value is non-zero going forward.
961 assert(FalseState);
962 return FalseState;
963}
964
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000965static QualType getDeepPointeeType(QualType T) {
966 QualType Result = T, PointeeType = T->getPointeeType();
967 while (!PointeeType.isNull()) {
968 Result = PointeeType;
969 PointeeType = PointeeType->getPointeeType();
970 }
971 return Result;
972}
973
974static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
975
976 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
977 if (!ConstructE)
978 return false;
979
980 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
981 return false;
982
983 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
984
985 // Iterate over the constructor parameters.
David Majnemer59f77922016-06-24 04:05:48 +0000986 for (const auto *CtorParam : CtorD->parameters()) {
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000987
988 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
989 if (CtorParamPointeeT.isNull())
990 continue;
991
992 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
993
994 if (CtorParamPointeeT->getAsCXXRecordDecl())
995 return true;
996 }
997
998 return false;
999}
1000
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001001void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001002 CheckerContext &C) const {
1003
1004 if (NE->getNumPlacementArgs())
1005 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1006 E = NE->placement_arg_end(); I != E; ++I)
1007 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1008 checkUseAfterFree(Sym, C, *I);
1009
Anton Yartsev13df0362013-03-25 01:35:45 +00001010 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1011 return;
1012
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +00001013 ParentMap &PM = C.getLocationContext()->getParentMap();
1014 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1015 return;
1016
Anton Yartsev13df0362013-03-25 01:35:45 +00001017 ProgramStateRef State = C.getState();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001018 // The return value from operator new is bound to a specified initialization
1019 // value (if any) and we don't want to loose this value. So we call
1020 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
Anton Yartsev13df0362013-03-25 01:35:45 +00001021 // existing binding.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001022 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
Anton Yartsev05789592013-03-28 17:05:19 +00001023 : AF_CXXNew);
Gabor Horvath73040272016-09-19 20:39:52 +00001024 State = addExtentSize(C, NE, State);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001025 State = ProcessZeroAllocation(C, NE, 0, State);
Anton Yartsev13df0362013-03-25 01:35:45 +00001026 C.addTransition(State);
1027}
1028
Gabor Horvath73040272016-09-19 20:39:52 +00001029// Sets the extent value of the MemRegion allocated by
1030// new expression NE to its size in Bytes.
1031//
1032ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1033 const CXXNewExpr *NE,
1034 ProgramStateRef State) {
1035 if (!State)
1036 return nullptr;
1037 SValBuilder &svalBuilder = C.getSValBuilder();
1038 SVal ElementCount;
1039 const LocationContext *LCtx = C.getLocationContext();
1040 const SubRegion *Region;
1041 if (NE->isArray()) {
1042 const Expr *SizeExpr = NE->getArraySize();
1043 ElementCount = State->getSVal(SizeExpr, C.getLocationContext());
1044 // Store the extent size for the (symbolic)region
1045 // containing the elements.
1046 Region = (State->getSVal(NE, LCtx))
1047 .getAsRegion()
1048 ->getAs<SubRegion>()
1049 ->getSuperRegion()
1050 ->getAs<SubRegion>();
1051 } else {
1052 ElementCount = svalBuilder.makeIntVal(1, true);
1053 Region = (State->getSVal(NE, LCtx)).getAsRegion()->getAs<SubRegion>();
1054 }
1055 assert(Region);
1056
1057 // Set the region's extent equal to the Size in Bytes.
1058 QualType ElementType = NE->getAllocatedType();
1059 ASTContext &AstContext = C.getASTContext();
1060 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1061
Devin Coughline3b75de2016-12-16 18:41:40 +00001062 if (ElementCount.getAs<NonLoc>()) {
Gabor Horvath73040272016-09-19 20:39:52 +00001063 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1064 // size in Bytes = ElementCount*TypeSize
1065 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1066 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1067 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1068 svalBuilder.getArrayIndexType());
1069 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1070 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1071 State = State->assume(extentMatchesSize, true);
1072 }
1073 return State;
1074}
1075
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001076void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
Anton Yartsev13df0362013-03-25 01:35:45 +00001077 CheckerContext &C) const {
1078
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001079 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +00001080 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1081 checkUseAfterFree(Sym, C, DE->getArgument());
1082
Anton Yartsev13df0362013-03-25 01:35:45 +00001083 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1084 return;
1085
1086 ProgramStateRef State = C.getState();
1087 bool ReleasedAllocated;
1088 State = FreeMemAux(C, DE->getArgument(), DE, State,
1089 /*Hold*/false, ReleasedAllocated);
1090
1091 C.addTransition(State);
1092}
1093
Jordan Rose613f3c02013-03-09 00:59:10 +00001094static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1095 // If the first selector piece is one of the names below, assume that the
1096 // object takes ownership of the memory, promising to eventually deallocate it
1097 // with free().
1098 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1099 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1100 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
Alexander Kornienko9c104902015-12-28 13:06:58 +00001101 return FirstSlot == "dataWithBytesNoCopy" ||
1102 FirstSlot == "initWithBytesNoCopy" ||
1103 FirstSlot == "initWithCharactersNoCopy";
Anna Zaks0d6989b2012-06-22 02:04:31 +00001104}
1105
Jordan Rose613f3c02013-03-09 00:59:10 +00001106static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1107 Selector S = Call.getSelector();
1108
1109 // FIXME: We should not rely on fully-constrained symbols being folded.
1110 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1111 if (S.getNameForSlot(i).equals("freeWhenDone"))
1112 return !Call.getArgSVal(i).isZeroConstant();
1113
1114 return None;
1115}
1116
Anna Zaks67291b92012-11-13 03:18:01 +00001117void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1118 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +00001119 if (C.wasInlined)
1120 return;
1121
Jordan Rose613f3c02013-03-09 00:59:10 +00001122 if (!isKnownDeallocObjCMethodName(Call))
1123 return;
Anna Zaks67291b92012-11-13 03:18:01 +00001124
Jordan Rose613f3c02013-03-09 00:59:10 +00001125 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1126 if (!*FreeWhenDone)
1127 return;
1128
1129 bool ReleasedAllocatedMemory;
1130 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1131 Call.getOriginExpr(), C.getState(),
1132 /*Hold=*/true, ReleasedAllocatedMemory,
1133 /*RetNullOnFailure=*/true);
1134
1135 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +00001136}
1137
Richard Smith852e9ce2013-11-27 01:46:48 +00001138ProgramStateRef
1139MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001140 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001141 ProgramStateRef State) const {
1142 if (!State)
1143 return nullptr;
1144
Richard Smith852e9ce2013-11-27 01:46:48 +00001145 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001146 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001147
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001148 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001149 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001150 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001151 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001152 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1153}
1154
1155ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1156 const CallExpr *CE,
1157 const Expr *SizeEx, SVal Init,
1158 ProgramStateRef State,
1159 AllocationFamily Family) {
1160 if (!State)
1161 return nullptr;
1162
1163 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1164 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001165}
1166
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001167ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001168 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001169 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +00001170 ProgramStateRef State,
1171 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001172 if (!State)
1173 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +00001174
Jordan Rosef69e65f2014-09-05 16:33:51 +00001175 // We expect the malloc functions to return a pointer.
1176 if (!Loc::isLocType(CE->getType()))
1177 return nullptr;
1178
Anna Zaks3563fde2012-06-07 03:57:32 +00001179 // Bind the return value to the symbolic value from the heap region.
1180 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1181 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +00001182 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +00001183 SValBuilder &svalBuilder = C.getSValBuilder();
1184 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +00001185 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1186 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +00001187 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +00001188
Jordy Rose674bd552010-07-04 00:00:41 +00001189 // Fill the region with the initialization value.
Anna Zaksb5701952017-01-13 00:50:57 +00001190 State = State->bindDefault(RetVal, Init, LCtx);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001191
Jordy Rose674bd552010-07-04 00:00:41 +00001192 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +00001193 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +00001194 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +00001195 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +00001196 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001197 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001198 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001199 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001200 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001201 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001202 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001203
Anton Yartsev05789592013-03-28 17:05:19 +00001204 State = State->assume(extentMatchesSize, true);
1205 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001206 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001207
Anton Yartsev05789592013-03-28 17:05:19 +00001208 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001209}
1210
1211ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001212 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001213 ProgramStateRef State,
1214 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001215 if (!State)
1216 return nullptr;
1217
Anna Zaks40a7eb32012-02-22 19:24:52 +00001218 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001219 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001220
1221 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001222 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001223 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001224
Ted Kremenek90af9092010-12-02 07:49:45 +00001225 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001226 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001227
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001228 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001229 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001230}
1231
Anna Zaks40a7eb32012-02-22 19:24:52 +00001232ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1233 const CallExpr *CE,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001234 const OwnershipAttr *Att,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001235 ProgramStateRef State) const {
1236 if (!State)
1237 return nullptr;
1238
Richard Smith852e9ce2013-11-27 01:46:48 +00001239 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001240 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001241
Anna Zaksfe6eb672012-08-24 02:28:20 +00001242 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001243
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001244 for (const auto &Arg : Att->args()) {
1245 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001246 Att->getOwnKind() == OwnershipAttr::Holds,
1247 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001248 if (StateI)
1249 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001250 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001251 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001252}
1253
Ted Kremenek49b1e382012-01-26 21:29:00 +00001254ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001255 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001256 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001257 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001258 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001259 bool &ReleasedAllocated,
1260 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001261 if (!State)
1262 return nullptr;
1263
Anna Zaksb508d292012-04-10 23:41:11 +00001264 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001265 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001266
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001267 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001268 ReleasedAllocated, ReturnsNullOnFailure);
1269}
1270
Anna Zaksa14c1d02012-11-13 19:47:40 +00001271/// Checks if the previous call to free on the given symbol failed - if free
1272/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001273static bool didPreviousFreeFail(ProgramStateRef State,
1274 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001275 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001276 if (Ret) {
1277 assert(*Ret && "We should not store the null return symbol");
1278 ConstraintManager &CMgr = State->getConstraintManager();
1279 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001280 RetStatusSymbol = *Ret;
1281 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001282 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001283 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001284}
1285
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001286AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001287 const Stmt *S) const {
1288 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001289 return AF_None;
1290
Anton Yartseve3377fb2013-04-04 23:46:29 +00001291 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001292 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001293
1294 if (!FD)
1295 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1296
Anton Yartsev05789592013-03-28 17:05:19 +00001297 ASTContext &Ctx = C.getASTContext();
1298
Anna Zaksd79b8402014-10-03 21:48:59 +00001299 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001300 return AF_Malloc;
1301
1302 if (isStandardNewDelete(FD, Ctx)) {
1303 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001304 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001305 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001306 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001307 return AF_CXXNewArray;
1308 }
1309
Anna Zaksd79b8402014-10-03 21:48:59 +00001310 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1311 return AF_IfNameIndex;
1312
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001313 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1314 return AF_Alloca;
1315
Anton Yartsev05789592013-03-28 17:05:19 +00001316 return AF_None;
1317 }
1318
Anton Yartseve3377fb2013-04-04 23:46:29 +00001319 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1320 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1321
1322 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001323 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1324
Anton Yartseve3377fb2013-04-04 23:46:29 +00001325 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001326 return AF_Malloc;
1327
1328 return AF_None;
1329}
1330
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001331bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
Anton Yartsev05789592013-03-28 17:05:19 +00001332 const Expr *E) const {
1333 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1334 // FIXME: This doesn't handle indirect calls.
1335 const FunctionDecl *FD = CE->getDirectCallee();
1336 if (!FD)
1337 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001338
Anton Yartsev05789592013-03-28 17:05:19 +00001339 os << *FD;
1340 if (!FD->isOverloadedOperator())
1341 os << "()";
1342 return true;
1343 }
1344
1345 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1346 if (Msg->isInstanceMessage())
1347 os << "-";
1348 else
1349 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001350 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001351 return true;
1352 }
1353
1354 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001355 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001356 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1357 << "'";
1358 return true;
1359 }
1360
1361 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001362 os << "'"
Anton Yartsev05789592013-03-28 17:05:19 +00001363 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1364 << "'";
1365 return true;
1366 }
1367
1368 return false;
1369}
1370
1371void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1372 const Expr *E) const {
1373 AllocationFamily Family = getAllocationFamily(C, E);
1374
1375 switch(Family) {
1376 case AF_Malloc: os << "malloc()"; return;
1377 case AF_CXXNew: os << "'new'"; return;
1378 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001379 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001380 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001381 case AF_None: llvm_unreachable("not a deallocation expression");
1382 }
1383}
1384
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001385void MallocChecker::printExpectedDeallocName(raw_ostream &os,
Anton Yartsev05789592013-03-28 17:05:19 +00001386 AllocationFamily Family) const {
1387 switch(Family) {
1388 case AF_Malloc: os << "free()"; return;
1389 case AF_CXXNew: os << "'delete'"; return;
1390 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001391 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001392 case AF_Alloca:
1393 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001394 }
1395}
1396
Anna Zaks0d6989b2012-06-22 02:04:31 +00001397ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1398 const Expr *ArgExpr,
1399 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001400 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001401 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001402 bool &ReleasedAllocated,
1403 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001404
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001405 if (!State)
1406 return nullptr;
1407
Anna Zaks67291b92012-11-13 03:18:01 +00001408 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001409 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001410 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001411 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001412
1413 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001414 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001415 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001416
Anna Zaksad01ef52012-02-14 00:26:13 +00001417 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001418 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001419 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001420 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001421 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001422
Jordy Rose3597b212010-06-07 19:32:37 +00001423 // Unknown values could easily be okay
1424 // Undefined values are handled elsewhere
1425 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001426 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001427
Jordy Rose3597b212010-06-07 19:32:37 +00001428 const MemRegion *R = ArgVal.getAsRegion();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001429
Jordy Rose3597b212010-06-07 19:32:37 +00001430 // Nonlocs can't be freed, of course.
1431 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1432 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001433 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001434 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001435 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001436
Jordy Rose3597b212010-06-07 19:32:37 +00001437 R = R->StripCasts();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001438
Jordy Rose3597b212010-06-07 19:32:37 +00001439 // Blocks might show up as heap data, but should not be free()d
1440 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001441 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001442 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001443 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001444
Jordy Rose3597b212010-06-07 19:32:37 +00001445 const MemSpaceRegion *MS = R->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001446
1447 // Parameters, locals, statics, globals, and memory returned by
Anton Yartsevc38d7952015-03-03 22:58:46 +00001448 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001449 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1450 // FIXME: at the time this code was written, malloc() regions were
1451 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1452 // This means that there isn't actually anything from HeapSpaceRegion
1453 // that should be freed, even though we allow it here.
1454 // Of course, free() can work on memory allocated outside the current
1455 // function, so UnknownSpaceRegion is always a possibility.
1456 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001457
1458 if (isa<AllocaRegion>(R))
1459 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1460 else
1461 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1462
Craig Topper0dbb7832014-05-27 02:45:47 +00001463 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001464 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001465
1466 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001467 // Various cases could lead to non-symbol values here.
1468 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001469 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001470 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001471
Anna Zaksc89ad072013-02-07 23:05:47 +00001472 SymbolRef SymBase = SrBase->getSymbol();
1473 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001474 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001475
Anton Yartseve3377fb2013-04-04 23:46:29 +00001476 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001477
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001478 // Memory returned by alloca() shouldn't be freed.
1479 if (RsBase->getAllocationFamily() == AF_Alloca) {
1480 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1481 return nullptr;
1482 }
1483
Anna Zaks93a21a82013-04-09 00:30:28 +00001484 // Check for double free first.
1485 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001486 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1487 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1488 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001489 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001490
Anna Zaks93a21a82013-04-09 00:30:28 +00001491 // If the pointer is allocated or escaped, but we are now trying to free it,
1492 // check that the call to free is proper.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001493 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001494 RsBase->isEscaped()) {
Anna Zaks93a21a82013-04-09 00:30:28 +00001495
1496 // Check if an expected deallocation function matches the real one.
1497 bool DeallocMatchesAlloc =
1498 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1499 if (!DeallocMatchesAlloc) {
1500 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001501 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001502 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001503 }
1504
1505 // Check if the memory location being freed is the actual location
1506 // allocated, or an offset.
1507 RegionOffset Offset = R->getAsOffset();
1508 if (Offset.isValid() &&
1509 !Offset.hasSymbolicOffset() &&
1510 Offset.getOffset() != 0) {
1511 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001512 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
Anna Zaks93a21a82013-04-09 00:30:28 +00001513 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001514 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001515 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001516 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001517 }
1518
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001519 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001520 RsBase->isAllocatedOfSizeZero());
Anna Zaksfe6eb672012-08-24 02:28:20 +00001521
Anna Zaksa14c1d02012-11-13 19:47:40 +00001522 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001523 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001524
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001525 // Keep track of the return value. If it is NULL, we will know that free
Anna Zaks67291b92012-11-13 03:18:01 +00001526 // failed.
1527 if (ReturnsNullOnFailure) {
1528 SVal RetVal = C.getSVal(ParentExpr);
1529 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1530 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001531 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1532 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001533 }
1534 }
1535
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001536 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1537 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001538 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001539 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001540 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001541 RefState::getRelinquished(Family,
1542 ParentExpr));
1543
1544 return State->set<RegionState>(SymBase,
1545 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001546}
1547
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001548Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001549MallocChecker::getCheckIfTracked(AllocationFamily Family,
1550 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001551 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001552 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001553 case AF_Alloca:
1554 case AF_IfNameIndex: {
1555 if (ChecksEnabled[CK_MallocChecker])
1556 return CK_MallocChecker;
1557
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001558 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001559 }
1560 case AF_CXXNew:
1561 case AF_CXXNewArray: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001562 if (IsALeakCheck) {
1563 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1564 return CK_NewDeleteLeaksChecker;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001565 }
Anton Yartsev2487dd62015-03-10 22:24:21 +00001566 else {
1567 if (ChecksEnabled[CK_NewDeleteChecker])
1568 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001569 }
1570 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001571 }
1572 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001573 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001574 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001575 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001576 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001577}
1578
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001579Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001580MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001581 const Stmt *AllocDeallocStmt,
1582 bool IsALeakCheck) const {
1583 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1584 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001585}
1586
1587Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001588MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1589 bool IsALeakCheck) const {
Devin Coughlin81771732015-09-22 22:47:14 +00001590 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1591 return CK_MallocChecker;
1592
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001593 const RefState *RS = C.getState()->get<RegionState>(Sym);
1594 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001595 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001596}
1597
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001598bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001599 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001600 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001601 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001602 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001603 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001604 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001605 else
1606 return false;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001607
Jordy Rose3597b212010-06-07 19:32:37 +00001608 return true;
1609}
1610
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001611bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001612 const MemRegion *MR) {
1613 switch (MR->getKind()) {
Artem Dergachev73f018e2016-01-13 13:49:29 +00001614 case MemRegion::FunctionCodeRegionKind: {
1615 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001616 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001617 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001618 else
1619 os << "the address of a function";
1620 return true;
1621 }
Artem Dergachev73f018e2016-01-13 13:49:29 +00001622 case MemRegion::BlockCodeRegionKind:
Jordy Rose3597b212010-06-07 19:32:37 +00001623 os << "block text";
1624 return true;
1625 case MemRegion::BlockDataRegionKind:
1626 // FIXME: where the block came from?
1627 os << "a block";
1628 return true;
1629 default: {
1630 const MemSpaceRegion *MS = MR->getMemorySpace();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001631
Anna Zaks8158ef02012-01-04 23:54:01 +00001632 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001633 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1634 const VarDecl *VD;
1635 if (VR)
1636 VD = VR->getDecl();
1637 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001638 VD = nullptr;
1639
Jordy Rose3597b212010-06-07 19:32:37 +00001640 if (VD)
1641 os << "the address of the local variable '" << VD->getName() << "'";
1642 else
1643 os << "the address of a local stack variable";
1644 return true;
1645 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001646
1647 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001648 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1649 const VarDecl *VD;
1650 if (VR)
1651 VD = VR->getDecl();
1652 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001653 VD = nullptr;
1654
Jordy Rose3597b212010-06-07 19:32:37 +00001655 if (VD)
1656 os << "the address of the parameter '" << VD->getName() << "'";
1657 else
1658 os << "the address of a parameter";
1659 return true;
1660 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001661
1662 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001663 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1664 const VarDecl *VD;
1665 if (VR)
1666 VD = VR->getDecl();
1667 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001668 VD = nullptr;
1669
Jordy Rose3597b212010-06-07 19:32:37 +00001670 if (VD) {
1671 if (VD->isStaticLocal())
1672 os << "the address of the static variable '" << VD->getName() << "'";
1673 else
1674 os << "the address of the global variable '" << VD->getName() << "'";
1675 } else
1676 os << "the address of a global variable";
1677 return true;
1678 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001679
1680 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001681 }
1682 }
1683}
1684
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001685void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1686 SourceRange Range,
Anton Yartsev05789592013-03-28 17:05:19 +00001687 const Expr *DeallocExpr) const {
1688
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001689 if (!ChecksEnabled[CK_MallocChecker] &&
1690 !ChecksEnabled[CK_NewDeleteChecker])
1691 return;
1692
1693 Optional<MallocChecker::CheckKind> CheckKind =
1694 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001695 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001696 return;
1697
Devin Coughline39bd402015-09-16 22:03:05 +00001698 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001699 if (!BT_BadFree[*CheckKind])
1700 BT_BadFree[*CheckKind].reset(
1701 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1702
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001703 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001704 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001705
Jordy Rose3597b212010-06-07 19:32:37 +00001706 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001707 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1708 MR = ER->getSuperRegion();
1709
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001710 os << "Argument to ";
1711 if (!printAllocDeallocName(os, C, DeallocExpr))
1712 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001713
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001714 os << " is ";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001715 bool Summarized = MR ? SummarizeRegion(os, MR)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001716 : SummarizeValue(os, ArgVal);
1717 if (Summarized)
1718 os << ", which is not memory allocated by ";
1719 else
1720 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001721
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001722 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001723
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001724 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001725 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001726 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001727 C.emitReport(std::move(R));
Jordy Rose3597b212010-06-07 19:32:37 +00001728 }
1729}
1730
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001731void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001732 SourceRange Range) const {
1733
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001734 Optional<MallocChecker::CheckKind> CheckKind;
1735
1736 if (ChecksEnabled[CK_MallocChecker])
1737 CheckKind = CK_MallocChecker;
1738 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1739 CheckKind = CK_MismatchedDeallocatorChecker;
1740 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001741 return;
1742
Devin Coughline39bd402015-09-16 22:03:05 +00001743 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001744 if (!BT_FreeAlloca[*CheckKind])
1745 BT_FreeAlloca[*CheckKind].reset(
1746 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1747
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001748 auto R = llvm::make_unique<BugReport>(
1749 *BT_FreeAlloca[*CheckKind],
1750 "Memory allocated by alloca() should not be deallocated", N);
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001751 R->markInteresting(ArgVal.getAsRegion());
1752 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001753 C.emitReport(std::move(R));
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001754 }
1755}
1756
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001757void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001758 SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001759 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001760 const RefState *RS,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001761 SymbolRef Sym,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001762 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001763
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001764 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001765 return;
1766
Devin Coughline39bd402015-09-16 22:03:05 +00001767 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001768 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001769 BT_MismatchedDealloc.reset(
1770 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1771 "Bad deallocator", "Memory Error"));
1772
Anton Yartsev05789592013-03-28 17:05:19 +00001773 SmallString<100> buf;
1774 llvm::raw_svector_ostream os(buf);
1775
1776 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1777 SmallString<20> AllocBuf;
1778 llvm::raw_svector_ostream AllocOs(AllocBuf);
1779 SmallString<20> DeallocBuf;
1780 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1781
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001782 if (OwnershipTransferred) {
1783 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1784 os << DeallocOs.str() << " cannot";
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001785 else
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001786 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001787
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001788 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001789
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001790 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1791 os << " allocated by " << AllocOs.str();
1792 } else {
1793 os << "Memory";
1794 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1795 os << " allocated by " << AllocOs.str();
1796
1797 os << " should be deallocated by ";
1798 printExpectedDeallocName(os, RS->getAllocationFamily());
1799
1800 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1801 os << ", not " << DeallocOs.str();
1802 }
Anton Yartsev05789592013-03-28 17:05:19 +00001803
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001804 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001805 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001806 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001807 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001808 C.emitReport(std::move(R));
Anton Yartsev05789592013-03-28 17:05:19 +00001809 }
1810}
1811
Anna Zaksc89ad072013-02-07 23:05:47 +00001812void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001813 SourceRange Range, const Expr *DeallocExpr,
1814 const Expr *AllocExpr) const {
1815
Anton Yartsev05789592013-03-28 17:05:19 +00001816
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001817 if (!ChecksEnabled[CK_MallocChecker] &&
1818 !ChecksEnabled[CK_NewDeleteChecker])
1819 return;
1820
1821 Optional<MallocChecker::CheckKind> CheckKind =
1822 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001823 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001824 return;
1825
Devin Coughline39bd402015-09-16 22:03:05 +00001826 ExplodedNode *N = C.generateErrorNode();
Craig Topper0dbb7832014-05-27 02:45:47 +00001827 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001828 return;
1829
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001830 if (!BT_OffsetFree[*CheckKind])
1831 BT_OffsetFree[*CheckKind].reset(
1832 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001833
1834 SmallString<100> buf;
1835 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001836 SmallString<20> AllocNameBuf;
1837 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001838
1839 const MemRegion *MR = ArgVal.getAsRegion();
1840 assert(MR && "Only MemRegion based symbols can have offset free errors");
1841
1842 RegionOffset Offset = MR->getAsOffset();
1843 assert((Offset.isValid() &&
1844 !Offset.hasSymbolicOffset() &&
1845 Offset.getOffset() != 0) &&
1846 "Only symbols with a valid offset can have offset free errors");
1847
1848 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1849
Anton Yartsev05789592013-03-28 17:05:19 +00001850 os << "Argument to ";
1851 if (!printAllocDeallocName(os, C, DeallocExpr))
1852 os << "deallocator";
1853 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001854 << offsetBytes
1855 << " "
1856 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001857 << " from the start of ";
1858 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1859 os << "memory allocated by " << AllocNameOs.str();
1860 else
1861 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001862
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001863 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001864 R->markInteresting(MR->getBaseRegion());
1865 R->addRange(Range);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001866 C.emitReport(std::move(R));
Anna Zaksc89ad072013-02-07 23:05:47 +00001867}
1868
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001869void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1870 SymbolRef Sym) const {
1871
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001872 if (!ChecksEnabled[CK_MallocChecker] &&
1873 !ChecksEnabled[CK_NewDeleteChecker])
1874 return;
1875
1876 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001877 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001878 return;
1879
Devin Coughline39bd402015-09-16 22:03:05 +00001880 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001881 if (!BT_UseFree[*CheckKind])
1882 BT_UseFree[*CheckKind].reset(new BugType(
1883 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001884
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001885 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1886 "Use of memory after it is freed", N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001887
1888 R->markInteresting(Sym);
1889 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001890 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001891 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001892 }
1893}
1894
1895void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00001896 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001897 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001898
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001899 if (!ChecksEnabled[CK_MallocChecker] &&
1900 !ChecksEnabled[CK_NewDeleteChecker])
1901 return;
1902
1903 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001904 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001905 return;
1906
Devin Coughline39bd402015-09-16 22:03:05 +00001907 if (ExplodedNode *N = C.generateErrorNode()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001908 if (!BT_DoubleFree[*CheckKind])
1909 BT_DoubleFree[*CheckKind].reset(
1910 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001911
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001912 auto R = llvm::make_unique<BugReport>(
1913 *BT_DoubleFree[*CheckKind],
1914 (Released ? "Attempt to free released memory"
1915 : "Attempt to free non-owned memory"),
1916 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001917 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001918 R->markInteresting(Sym);
1919 if (PrevSym)
1920 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001921 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001922 C.emitReport(std::move(R));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001923 }
1924}
1925
Jordan Rose656fdd52014-01-08 18:46:55 +00001926void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1927
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001928 if (!ChecksEnabled[CK_NewDeleteChecker])
1929 return;
1930
1931 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001932 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001933 return;
1934
Devin Coughline39bd402015-09-16 22:03:05 +00001935 if (ExplodedNode *N = C.generateErrorNode()) {
Jordan Rose656fdd52014-01-08 18:46:55 +00001936 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001937 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1938 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001939
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001940 auto R = llvm::make_unique<BugReport>(
1941 *BT_DoubleDelete, "Attempt to delete released memory", N);
Jordan Rose656fdd52014-01-08 18:46:55 +00001942
1943 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001944 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001945 C.emitReport(std::move(R));
Jordan Rose656fdd52014-01-08 18:46:55 +00001946 }
1947}
1948
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001949void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1950 SourceRange Range,
1951 SymbolRef Sym) const {
1952
1953 if (!ChecksEnabled[CK_MallocChecker] &&
1954 !ChecksEnabled[CK_NewDeleteChecker])
1955 return;
1956
1957 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1958
1959 if (!CheckKind.hasValue())
1960 return;
1961
Devin Coughline39bd402015-09-16 22:03:05 +00001962 if (ExplodedNode *N = C.generateErrorNode()) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001963 if (!BT_UseZerroAllocated[*CheckKind])
1964 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
1965 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
1966
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001967 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
1968 "Use of zero-allocated memory", N);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001969
1970 R->addRange(Range);
1971 if (Sym) {
1972 R->markInteresting(Sym);
1973 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1974 }
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00001975 C.emitReport(std::move(R));
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00001976 }
1977}
1978
Anna Zaks40a7eb32012-02-22 19:24:52 +00001979ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1980 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001981 bool FreesOnFail,
1982 ProgramStateRef State) const {
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 Kremenek90af9092010-12-02 07:49:45 +00001989 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001990 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001991 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001992 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001993 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001994 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001995
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001996 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001997
Ted Kremenek90af9092010-12-02 07:49:45 +00001998 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001999 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002000
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002001 // Get the size argument. If there is no size arg then give up.
2002 const Expr *Arg1 = CE->getArg(1);
2003 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00002004 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002005
2006 // Get the value of the size argument.
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002007 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00002008 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00002009 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00002010 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002011
2012 // Compare the size argument to 0.
2013 DefinedOrUnknownSVal SizeZero =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002014 svalBuilder.evalEQ(State, Arg1Val,
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002015 svalBuilder.makeIntValWithPtrWidth(0, false));
2016
Anna Zaksd56c8792012-02-13 18:05:39 +00002017 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002018 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00002019 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002020 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00002021 // We only assume exceptional states if they are definitely true; if the
2022 // state is under-constrained, assume regular realloc behavior.
2023 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2024 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2025
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002026 // If the ptr is NULL and the size is not 0, the call is equivalent to
Lenny Maiorani005b5c12011-04-27 14:49:29 +00002027 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00002028 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00002029 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00002030 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002031 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002032 }
2033
Anna Zaksd56c8792012-02-13 18:05:39 +00002034 if (PrtIsNull && SizeIsZero)
Devin Coughlin81771732015-09-22 22:47:14 +00002035 return State;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002036
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002037 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00002038 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002039 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002040 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002041 SymbolRef ToPtr = RetVal.getAsSymbol();
2042 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00002043 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00002044
Anna Zaksfe6eb672012-08-24 02:28:20 +00002045 bool ReleasedAllocated = false;
2046
Anna Zaksd56c8792012-02-13 18:05:39 +00002047 // If the size is 0, free the memory.
2048 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00002049 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2050 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00002051 // The semantics of the return value are:
2052 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00002053 // to free() is returned. We just free the input pointer and do not add
2054 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00002055 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00002056 }
2057
2058 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00002059 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002060 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00002061
Anna Zaksd56c8792012-02-13 18:05:39 +00002062 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
2063 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00002064 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00002065 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00002066
Anna Zaks75cfbb62012-09-12 22:57:34 +00002067 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2068 if (FreesOnFail)
2069 Kind = RPIsFreeOnFailure;
2070 else if (!ReleasedAllocated)
2071 Kind = RPDoNotTrackAfterFailure;
2072
Anna Zaksfe6eb672012-08-24 02:28:20 +00002073 // Record the info about the reallocated symbol so that we could properly
2074 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00002075 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00002076 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00002077 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00002078 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00002079 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00002080 }
Craig Topper0dbb7832014-05-27 02:45:47 +00002081 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00002082}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002083
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002084ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002085 ProgramStateRef State) {
2086 if (!State)
2087 return nullptr;
2088
Anna Zaksb508d292012-04-10 23:41:11 +00002089 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00002090 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00002091
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00002092 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00002093 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002094 SVal count = State->getSVal(CE->getArg(0), LCtx);
2095 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
2096 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002097 svalBuilder.getContext().getSizeType());
Ted Kremenek90af9092010-12-02 07:49:45 +00002098 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002099
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00002100 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00002101}
2102
Anna Zaksfc2e1532012-03-21 19:45:08 +00002103LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00002104MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2105 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00002106 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00002107 // Walk the ExplodedGraph backwards and find the first node that referred to
2108 // the tracked symbol.
2109 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002110 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00002111
2112 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00002113 ProgramStateRef State = N->getState();
2114 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00002115 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00002116
2117 // Find the most recent expression bound to the symbol in the current
2118 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00002119 if (!ReferenceRegion) {
2120 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2121 SVal Val = State->getSVal(MR);
2122 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00002123 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00002124 // Do not show local variables belonging to a function other than
2125 // where the error is reported.
2126 if (!VR ||
2127 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2128 ReferenceRegion = MR;
2129 }
2130 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00002131 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00002132
Anna Zaks486a0ff2015-02-05 01:02:53 +00002133 // Allocation node, is the last node in the current or parent context in
2134 // which the symbol was tracked.
2135 const LocationContext *NContext = N->getLocationContext();
2136 if (NContext == LeakContext ||
2137 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00002138 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00002139 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00002140 }
2141
Anna Zaksa043d0c2013-01-08 00:25:29 +00002142 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00002143}
2144
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002145void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2146 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00002147
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002148 if (!ChecksEnabled[CK_MallocChecker] &&
2149 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00002150 return;
2151
Anton Yartsev9907fc92015-03-04 23:18:21 +00002152 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002153 assert(RS && "cannot leak an untracked symbol");
2154 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00002155
2156 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002157 return;
2158
Anton Yartsev2487dd62015-03-10 22:24:21 +00002159 Optional<MallocChecker::CheckKind>
2160 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002161
Anton Yartsev2487dd62015-03-10 22:24:21 +00002162 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00002163 return;
2164
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002165 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002166 if (!BT_Leak[*CheckKind]) {
2167 BT_Leak[*CheckKind].reset(
2168 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002169 // Leaks should not be reported if they are post-dominated by a sink:
2170 // (1) Sinks are higher importance bugs.
2171 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2172 // with __noreturn functions such as assert() or exit(). We choose not
2173 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002174 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002175 }
2176
Anna Zaksdf901a42012-02-23 21:38:21 +00002177 // Most bug reports are cached at the location where they occurred.
2178 // With leaks, we want to unique them by the location where they were
2179 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00002180 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00002181 const ExplodedNode *AllocNode = nullptr;
2182 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002183 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002184
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002185 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
Anton Yartsev6e499252013-04-05 02:25:02 +00002186 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00002187 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2188 C.getSourceManager(),
2189 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00002190
Anna Zaksfc2e1532012-03-21 19:45:08 +00002191 SmallString<200> buf;
2192 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002193 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00002194 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00002195 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00002196 } else {
2197 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00002198 }
2199
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002200 auto R = llvm::make_unique<BugReport>(
2201 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2202 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00002203 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00002204 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +00002205 C.emitReport(std::move(R));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002206}
2207
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002208void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2209 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00002210{
Zhongxing Xubce831f2010-08-15 08:19:57 +00002211 if (!SymReaper.hasDeadSymbols())
2212 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00002213
Ted Kremenek49b1e382012-01-26 21:29:00 +00002214 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002215 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002216 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002217
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002218 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002219 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2220 if (SymReaper.isDead(I->first)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002221 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002222 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002223 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002224 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002225
Zhongxing Xuc7460962009-11-13 07:48:11 +00002226 }
2227 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002228
Anna Zaksd56c8792012-02-13 18:05:39 +00002229 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002230 ReallocPairsTy RP = state->get<ReallocPairs>();
2231 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002232 if (SymReaper.isDead(I->first) ||
2233 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002234 state = state->remove<ReallocPairs>(I->first);
2235 }
2236 }
2237
Anna Zaks67291b92012-11-13 03:18:01 +00002238 // Cleanup the FreeReturnValue Map.
2239 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2240 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2241 if (SymReaper.isDead(I->first) ||
2242 SymReaper.isDead(I->second)) {
2243 state = state->remove<FreeReturnValue>(I->first);
2244 }
2245 }
2246
Anna Zaksdf901a42012-02-23 21:38:21 +00002247 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002248 ExplodedNode *N = C.getPredecessor();
2249 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002250 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +00002251 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2252 if (N) {
2253 for (SmallVectorImpl<SymbolRef>::iterator
Craig Topper2341c0d2013-07-04 03:08:24 +00002254 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Devin Coughline39bd402015-09-16 22:03:05 +00002255 reportLeak(*I, N, C);
2256 }
Anna Zaks78edc2f2012-02-09 06:48:19 +00002257 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002258 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002259
Anna Zaksdf901a42012-02-23 21:38:21 +00002260 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002261}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002262
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002263void MallocChecker::checkPreCall(const CallEvent &Call,
2264 CheckerContext &C) const {
2265
Jordan Rose656fdd52014-01-08 18:46:55 +00002266 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2267 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2268 if (!Sym || checkDoubleDelete(Sym, C))
2269 return;
2270 }
2271
Anna Zaks46d01602012-05-18 01:16:10 +00002272 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002273 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2274 const FunctionDecl *FD = FC->getDecl();
2275 if (!FD)
2276 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002277
Anna Zaksd79b8402014-10-03 21:48:59 +00002278 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002279 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002280 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2281 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2282 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002283 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002284
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002285 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002286 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002287 return;
2288 }
2289
2290 // Check if the callee of a method is deleted.
2291 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2292 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2293 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2294 return;
2295 }
2296
2297 // Check arguments for being used after free.
2298 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2299 SVal ArgSVal = Call.getArgSVal(I);
2300 if (ArgSVal.getAs<Loc>()) {
2301 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002302 if (!Sym)
2303 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002304 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002305 return;
2306 }
2307 }
2308}
2309
Anna Zaksa1b227b2012-02-08 23:16:56 +00002310void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2311 const Expr *E = S->getRetValue();
2312 if (!E)
2313 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002314
2315 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002316 ProgramStateRef State = C.getState();
2317 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002318 SymbolRef Sym = RetVal.getAsSymbol();
2319 if (!Sym)
2320 // If we are returning a field of the allocated struct or an array element,
2321 // the callee could still free the memory.
2322 // TODO: This logic should be a part of generic symbol escape callback.
2323 if (const MemRegion *MR = RetVal.getAsRegion())
2324 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2325 if (const SymbolicRegion *BMR =
2326 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2327 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002328
Anna Zaks3aa52252012-02-11 21:44:39 +00002329 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002330 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002331 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002332}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002333
Anna Zaks9fe80982012-03-22 00:57:20 +00002334// TODO: Blocks should be either inlined or should call invalidate regions
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002335// upon invocation. After that's in place, special casing here will not be
Anna Zaks9fe80982012-03-22 00:57:20 +00002336// needed.
2337void MallocChecker::checkPostStmt(const BlockExpr *BE,
2338 CheckerContext &C) const {
2339
2340 // Scan the BlockDecRefExprs for any object the retain count checker
2341 // may be tracking.
2342 if (!BE->getBlockDecl()->hasCaptures())
2343 return;
2344
2345 ProgramStateRef state = C.getState();
2346 const BlockDataRegion *R =
2347 cast<BlockDataRegion>(state->getSVal(BE,
2348 C.getLocationContext()).getAsRegion());
2349
2350 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2351 E = R->referenced_vars_end();
2352
2353 if (I == E)
2354 return;
2355
2356 SmallVector<const MemRegion*, 10> Regions;
2357 const LocationContext *LC = C.getLocationContext();
2358 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2359
2360 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002361 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002362 if (VR->getSuperRegion() == R) {
2363 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2364 }
2365 Regions.push_back(VR);
2366 }
2367
2368 state =
2369 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2370 Regions.data() + Regions.size()).getState();
2371 C.addTransition(state);
2372}
2373
Anna Zaks46d01602012-05-18 01:16:10 +00002374bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002375 assert(Sym);
2376 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002377 return (RS && RS->isReleased());
2378}
2379
2380bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2381 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002382
Jordan Rose656fdd52014-01-08 18:46:55 +00002383 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002384 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2385 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002386 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002387
Anna Zaksa1b227b2012-02-08 23:16:56 +00002388 return false;
2389}
2390
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002391void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2392 const Stmt *S) const {
2393 assert(Sym);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002394
Devin Coughlin81771732015-09-22 22:47:14 +00002395 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2396 if (RS->isAllocatedOfSizeZero())
2397 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2398 }
2399 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2400 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2401 }
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002402}
2403
Jordan Rose656fdd52014-01-08 18:46:55 +00002404bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2405
2406 if (isReleased(Sym, C)) {
2407 ReportDoubleDelete(C, Sym);
2408 return true;
2409 }
2410 return false;
2411}
2412
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002413// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002414void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2415 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002416 SymbolRef Sym = l.getLocSymbolInBase();
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002417 if (Sym) {
Anna Zaks46d01602012-05-18 01:16:10 +00002418 checkUseAfterFree(Sym, C, S);
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002419 checkUseZeroAllocated(Sym, C, S);
2420 }
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002421}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002422
Anna Zaksbb1ef902012-02-11 21:02:35 +00002423// If a symbolic region is assumed to NULL (or another constant), stop tracking
2424// it - assuming that allocation failed on this path.
2425ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2426 SVal Cond,
2427 bool Assumption) const {
2428 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002429 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002430 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002431 ConstraintManager &CMgr = state->getConstraintManager();
2432 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2433 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002434 state = state->remove<RegionState>(I.getKey());
2435 }
2436
Anna Zaksd56c8792012-02-13 18:05:39 +00002437 // Realloc returns 0 when reallocation fails, which means that we should
2438 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002439 ReallocPairsTy RP = state->get<ReallocPairs>();
2440 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002441 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002442 ConstraintManager &CMgr = state->getConstraintManager();
2443 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002444 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002445 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002446
Anna Zaks75cfbb62012-09-12 22:57:34 +00002447 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2448 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2449 if (RS->isReleased()) {
2450 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002451 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002452 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002453 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2454 state = state->remove<RegionState>(ReallocSym);
2455 else
2456 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002457 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002458 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002459 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002460 }
2461
Anna Zaksbb1ef902012-02-11 21:02:35 +00002462 return state;
2463}
2464
Anna Zaks8ebeb642013-06-08 00:29:29 +00002465bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002466 const CallEvent *Call,
2467 ProgramStateRef State,
2468 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002469 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002470 EscapingSymbol = nullptr;
2471
Jordan Rose2a833ca2014-01-15 17:25:15 +00002472 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002473 // TODO: If we want to be more optimistic here, we'll need to make sure that
2474 // regions escape to C++ containers. They seem to do that even now, but for
2475 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002476 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002477 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002478
Jordan Rose742920c2012-07-02 19:27:35 +00002479 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002480 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002481 // If it's not a framework call, or if it takes a callback, assume it
2482 // can free memory.
Anna Zaksfe1eca52015-10-27 20:19:45 +00002483 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002484 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002485
Jordan Rose613f3c02013-03-09 00:59:10 +00002486 // If it's a method we know about, handle it explicitly post-call.
2487 // This should happen before the "freeWhenDone" check below.
2488 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002489 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002490
Jordan Rose613f3c02013-03-09 00:59:10 +00002491 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2492 // about, we can't be sure that the object will use free() to deallocate the
2493 // memory, so we can't model it explicitly. The best we can do is use it to
2494 // decide whether the pointer escapes.
2495 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002496 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002497
Jordan Rose613f3c02013-03-09 00:59:10 +00002498 // If the first selector piece ends with "NoCopy", and there is no
2499 // "freeWhenDone" parameter set to zero, we know ownership is being
2500 // transferred. Again, though, we can't be sure that the object will use
2501 // free() to deallocate the memory, so we can't model it explicitly.
2502 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002503 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002504 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002505
Anna Zaks42908c72012-06-19 05:10:32 +00002506 // If the first selector starts with addPointer, insertPointer,
2507 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2508 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002509 // that the pointers get freed by following the container itself.
2510 if (FirstSlot.startswith("addPointer") ||
2511 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002512 FirstSlot.startswith("replacePointer") ||
2513 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002514 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002515 }
2516
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002517 // We should escape receiver on call to 'init'. This is especially relevant
2518 // to the receiver, as the corresponding symbol is usually not referenced
2519 // after the call.
2520 if (Msg->getMethodFamily() == OMF_init) {
2521 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2522 return true;
2523 }
Anna Zaks737926b2013-05-31 22:39:13 +00002524
Jordan Rose742920c2012-07-02 19:27:35 +00002525 // Otherwise, assume that the method does not free memory.
2526 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002527 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002528 }
2529
Jordan Rose742920c2012-07-02 19:27:35 +00002530 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002531 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002532 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002533 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002534
Jordan Rose742920c2012-07-02 19:27:35 +00002535 ASTContext &ASTC = State->getStateManager().getContext();
2536
2537 // If it's one of the allocation functions we can reason about, we model
2538 // its behavior explicitly.
2539 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002540 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002541
2542 // If it's not a system call, assume it frees memory.
2543 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002544 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002545
2546 // White list the system functions whose arguments escape.
2547 const IdentifierInfo *II = FD->getIdentifier();
2548 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002549 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002550 StringRef FName = II->getName();
2551
Jordan Rose742920c2012-07-02 19:27:35 +00002552 // White list the 'XXXNoCopy' CoreFoundation functions.
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002553 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002554 if (FName.endswith("NoCopy")) {
2555 // Look for the deallocator argument. We know that the memory ownership
2556 // is not transferred only if the deallocator argument is
2557 // 'kCFAllocatorNull'.
2558 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2559 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2560 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2561 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2562 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002563 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002564 }
2565 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002566 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002567 }
2568
Jordan Rose742920c2012-07-02 19:27:35 +00002569 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002570 // 'closefn' is specified (and if that function does free memory),
2571 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002572 // Currently, we do not inspect the 'closefn' function (PR12101).
2573 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002574 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002575 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002576
2577 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2578 // these leaks might be intentional when setting the buffer for stdio.
2579 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2580 if (FName == "setbuf" || FName =="setbuffer" ||
2581 FName == "setlinebuf" || FName == "setvbuf") {
2582 if (Call->getNumArgs() >= 1) {
2583 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2584 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2585 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2586 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002587 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002588 }
2589 }
2590
2591 // A bunch of other functions which either take ownership of a pointer or
2592 // wrap the result up in a struct or object, meaning it can be freed later.
2593 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2594 // but the Malloc checker cannot differentiate between them. The right way
2595 // of doing this would be to implement a pointer escapes callback.
2596 if (FName == "CGBitmapContextCreate" ||
2597 FName == "CGBitmapContextCreateWithData" ||
2598 FName == "CVPixelBufferCreateWithBytes" ||
2599 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2600 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002601 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002602 }
2603
Anna Zaks03f48332016-01-06 00:32:56 +00002604 if (FName == "postEvent" &&
2605 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2606 return true;
2607 }
2608
2609 if (FName == "postEvent" &&
2610 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2611 return true;
2612 }
2613
Artem Dergachev85c92112016-12-16 12:21:55 +00002614 if (FName == "connectImpl" &&
2615 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2616 return true;
2617 }
2618
Jordan Rose7ab01822012-07-02 19:27:51 +00002619 // Handle cases where we know a buffer's /address/ can escape.
2620 // Note that the above checks handle some special cases where we know that
2621 // even though the address escapes, it's still our responsibility to free the
2622 // buffer.
2623 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002624 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002625
2626 // Otherwise, assume that the function does not free memory.
2627 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002628 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002629}
2630
Anna Zaks333481b2013-03-28 23:15:29 +00002631static bool retTrue(const RefState *RS) {
2632 return true;
2633}
2634
2635static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2636 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2637 RS->getAllocationFamily() == AF_CXXNew);
2638}
2639
Anna Zaksdc154152012-12-20 00:38:25 +00002640ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2641 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002642 const CallEvent *Call,
2643 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002644 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2645}
2646
2647ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2648 const InvalidatedSymbols &Escaped,
2649 const CallEvent *Call,
2650 PointerEscapeKind Kind) const {
2651 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2652 &checkIfNewOrNewArrayFamily);
2653}
2654
2655ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2656 const InvalidatedSymbols &Escaped,
2657 const CallEvent *Call,
2658 PointerEscapeKind Kind,
2659 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002660 // If we know that the call does not free memory, or we want to process the
2661 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002662 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002663 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002664 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2665 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002666 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002667 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002668 }
Anna Zaks3d348342012-02-14 21:55:24 +00002669
Anna Zaksdc154152012-12-20 00:38:25 +00002670 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002671 E = Escaped.end();
2672 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002673 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002674
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002675 if (EscapingSymbol && EscapingSymbol != sym)
2676 continue;
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002677
Anna Zaks0d6989b2012-06-22 02:04:31 +00002678 if (const RefState *RS = State->get<RegionState>(sym)) {
Anton Yartsevb50f4ba2015-04-14 14:18:04 +00002679 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2680 CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002681 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002682 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2683 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002684 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002685 }
Anna Zaks3d348342012-02-14 21:55:24 +00002686 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002687}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002688
Jordy Rosebf38f202012-03-18 07:43:35 +00002689static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2690 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002691 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2692 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002693
Jordan Rose0c153cb2012-11-02 01:54:06 +00002694 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002695 I != E; ++I) {
2696 SymbolRef sym = I.getKey();
2697 if (!currMap.lookup(sym))
2698 return sym;
2699 }
2700
Craig Topper0dbb7832014-05-27 02:45:47 +00002701 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002702}
2703
David Blaikie0a0c2752017-01-05 17:26:53 +00002704std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2705 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2706 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002707 ProgramStateRef state = N->getState();
2708 ProgramStateRef statePrev = PrevN->getState();
2709
2710 const RefState *RS = state->get<RegionState>(Sym);
2711 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002712 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002713 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002714
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002715 const Stmt *S = PathDiagnosticLocation::getStmt(N);
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002716 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002717 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002718
Jordan Rose681cce92012-07-10 22:07:42 +00002719 // FIXME: We will eventually need to handle non-statement-based events
2720 // (__attribute__((cleanup))).
2721
Anna Zaks2b5bb972012-02-09 06:25:51 +00002722 // Find out if this is an interesting point and what is the kind.
Gabor Horvath6ee4f902016-08-18 07:54:50 +00002723 const char *Msg = nullptr;
2724 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002725 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002726 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002727 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002728 StackHint = new StackHintGeneratorForSymbol(Sym,
2729 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002730 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002731 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002732 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002733 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002734 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002735 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002736 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002737 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002738 Mode = ReallocationFailed;
2739 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002740 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002741 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002742
Jordy Rose21ff76e2012-03-24 03:15:09 +00002743 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2744 // Is it possible to fail two reallocs WITHOUT testing in between?
2745 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2746 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002747 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002748 FailedReallocSymbol = sym;
2749 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002750 }
2751
2752 // We are in a special mode if a reallocation failed later in the path.
2753 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002754 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002755
Jordy Rose21ff76e2012-03-24 03:15:09 +00002756 // Is this is the first appearance of the reallocated symbol?
2757 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002758 // We're at the reallocation point.
2759 Msg = "Attempt to reallocate memory";
2760 StackHint = new StackHintGeneratorForSymbol(Sym,
2761 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002762 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002763 Mode = Normal;
2764 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002765 }
2766
Anna Zaks2b5bb972012-02-09 06:25:51 +00002767 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002768 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002769 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002770
2771 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002772 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002773 N->getLocationContext());
David Blaikie0a0c2752017-01-05 17:26:53 +00002774 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002775}
2776
Anna Zaks263b7e02012-05-02 00:05:20 +00002777void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2778 const char *NL, const char *Sep) const {
2779
2780 RegionStateTy RS = State->get<RegionState>();
2781
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002782 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002783 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002784 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002785 const RefState *RefS = State->get<RegionState>(I.getKey());
2786 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002787 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002788 if (!CheckKind.hasValue())
2789 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002790
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002791 I.getKey()->dumpToStream(Out);
2792 Out << " : ";
2793 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002794 if (CheckKind.hasValue())
2795 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002796 Out << NL;
2797 }
2798 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002799}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002800
Anna Zakse4cfcd42013-04-16 00:22:55 +00002801void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2802 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002803 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002804 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2805 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002806 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2807 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2808 mgr.getCurrentCheckName();
Ted Kremenek3a0678e2015-09-08 03:50:52 +00002809 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
Anna Zakse4cfcd42013-04-16 00:22:55 +00002810 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002811 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002812 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002813}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002814
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002815#define REGISTER_CHECKER(name) \
2816 void ento::register##name(CheckerManager &mgr) { \
2817 registerCStringCheckerBasic(mgr); \
2818 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002819 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2820 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002821 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2822 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2823 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002824
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002825REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002826REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002827REGISTER_CHECKER(MismatchedDeallocatorChecker)