blob: a49247bbd22fa867399317221e4942677437b791 [file] [log] [blame]
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines malloc/free checker, which checks for potential memory
11// leaks, double free, and use-after-free problems.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zakse56167e2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +000018#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/SourceManager.h"
Jordan Rose6b33c6f2014-03-26 17:05:46 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000023#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000029#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000030#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000032#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000033#include <climits>
34
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000035using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000036using namespace ento;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000037
38namespace {
39
Anton Yartsev05789592013-03-28 17:05:19 +000040// Used to check correspondence between allocators and deallocators.
41enum AllocationFamily {
42 AF_None,
43 AF_Malloc,
44 AF_CXXNew,
Anna Zaksd79b8402014-10-03 21:48:59 +000045 AF_CXXNewArray,
46 AF_IfNameIndex
Anton Yartsev05789592013-03-28 17:05:19 +000047};
48
Zhongxing Xu1239de12009-12-11 00:55:44 +000049class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000050 enum Kind { // Reference to allocated memory.
51 Allocated,
52 // Reference to released/freed memory.
53 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000054 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000055 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000056 Relinquished,
57 // We are no longer guaranteed to have observed all manipulations
58 // of this pointer/memory. For example, it could have been
59 // passed as a parameter to an opaque function.
60 Escaped
61 };
Anton Yartsev05789592013-03-28 17:05:19 +000062
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000063 const Stmt *S;
Anton Yartsev05789592013-03-28 17:05:19 +000064 unsigned K : 2; // Kind enum, but stored as a bitfield.
65 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
66 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000067
Anton Yartsev05789592013-03-28 17:05:19 +000068 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000069 : S(s), K(k), Family(family) {
70 assert(family != AF_None);
71 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000072public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000073 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000074 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000075 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000076 bool isEscaped() const { return K == Escaped; }
77 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000078 return (AllocationFamily)Family;
79 }
Anna Zaksd56c8792012-02-13 18:05:39 +000080 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000081
82 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000083 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000084 }
85
Anton Yartsev05789592013-03-28 17:05:19 +000086 static RefState getAllocated(unsigned family, const Stmt *s) {
87 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000088 }
Anton Yartsev05789592013-03-28 17:05:19 +000089 static RefState getReleased(unsigned family, const Stmt *s) {
90 return RefState(Released, s, family);
91 }
92 static RefState getRelinquished(unsigned family, const Stmt *s) {
93 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +000094 }
Anna Zaks93a21a82013-04-09 00:30:28 +000095 static RefState getEscaped(const RefState *RS) {
96 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
97 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000098
99 void Profile(llvm::FoldingSetNodeID &ID) const {
100 ID.AddInteger(K);
101 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +0000102 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000103 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000104
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000105 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000106 switch (static_cast<Kind>(K)) {
107#define CASE(ID) case ID: OS << #ID; break;
108 CASE(Allocated)
109 CASE(Released)
110 CASE(Relinquished)
111 CASE(Escaped)
112 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000113 }
114
Alp Tokeref6b0072014-01-04 13:47:14 +0000115 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000116};
117
Anna Zaks75cfbb62012-09-12 22:57:34 +0000118enum ReallocPairKind {
119 RPToBeFreedAfterFailure,
120 // The symbol has been freed when reallocation failed.
121 RPIsFreeOnFailure,
122 // The symbol does not need to be freed after reallocation fails.
123 RPDoNotTrackAfterFailure
124};
125
Anna Zaksfe6eb672012-08-24 02:28:20 +0000126/// \class ReallocPair
127/// \brief Stores information about the symbol being reallocated by a call to
128/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000129struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000130 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000131 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000132 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000133
Anna Zaks75cfbb62012-09-12 22:57:34 +0000134 ReallocPair(SymbolRef S, ReallocPairKind K) :
135 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000136 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000137 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000138 ID.AddPointer(ReallocatedSym);
139 }
140 bool operator==(const ReallocPair &X) const {
141 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000142 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000143 }
144};
145
Anna Zaksa043d0c2013-01-08 00:25:29 +0000146typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000147
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000148class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000149 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000150 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000151 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000152 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000153 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000154 check::PostStmt<CXXNewExpr>,
155 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000156 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000157 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000158 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000159 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000160{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000161public:
Craig Topper0dbb7832014-05-27 02:45:47 +0000162 MallocChecker()
163 : II_malloc(nullptr), II_free(nullptr), II_realloc(nullptr),
164 II_calloc(nullptr), II_valloc(nullptr), II_reallocf(nullptr),
Anna Zaksd79b8402014-10-03 21:48:59 +0000165 II_strndup(nullptr), II_strdup(nullptr), II_kmalloc(nullptr),
166 II_if_nameindex(nullptr), II_if_freenameindex(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000167
168 /// In pessimistic mode, the checker assumes that it does not know which
169 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000170 enum CheckKind {
171 CK_MallocPessimistic,
172 CK_MallocOptimistic,
173 CK_NewDeleteChecker,
174 CK_NewDeleteLeaksChecker,
175 CK_MismatchedDeallocatorChecker,
176 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000177 };
178
Anna Zaksd79b8402014-10-03 21:48:59 +0000179 enum class MemoryOperationKind {
180 MOK_Allocate,
181 MOK_Free,
182 MOK_Any
183 };
184
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000185 DefaultBool ChecksEnabled[CK_NumCheckKinds];
186 CheckName CheckNames[CK_NumCheckKinds];
Anton Yartseve5c0c142015-02-18 00:39:06 +0000187 typedef llvm::SmallVector<CheckKind, CK_NumCheckKinds> CKVecTy;
Anna Zakscd37bf42012-02-08 23:16:52 +0000188
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000189 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000190 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000191 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
192 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000193 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000194 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000195 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000196 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000197 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000198 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000199 void checkLocation(SVal l, bool isLoad, const Stmt *S,
200 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000201
202 ProgramStateRef checkPointerEscape(ProgramStateRef State,
203 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000204 const CallEvent *Call,
205 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000206 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
207 const InvalidatedSymbols &Escaped,
208 const CallEvent *Call,
209 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000210
Anna Zaks263b7e02012-05-02 00:05:20 +0000211 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000212 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000213
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000214private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000215 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
216 mutable std::unique_ptr<BugType> BT_DoubleDelete;
217 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
218 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
219 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
220 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
221 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000222 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000223 *II_valloc, *II_reallocf, *II_strndup, *II_strdup,
Anna Zaksd79b8402014-10-03 21:48:59 +0000224 *II_kmalloc, *II_if_nameindex, *II_if_freenameindex;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000225 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000226
Anna Zaks3d348342012-02-14 21:55:24 +0000227 void initIdentifierInfo(ASTContext &C) const;
228
Anton Yartsev05789592013-03-28 17:05:19 +0000229 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000230 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000231
232 /// \brief Print names of allocators and deallocators.
233 ///
234 /// \returns true on success.
235 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
236 const Expr *E) const;
237
238 /// \brief Print expected name of an allocator based on the deallocator's
239 /// family derived from the DeallocExpr.
240 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
241 const Expr *DeallocExpr) const;
242 /// \brief Print expected name of a deallocator based on the allocator's
243 /// family.
244 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
245
Jordan Rose613f3c02013-03-09 00:59:10 +0000246 ///@{
Anna Zaks3d348342012-02-14 21:55:24 +0000247 /// Check if this is one of the functions which can allocate/reallocate memory
248 /// pointed to by one of its arguments.
249 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000250 bool isCMemFunction(const FunctionDecl *FD,
251 ASTContext &C,
252 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000253 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000254 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000255 ///@}
Richard Smith852e9ce2013-11-27 01:46:48 +0000256 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
257 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000258 const OwnershipAttr* Att,
259 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000260 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000261 const Expr *SizeEx, SVal Init,
262 ProgramStateRef State,
263 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000264 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000265 SVal SizeEx, SVal Init,
266 ProgramStateRef State,
267 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000268
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000269 // Check if this malloc() for special flags. At present that means M_ZERO or
270 // __GFP_ZERO (in which case, treat it like calloc).
271 llvm::Optional<ProgramStateRef>
272 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
273 const ProgramStateRef &State) const;
274
Anna Zaks40a7eb32012-02-22 19:24:52 +0000275 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev05789592013-03-28 17:05:19 +0000276 static ProgramStateRef
277 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
278 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000279
280 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000281 const OwnershipAttr* Att,
282 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000283 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000284 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000285 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000286 bool &ReleasedAllocated,
287 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000288 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
289 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000290 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000291 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000292 bool &ReleasedAllocated,
293 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000294
Anna Zaks40a7eb32012-02-22 19:24:52 +0000295 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000296 bool FreesMemOnFailure,
297 ProgramStateRef State) const;
298 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
299 ProgramStateRef State);
Jordy Rose3597b212010-06-07 19:32:37 +0000300
Anna Zaks46d01602012-05-18 01:16:10 +0000301 ///\brief Check if the memory associated with this symbol was released.
302 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
303
Anton Yartsev13df0362013-03-25 01:35:45 +0000304 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000305
Jordan Rose656fdd52014-01-08 18:46:55 +0000306 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
307
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000308 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000309 /// "interesting" and should be modeled explicitly.
310 ///
Anna Zaks8ebeb642013-06-08 00:29:29 +0000311 /// \param [out] EscapingSymbol A function might not free memory in general,
312 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000313 /// returned and the single escaping symbol is returned through the out
314 /// parameter.
315 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000316 /// We assume that pointers do not escape through calls to system functions
317 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000318 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000319 ProgramStateRef State,
320 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000321
Anna Zaks333481b2013-03-28 23:15:29 +0000322 // Implementation of the checkPointerEscape callabcks.
323 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
324 const InvalidatedSymbols &Escaped,
325 const CallEvent *Call,
326 PointerEscapeKind Kind,
327 bool(*CheckRefState)(const RefState*)) const;
328
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000329 ///@{
330 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartseve5c0c142015-02-18 00:39:06 +0000331 /// Looks through incoming CheckKind(s) and returns the kind of the checker
332 /// responsible for this family/call/symbol.
333 Optional<CheckKind> getCheckIfTracked(CheckKind CK,
334 AllocationFamily Family) const;
335 Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec,
336 AllocationFamily Family) const;
337 Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000338 const Stmt *AllocDeallocStmt) const;
Anton Yartseve5c0c142015-02-18 00:39:06 +0000339 Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
340 SymbolRef Sym) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000341 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000342 static bool SummarizeValue(raw_ostream &os, SVal V);
343 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev05789592013-03-28 17:05:19 +0000344 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
345 const Expr *DeallocExpr) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000346 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000347 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000348 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000349 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
350 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000351 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000352 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
353 SymbolRef Sym) const;
354 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000355 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000356
Jordan Rose656fdd52014-01-08 18:46:55 +0000357 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
358
Anna Zaksdf901a42012-02-23 21:38:21 +0000359 /// Find the location of the allocation for Sym on the path leading to the
360 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000361 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
362 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000363
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000364 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
365
Anna Zaks2b5bb972012-02-09 06:25:51 +0000366 /// The bug visitor which allows us to print extra diagnostics along the
367 /// BugReport path. For example, showing the allocation site of the leaked
368 /// region.
Jordy Rosef78877e2012-03-24 02:45:35 +0000369 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000370 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000371 enum NotificationMode {
372 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000373 ReallocationFailed
374 };
375
Anna Zaks2b5bb972012-02-09 06:25:51 +0000376 // The allocated region symbol tracked by the main analysis.
377 SymbolRef Sym;
378
Anna Zaks62cce9e2012-05-10 01:37:40 +0000379 // The mode we are in, i.e. what kind of diagnostics will be emitted.
380 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000381
Anna Zaks62cce9e2012-05-10 01:37:40 +0000382 // A symbol from when the primary region should have been reallocated.
383 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000384
Anna Zaks62cce9e2012-05-10 01:37:40 +0000385 bool IsLeak;
386
387 public:
388 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000389 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000390
Anna Zaks2b5bb972012-02-09 06:25:51 +0000391 virtual ~MallocBugVisitor() {}
392
Craig Topperfb6b25b2014-03-15 04:29:04 +0000393 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000394 static int X = 0;
395 ID.AddPointer(&X);
396 ID.AddPointer(Sym);
397 }
398
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000399 inline bool isAllocated(const RefState *S, const RefState *SPrev,
400 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000401 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000402 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000403 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000404 }
405
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000406 inline bool isReleased(const RefState *S, const RefState *SPrev,
407 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000408 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000409 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000410 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
411 }
412
Anna Zaks0d6989b2012-06-22 02:04:31 +0000413 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
414 const Stmt *Stmt) {
415 // Did not track -> relinquished. Other state (allocated) -> relinquished.
416 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
417 isa<ObjCPropertyRefExpr>(Stmt)) &&
418 (S && S->isRelinquished()) &&
419 (!SPrev || !SPrev->isRelinquished()));
420 }
421
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000422 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
423 const Stmt *Stmt) {
424 // If the expression is not a call, and the state change is
425 // released -> allocated, it must be the realloc return value
426 // check. If we have to handle more cases here, it might be cleaner just
427 // to track this extra bit in the state itself.
428 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
429 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000430 }
431
432 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
433 const ExplodedNode *PrevN,
434 BugReporterContext &BRC,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000435 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000436
David Blaikied15481c2014-08-29 18:18:43 +0000437 std::unique_ptr<PathDiagnosticPiece>
438 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
439 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000440 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000441 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000442
443 PathDiagnosticLocation L =
444 PathDiagnosticLocation::createEndOfPath(EndPathNode,
445 BRC.getSourceManager());
446 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000447 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
448 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000449 }
450
Anna Zakscba4f292012-03-16 23:24:20 +0000451 private:
452 class StackHintGeneratorForReallocationFailed
453 : public StackHintGeneratorForSymbol {
454 public:
455 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
456 : StackHintGeneratorForSymbol(S, M) {}
457
Craig Topperfb6b25b2014-03-15 04:29:04 +0000458 std::string getMessageForArg(const Expr *ArgE,
459 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000460 // Printed parameters start at 1, not 0.
461 ++ArgIndex;
462
Anna Zakscba4f292012-03-16 23:24:20 +0000463 SmallString<200> buf;
464 llvm::raw_svector_ostream os(buf);
465
Jordan Rosec102b352012-09-22 01:24:42 +0000466 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
467 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000468
469 return os.str();
470 }
471
Craig Topperfb6b25b2014-03-15 04:29:04 +0000472 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000473 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000474 }
475 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000476 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000477};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000478} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000479
Jordan Rose0c153cb2012-11-02 01:54:06 +0000480REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
481REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000482
Anna Zaks67291b92012-11-13 03:18:01 +0000483// A map from the freed symbol to the symbol representing the return value of
484// the free function.
485REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
486
Anna Zaksbb1ef902012-02-11 21:02:35 +0000487namespace {
488class StopTrackingCallback : public SymbolVisitor {
489 ProgramStateRef state;
490public:
491 StopTrackingCallback(ProgramStateRef st) : state(st) {}
492 ProgramStateRef getState() const { return state; }
493
Craig Topperfb6b25b2014-03-15 04:29:04 +0000494 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000495 state = state->remove<RegionState>(sym);
496 return true;
497 }
498};
499} // end anonymous namespace
500
Anna Zaks3d348342012-02-14 21:55:24 +0000501void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000502 if (II_malloc)
503 return;
504 II_malloc = &Ctx.Idents.get("malloc");
505 II_free = &Ctx.Idents.get("free");
506 II_realloc = &Ctx.Idents.get("realloc");
507 II_reallocf = &Ctx.Idents.get("reallocf");
508 II_calloc = &Ctx.Idents.get("calloc");
509 II_valloc = &Ctx.Idents.get("valloc");
510 II_strdup = &Ctx.Idents.get("strdup");
511 II_strndup = &Ctx.Idents.get("strndup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000512 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000513 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
514 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000515}
516
Anna Zaks3d348342012-02-14 21:55:24 +0000517bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000518 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000519 return true;
520
Anna Zaksd79b8402014-10-03 21:48:59 +0000521 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000522 return true;
523
Anton Yartsev13df0362013-03-25 01:35:45 +0000524 if (isStandardNewDelete(FD, C))
525 return true;
526
Anna Zaks46d01602012-05-18 01:16:10 +0000527 return false;
528}
529
Anna Zaksd79b8402014-10-03 21:48:59 +0000530bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
531 ASTContext &C,
532 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000533 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000534 if (!FD)
535 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000536
Anna Zaksd79b8402014-10-03 21:48:59 +0000537 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
538 MemKind == MemoryOperationKind::MOK_Free);
539 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
540 MemKind == MemoryOperationKind::MOK_Allocate);
541
Jordan Rose6cd16c52012-07-10 23:13:01 +0000542 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000543 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000544 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000545
Anna Zaksd79b8402014-10-03 21:48:59 +0000546 if (Family == AF_Malloc && CheckFree) {
547 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
548 return true;
549 }
550
551 if (Family == AF_Malloc && CheckAlloc) {
552 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
553 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
554 FunI == II_strndup || FunI == II_kmalloc)
555 return true;
556 }
557
558 if (Family == AF_IfNameIndex && CheckFree) {
559 if (FunI == II_if_freenameindex)
560 return true;
561 }
562
563 if (Family == AF_IfNameIndex && CheckAlloc) {
564 if (FunI == II_if_nameindex)
565 return true;
566 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000567 }
Anna Zaks3d348342012-02-14 21:55:24 +0000568
Anna Zaksd79b8402014-10-03 21:48:59 +0000569 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000570 return false;
571
Anna Zaksd79b8402014-10-03 21:48:59 +0000572 if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs()) {
573 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
574 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
575 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
576 if (CheckFree)
577 return true;
578 } else if (OwnKind == OwnershipAttr::Returns) {
579 if (CheckAlloc)
580 return true;
581 }
582 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000583 }
Anna Zaks3d348342012-02-14 21:55:24 +0000584
Anna Zaks3d348342012-02-14 21:55:24 +0000585 return false;
586}
587
Anton Yartsev8b662702013-03-28 16:10:38 +0000588// Tells if the callee is one of the following:
589// 1) A global non-placement new/delete operator function.
590// 2) A global placement operator function with the single placement argument
591// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000592bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
593 ASTContext &C) const {
594 if (!FD)
595 return false;
596
597 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
598 if (Kind != OO_New && Kind != OO_Array_New &&
599 Kind != OO_Delete && Kind != OO_Array_Delete)
600 return false;
601
Anton Yartsev8b662702013-03-28 16:10:38 +0000602 // Skip all operator new/delete methods.
603 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000604 return false;
605
606 // Return true if tested operator is a standard placement nothrow operator.
607 if (FD->getNumParams() == 2) {
608 QualType T = FD->getParamDecl(1)->getType();
609 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
610 return II->getName().equals("nothrow_t");
611 }
612
613 // Skip placement operators.
614 if (FD->getNumParams() != 1 || FD->isVariadic())
615 return false;
616
617 // One of the standard new/new[]/delete/delete[] non-placement operators.
618 return true;
619}
620
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000621llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
622 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
623 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
624 //
625 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
626 //
627 // One of the possible flags is M_ZERO, which means 'give me back an
628 // allocation which is already zeroed', like calloc.
629
630 // 2-argument kmalloc(), as used in the Linux kernel:
631 //
632 // void *kmalloc(size_t size, gfp_t flags);
633 //
634 // Has the similar flag value __GFP_ZERO.
635
636 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
637 // code could be shared.
638
639 ASTContext &Ctx = C.getASTContext();
640 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
641
642 if (!KernelZeroFlagVal.hasValue()) {
643 if (OS == llvm::Triple::FreeBSD)
644 KernelZeroFlagVal = 0x0100;
645 else if (OS == llvm::Triple::NetBSD)
646 KernelZeroFlagVal = 0x0002;
647 else if (OS == llvm::Triple::OpenBSD)
648 KernelZeroFlagVal = 0x0008;
649 else if (OS == llvm::Triple::Linux)
650 // __GFP_ZERO
651 KernelZeroFlagVal = 0x8000;
652 else
653 // FIXME: We need a more general way of getting the M_ZERO value.
654 // See also: O_CREAT in UnixAPIChecker.cpp.
655
656 // Fall back to normal malloc behavior on platforms where we don't
657 // know M_ZERO.
658 return None;
659 }
660
661 // We treat the last argument as the flags argument, and callers fall-back to
662 // normal malloc on a None return. This works for the FreeBSD kernel malloc
663 // as well as Linux kmalloc.
664 if (CE->getNumArgs() < 2)
665 return None;
666
667 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
668 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
669 if (!V.getAs<NonLoc>()) {
670 // The case where 'V' can be a location can only be due to a bad header,
671 // so in this case bail out.
672 return None;
673 }
674
675 NonLoc Flags = V.castAs<NonLoc>();
676 NonLoc ZeroFlag = C.getSValBuilder()
677 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
678 .castAs<NonLoc>();
679 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
680 Flags, ZeroFlag,
681 FlagsEx->getType());
682 if (MaskedFlagsUC.isUnknownOrUndef())
683 return None;
684 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
685
686 // Check if maskedFlags is non-zero.
687 ProgramStateRef TrueState, FalseState;
688 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
689
690 // If M_ZERO is set, treat this like calloc (initialized).
691 if (TrueState && !FalseState) {
692 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
693 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
694 }
695
696 return None;
697}
698
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000699void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000700 if (C.wasInlined)
701 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000702
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000703 const FunctionDecl *FD = C.getCalleeDecl(CE);
704 if (!FD)
705 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000706
Anna Zaks40a7eb32012-02-22 19:24:52 +0000707 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000708 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000709
710 if (FD->getKind() == Decl::Function) {
711 initIdentifierInfo(C.getASTContext());
712 IdentifierInfo *FunI = FD->getIdentifier();
713
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000714 if (FunI == II_malloc) {
715 if (CE->getNumArgs() < 1)
716 return;
717 if (CE->getNumArgs() < 3) {
718 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
719 } else if (CE->getNumArgs() == 3) {
720 llvm::Optional<ProgramStateRef> MaybeState =
721 performKernelMalloc(CE, C, State);
722 if (MaybeState.hasValue())
723 State = MaybeState.getValue();
724 else
725 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
726 }
727 } else if (FunI == II_kmalloc) {
728 llvm::Optional<ProgramStateRef> MaybeState =
729 performKernelMalloc(CE, C, State);
730 if (MaybeState.hasValue())
731 State = MaybeState.getValue();
732 else
733 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
734 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000735 if (CE->getNumArgs() < 1)
736 return;
737 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
738 } else if (FunI == II_realloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000739 State = ReallocMem(C, CE, false, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000740 } else if (FunI == II_reallocf) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000741 State = ReallocMem(C, CE, true, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000742 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000743 State = CallocMem(C, CE, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000744 } else if (FunI == II_free) {
745 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
746 } else if (FunI == II_strdup) {
747 State = MallocUpdateRefState(C, CE, State);
748 } else if (FunI == II_strndup) {
749 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev13df0362013-03-25 01:35:45 +0000750 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000751 else if (isStandardNewDelete(FD, C.getASTContext())) {
752 // Process direct calls to operator new/new[]/delete/delete[] functions
753 // as distinct from new/new[]/delete/delete[] expressions that are
754 // processed by the checkPostStmt callbacks for CXXNewExpr and
755 // CXXDeleteExpr.
756 OverloadedOperatorKind K = FD->getOverloadedOperator();
757 if (K == OO_New)
758 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
759 AF_CXXNew);
760 else if (K == OO_Array_New)
761 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
762 AF_CXXNewArray);
763 else if (K == OO_Delete || K == OO_Array_Delete)
764 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
765 else
766 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000767 } else if (FunI == II_if_nameindex) {
768 // Should we model this differently? We can allocate a fixed number of
769 // elements with zeros in the last one.
770 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
771 AF_IfNameIndex);
772 } else if (FunI == II_if_freenameindex) {
773 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000774 }
775 }
776
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000777 if (ChecksEnabled[CK_MallocOptimistic] ||
778 ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000779 // Check all the attributes, if there are any.
780 // There can be multiple of these attributes.
781 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000782 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
783 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000784 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000785 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000786 break;
787 case OwnershipAttr::Takes:
788 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000789 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000790 break;
791 }
792 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000793 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000794 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000795}
796
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000797static QualType getDeepPointeeType(QualType T) {
798 QualType Result = T, PointeeType = T->getPointeeType();
799 while (!PointeeType.isNull()) {
800 Result = PointeeType;
801 PointeeType = PointeeType->getPointeeType();
802 }
803 return Result;
804}
805
806static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
807
808 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
809 if (!ConstructE)
810 return false;
811
812 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
813 return false;
814
815 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
816
817 // Iterate over the constructor parameters.
818 for (const auto *CtorParam : CtorD->params()) {
819
820 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
821 if (CtorParamPointeeT.isNull())
822 continue;
823
824 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
825
826 if (CtorParamPointeeT->getAsCXXRecordDecl())
827 return true;
828 }
829
830 return false;
831}
832
Anton Yartsev13df0362013-03-25 01:35:45 +0000833void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
834 CheckerContext &C) const {
835
836 if (NE->getNumPlacementArgs())
837 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
838 E = NE->placement_arg_end(); I != E; ++I)
839 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
840 checkUseAfterFree(Sym, C, *I);
841
Anton Yartsev13df0362013-03-25 01:35:45 +0000842 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
843 return;
844
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000845 ParentMap &PM = C.getLocationContext()->getParentMap();
846 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
847 return;
848
Anton Yartsev13df0362013-03-25 01:35:45 +0000849 ProgramStateRef State = C.getState();
850 // The return value from operator new is bound to a specified initialization
851 // value (if any) and we don't want to loose this value. So we call
852 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
853 // existing binding.
Anton Yartsev05789592013-03-28 17:05:19 +0000854 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
855 : AF_CXXNew);
Anton Yartsev13df0362013-03-25 01:35:45 +0000856 C.addTransition(State);
857}
858
859void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
860 CheckerContext &C) const {
861
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000862 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +0000863 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
864 checkUseAfterFree(Sym, C, DE->getArgument());
865
Anton Yartsev13df0362013-03-25 01:35:45 +0000866 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
867 return;
868
869 ProgramStateRef State = C.getState();
870 bool ReleasedAllocated;
871 State = FreeMemAux(C, DE->getArgument(), DE, State,
872 /*Hold*/false, ReleasedAllocated);
873
874 C.addTransition(State);
875}
876
Jordan Rose613f3c02013-03-09 00:59:10 +0000877static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
878 // If the first selector piece is one of the names below, assume that the
879 // object takes ownership of the memory, promising to eventually deallocate it
880 // with free().
881 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
882 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
883 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
884 if (FirstSlot == "dataWithBytesNoCopy" ||
885 FirstSlot == "initWithBytesNoCopy" ||
886 FirstSlot == "initWithCharactersNoCopy")
887 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000888
889 return false;
890}
891
Jordan Rose613f3c02013-03-09 00:59:10 +0000892static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
893 Selector S = Call.getSelector();
894
895 // FIXME: We should not rely on fully-constrained symbols being folded.
896 for (unsigned i = 1; i < S.getNumArgs(); ++i)
897 if (S.getNameForSlot(i).equals("freeWhenDone"))
898 return !Call.getArgSVal(i).isZeroConstant();
899
900 return None;
901}
902
Anna Zaks67291b92012-11-13 03:18:01 +0000903void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
904 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +0000905 if (C.wasInlined)
906 return;
907
Jordan Rose613f3c02013-03-09 00:59:10 +0000908 if (!isKnownDeallocObjCMethodName(Call))
909 return;
Anna Zaks67291b92012-11-13 03:18:01 +0000910
Jordan Rose613f3c02013-03-09 00:59:10 +0000911 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
912 if (!*FreeWhenDone)
913 return;
914
915 bool ReleasedAllocatedMemory;
916 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
917 Call.getOriginExpr(), C.getState(),
918 /*Hold=*/true, ReleasedAllocatedMemory,
919 /*RetNullOnFailure=*/true);
920
921 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +0000922}
923
Richard Smith852e9ce2013-11-27 01:46:48 +0000924ProgramStateRef
925MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000926 const OwnershipAttr *Att,
927 ProgramStateRef State) const {
928 if (!State)
929 return nullptr;
930
Richard Smith852e9ce2013-11-27 01:46:48 +0000931 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +0000932 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000933
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000934 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000935 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000936 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000937 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000938 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
939}
940
941ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
942 const CallExpr *CE,
943 const Expr *SizeEx, SVal Init,
944 ProgramStateRef State,
945 AllocationFamily Family) {
946 if (!State)
947 return nullptr;
948
949 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
950 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000951}
952
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000953ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000954 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000955 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000956 ProgramStateRef State,
957 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000958 if (!State)
959 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +0000960
Jordan Rosef69e65f2014-09-05 16:33:51 +0000961 // We expect the malloc functions to return a pointer.
962 if (!Loc::isLocType(CE->getType()))
963 return nullptr;
964
Anna Zaks3563fde2012-06-07 03:57:32 +0000965 // Bind the return value to the symbolic value from the heap region.
966 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
967 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +0000968 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +0000969 SValBuilder &svalBuilder = C.getSValBuilder();
970 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000971 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
972 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +0000973 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000974
Jordy Rose674bd552010-07-04 00:00:41 +0000975 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +0000976 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000977
Jordy Rose674bd552010-07-04 00:00:41 +0000978 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +0000979 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +0000980 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +0000981 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +0000982 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +0000983 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000984 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000985 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +0000986 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +0000987 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +0000988 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +0000989
Anton Yartsev05789592013-03-28 17:05:19 +0000990 State = State->assume(extentMatchesSize, true);
991 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +0000992 }
Ted Kremenek90af9092010-12-02 07:49:45 +0000993
Anton Yartsev05789592013-03-28 17:05:19 +0000994 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000995}
996
997ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +0000998 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +0000999 ProgramStateRef State,
1000 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001001 if (!State)
1002 return nullptr;
1003
Anna Zaks40a7eb32012-02-22 19:24:52 +00001004 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001005 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001006
1007 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001008 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001009 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001010
Ted Kremenek90af9092010-12-02 07:49:45 +00001011 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001012 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001013
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001014 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001015 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001016}
1017
Anna Zaks40a7eb32012-02-22 19:24:52 +00001018ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1019 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001020 const OwnershipAttr *Att,
1021 ProgramStateRef State) const {
1022 if (!State)
1023 return nullptr;
1024
Richard Smith852e9ce2013-11-27 01:46:48 +00001025 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001026 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001027
Anna Zaksfe6eb672012-08-24 02:28:20 +00001028 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001029
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001030 for (const auto &Arg : Att->args()) {
1031 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001032 Att->getOwnKind() == OwnershipAttr::Holds,
1033 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001034 if (StateI)
1035 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001036 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001037 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001038}
1039
Ted Kremenek49b1e382012-01-26 21:29:00 +00001040ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001041 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001042 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001043 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001044 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001045 bool &ReleasedAllocated,
1046 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001047 if (!State)
1048 return nullptr;
1049
Anna Zaksb508d292012-04-10 23:41:11 +00001050 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001051 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001052
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001053 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001054 ReleasedAllocated, ReturnsNullOnFailure);
1055}
1056
Anna Zaksa14c1d02012-11-13 19:47:40 +00001057/// Checks if the previous call to free on the given symbol failed - if free
1058/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001059static bool didPreviousFreeFail(ProgramStateRef State,
1060 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001061 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001062 if (Ret) {
1063 assert(*Ret && "We should not store the null return symbol");
1064 ConstraintManager &CMgr = State->getConstraintManager();
1065 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001066 RetStatusSymbol = *Ret;
1067 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001068 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001069 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001070}
1071
Anton Yartsev05789592013-03-28 17:05:19 +00001072AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001073 const Stmt *S) const {
1074 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001075 return AF_None;
1076
Anton Yartseve3377fb2013-04-04 23:46:29 +00001077 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001078 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001079
1080 if (!FD)
1081 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1082
Anton Yartsev05789592013-03-28 17:05:19 +00001083 ASTContext &Ctx = C.getASTContext();
1084
Anna Zaksd79b8402014-10-03 21:48:59 +00001085 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001086 return AF_Malloc;
1087
1088 if (isStandardNewDelete(FD, Ctx)) {
1089 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001090 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001091 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001092 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001093 return AF_CXXNewArray;
1094 }
1095
Anna Zaksd79b8402014-10-03 21:48:59 +00001096 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1097 return AF_IfNameIndex;
1098
Anton Yartsev05789592013-03-28 17:05:19 +00001099 return AF_None;
1100 }
1101
Anton Yartseve3377fb2013-04-04 23:46:29 +00001102 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1103 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1104
1105 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001106 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1107
Anton Yartseve3377fb2013-04-04 23:46:29 +00001108 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001109 return AF_Malloc;
1110
1111 return AF_None;
1112}
1113
1114bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1115 const Expr *E) const {
1116 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1117 // FIXME: This doesn't handle indirect calls.
1118 const FunctionDecl *FD = CE->getDirectCallee();
1119 if (!FD)
1120 return false;
1121
1122 os << *FD;
1123 if (!FD->isOverloadedOperator())
1124 os << "()";
1125 return true;
1126 }
1127
1128 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1129 if (Msg->isInstanceMessage())
1130 os << "-";
1131 else
1132 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001133 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001134 return true;
1135 }
1136
1137 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1138 os << "'"
1139 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1140 << "'";
1141 return true;
1142 }
1143
1144 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1145 os << "'"
1146 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1147 << "'";
1148 return true;
1149 }
1150
1151 return false;
1152}
1153
1154void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1155 const Expr *E) const {
1156 AllocationFamily Family = getAllocationFamily(C, E);
1157
1158 switch(Family) {
1159 case AF_Malloc: os << "malloc()"; return;
1160 case AF_CXXNew: os << "'new'"; return;
1161 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001162 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev05789592013-03-28 17:05:19 +00001163 case AF_None: llvm_unreachable("not a deallocation expression");
1164 }
1165}
1166
1167void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1168 AllocationFamily Family) const {
1169 switch(Family) {
1170 case AF_Malloc: os << "free()"; return;
1171 case AF_CXXNew: os << "'delete'"; return;
1172 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001173 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev05789592013-03-28 17:05:19 +00001174 case AF_None: llvm_unreachable("suspicious AF_None argument");
1175 }
1176}
1177
Anna Zaks0d6989b2012-06-22 02:04:31 +00001178ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1179 const Expr *ArgExpr,
1180 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001181 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001182 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001183 bool &ReleasedAllocated,
1184 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001185
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001186 if (!State)
1187 return nullptr;
1188
Anna Zaks67291b92012-11-13 03:18:01 +00001189 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001190 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001191 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001192 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001193
1194 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001195 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001196 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001197
Anna Zaksad01ef52012-02-14 00:26:13 +00001198 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001199 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001200 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001201 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001202 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001203
Jordy Rose3597b212010-06-07 19:32:37 +00001204 // Unknown values could easily be okay
1205 // Undefined values are handled elsewhere
1206 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001207 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001208
Jordy Rose3597b212010-06-07 19:32:37 +00001209 const MemRegion *R = ArgVal.getAsRegion();
1210
1211 // Nonlocs can't be freed, of course.
1212 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1213 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001214 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001215 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001216 }
1217
1218 R = R->StripCasts();
1219
1220 // Blocks might show up as heap data, but should not be free()d
1221 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001222 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001223 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001224 }
1225
1226 const MemSpaceRegion *MS = R->getMemorySpace();
1227
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001228 // Parameters, locals, statics, globals, and memory returned by alloca()
1229 // shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001230 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1231 // FIXME: at the time this code was written, malloc() regions were
1232 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1233 // This means that there isn't actually anything from HeapSpaceRegion
1234 // that should be freed, even though we allow it here.
1235 // Of course, free() can work on memory allocated outside the current
1236 // function, so UnknownSpaceRegion is always a possibility.
1237 // False negatives are better than false positives.
1238
Anton Yartsev05789592013-03-28 17:05:19 +00001239 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001240 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001241 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001242
1243 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001244 // Various cases could lead to non-symbol values here.
1245 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001246 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001247 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001248
Anna Zaksc89ad072013-02-07 23:05:47 +00001249 SymbolRef SymBase = SrBase->getSymbol();
1250 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001251 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001252
Anton Yartseve3377fb2013-04-04 23:46:29 +00001253 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001254
Anna Zaks93a21a82013-04-09 00:30:28 +00001255 // Check for double free first.
1256 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001257 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1258 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1259 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001260 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001261
Anna Zaks93a21a82013-04-09 00:30:28 +00001262 // If the pointer is allocated or escaped, but we are now trying to free it,
1263 // check that the call to free is proper.
1264 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1265
1266 // Check if an expected deallocation function matches the real one.
1267 bool DeallocMatchesAlloc =
1268 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1269 if (!DeallocMatchesAlloc) {
1270 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001271 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001272 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001273 }
1274
1275 // Check if the memory location being freed is the actual location
1276 // allocated, or an offset.
1277 RegionOffset Offset = R->getAsOffset();
1278 if (Offset.isValid() &&
1279 !Offset.hasSymbolicOffset() &&
1280 Offset.getOffset() != 0) {
1281 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1282 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1283 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001284 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001285 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001286 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001287 }
1288
Craig Topper0dbb7832014-05-27 02:45:47 +00001289 ReleasedAllocated = (RsBase != nullptr) && RsBase->isAllocated();
Anna Zaksfe6eb672012-08-24 02:28:20 +00001290
Anna Zaksa14c1d02012-11-13 19:47:40 +00001291 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001292 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001293
Anna Zaks67291b92012-11-13 03:18:01 +00001294 // Keep track of the return value. If it is NULL, we will know that free
1295 // failed.
1296 if (ReturnsNullOnFailure) {
1297 SVal RetVal = C.getSVal(ParentExpr);
1298 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1299 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001300 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1301 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001302 }
1303 }
1304
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001305 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1306 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001307 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001308 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001309 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001310 RefState::getRelinquished(Family,
1311 ParentExpr));
1312
1313 return State->set<RegionState>(SymBase,
1314 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001315}
1316
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001317Optional<MallocChecker::CheckKind>
Anton Yartseve5c0c142015-02-18 00:39:06 +00001318MallocChecker::getCheckIfTracked(MallocChecker::CheckKind CK,
1319 AllocationFamily Family) const {
1320
1321 if (CK == CK_NumCheckKinds || !ChecksEnabled[CK])
1322 return Optional<MallocChecker::CheckKind>();
1323
1324 // C/C++ checkers.
1325 if (CK == CK_MismatchedDeallocatorChecker)
1326 return CK;
1327
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001328 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001329 case AF_Malloc:
1330 case AF_IfNameIndex: {
Anton Yartseve5c0c142015-02-18 00:39:06 +00001331 // C checkers.
1332 if (CK == CK_MallocOptimistic ||
1333 CK == CK_MallocPessimistic) {
1334 return CK;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001335 }
1336 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001337 }
1338 case AF_CXXNew:
1339 case AF_CXXNewArray: {
Anton Yartseve5c0c142015-02-18 00:39:06 +00001340 // C++ checkers.
1341 if (CK == CK_NewDeleteChecker ||
1342 CK == CK_NewDeleteLeaksChecker) {
1343 return CK;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001344 }
1345 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001346 }
1347 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001348 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001349 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001350 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001351 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001352}
1353
Anton Yartseve5c0c142015-02-18 00:39:06 +00001354static MallocChecker::CKVecTy MakeVecFromCK(MallocChecker::CheckKind CK1,
1355 MallocChecker::CheckKind CK2 = MallocChecker::CK_NumCheckKinds,
1356 MallocChecker::CheckKind CK3 = MallocChecker::CK_NumCheckKinds,
1357 MallocChecker::CheckKind CK4 = MallocChecker::CK_NumCheckKinds) {
1358 MallocChecker::CKVecTy CKVec;
1359 CKVec.push_back(CK1);
1360 if (CK2 != MallocChecker::CK_NumCheckKinds) {
1361 CKVec.push_back(CK2);
1362 if (CK3 != MallocChecker::CK_NumCheckKinds) {
1363 CKVec.push_back(CK3);
1364 if (CK4 != MallocChecker::CK_NumCheckKinds)
1365 CKVec.push_back(CK4);
1366 }
1367 }
1368 return CKVec;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001369}
1370
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001371Optional<MallocChecker::CheckKind>
Anton Yartseve5c0c142015-02-18 00:39:06 +00001372MallocChecker::getCheckIfTracked(CKVecTy CKVec, AllocationFamily Family) const {
1373 for (auto CK: CKVec) {
1374 auto RetCK = getCheckIfTracked(CK, Family);
1375 if (RetCK.hasValue())
1376 return RetCK;
1377 }
1378 return Optional<MallocChecker::CheckKind>();
1379}
Anton Yartseve3377fb2013-04-04 23:46:29 +00001380
Anton Yartseve5c0c142015-02-18 00:39:06 +00001381Optional<MallocChecker::CheckKind>
1382MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
1383 const Stmt *AllocDeallocStmt) const {
1384 return getCheckIfTracked(CKVec, getAllocationFamily(C, AllocDeallocStmt));
1385}
1386
1387Optional<MallocChecker::CheckKind>
1388MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
1389 SymbolRef Sym) const {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001390 const RefState *RS = C.getState()->get<RegionState>(Sym);
1391 assert(RS);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001392 return getCheckIfTracked(CKVec, RS->getAllocationFamily());
Anton Yartseve3377fb2013-04-04 23:46:29 +00001393}
1394
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001395bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001396 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001397 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001398 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001399 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001400 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001401 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001402 else
1403 return false;
1404
1405 return true;
1406}
1407
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001408bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001409 const MemRegion *MR) {
1410 switch (MR->getKind()) {
1411 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001412 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001413 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001414 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001415 else
1416 os << "the address of a function";
1417 return true;
1418 }
1419 case MemRegion::BlockTextRegionKind:
1420 os << "block text";
1421 return true;
1422 case MemRegion::BlockDataRegionKind:
1423 // FIXME: where the block came from?
1424 os << "a block";
1425 return true;
1426 default: {
1427 const MemSpaceRegion *MS = MR->getMemorySpace();
1428
Anna Zaks8158ef02012-01-04 23:54:01 +00001429 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001430 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1431 const VarDecl *VD;
1432 if (VR)
1433 VD = VR->getDecl();
1434 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001435 VD = nullptr;
1436
Jordy Rose3597b212010-06-07 19:32:37 +00001437 if (VD)
1438 os << "the address of the local variable '" << VD->getName() << "'";
1439 else
1440 os << "the address of a local stack variable";
1441 return true;
1442 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001443
1444 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001445 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1446 const VarDecl *VD;
1447 if (VR)
1448 VD = VR->getDecl();
1449 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001450 VD = nullptr;
1451
Jordy Rose3597b212010-06-07 19:32:37 +00001452 if (VD)
1453 os << "the address of the parameter '" << VD->getName() << "'";
1454 else
1455 os << "the address of a parameter";
1456 return true;
1457 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001458
1459 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001460 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1461 const VarDecl *VD;
1462 if (VR)
1463 VD = VR->getDecl();
1464 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001465 VD = nullptr;
1466
Jordy Rose3597b212010-06-07 19:32:37 +00001467 if (VD) {
1468 if (VD->isStaticLocal())
1469 os << "the address of the static variable '" << VD->getName() << "'";
1470 else
1471 os << "the address of the global variable '" << VD->getName() << "'";
1472 } else
1473 os << "the address of a global variable";
1474 return true;
1475 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001476
1477 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001478 }
1479 }
1480}
1481
Anton Yartsev05789592013-03-28 17:05:19 +00001482void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1483 SourceRange Range,
1484 const Expr *DeallocExpr) const {
1485
Anton Yartseve5c0c142015-02-18 00:39:06 +00001486 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1487 CK_MallocPessimistic,
1488 CK_NewDeleteChecker),
1489 C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001490 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001491 return;
1492
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001493 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001494 if (!BT_BadFree[*CheckKind])
1495 BT_BadFree[*CheckKind].reset(
1496 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1497
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001498 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001499 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001500
Jordy Rose3597b212010-06-07 19:32:37 +00001501 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001502 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1503 MR = ER->getSuperRegion();
1504
1505 if (MR && isa<AllocaRegion>(MR))
1506 os << "Memory allocated by alloca() should not be deallocated";
1507 else {
1508 os << "Argument to ";
1509 if (!printAllocDeallocName(os, C, DeallocExpr))
1510 os << "deallocator";
1511
1512 os << " is ";
1513 bool Summarized = MR ? SummarizeRegion(os, MR)
1514 : SummarizeValue(os, ArgVal);
1515 if (Summarized)
1516 os << ", which is not memory allocated by ";
Jordy Rose3597b212010-06-07 19:32:37 +00001517 else
Anton Yartsev05789592013-03-28 17:05:19 +00001518 os << "not memory allocated by ";
1519
1520 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose3597b212010-06-07 19:32:37 +00001521 }
Anton Yartsev05789592013-03-28 17:05:19 +00001522
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001523 BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001524 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001525 R->addRange(Range);
Jordan Rosee10d5a72012-11-02 01:53:40 +00001526 C.emitReport(R);
Jordy Rose3597b212010-06-07 19:32:37 +00001527 }
1528}
1529
Anton Yartseve3377fb2013-04-04 23:46:29 +00001530void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1531 SourceRange Range,
1532 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001533 const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001534 SymbolRef Sym,
1535 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001536
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001537 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001538 return;
1539
1540 if (ExplodedNode *N = C.generateSink()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001541 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001542 BT_MismatchedDealloc.reset(
1543 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1544 "Bad deallocator", "Memory Error"));
1545
Anton Yartsev05789592013-03-28 17:05:19 +00001546 SmallString<100> buf;
1547 llvm::raw_svector_ostream os(buf);
1548
1549 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1550 SmallString<20> AllocBuf;
1551 llvm::raw_svector_ostream AllocOs(AllocBuf);
1552 SmallString<20> DeallocBuf;
1553 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1554
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001555 if (OwnershipTransferred) {
1556 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1557 os << DeallocOs.str() << " cannot";
1558 else
1559 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001560
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001561 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001562
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001563 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1564 os << " allocated by " << AllocOs.str();
1565 } else {
1566 os << "Memory";
1567 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1568 os << " allocated by " << AllocOs.str();
1569
1570 os << " should be deallocated by ";
1571 printExpectedDeallocName(os, RS->getAllocationFamily());
1572
1573 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1574 os << ", not " << DeallocOs.str();
1575 }
Anton Yartsev05789592013-03-28 17:05:19 +00001576
Anton Yartseve3377fb2013-04-04 23:46:29 +00001577 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001578 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001579 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001580 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev05789592013-03-28 17:05:19 +00001581 C.emitReport(R);
1582 }
1583}
1584
Anna Zaksc89ad072013-02-07 23:05:47 +00001585void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001586 SourceRange Range, const Expr *DeallocExpr,
1587 const Expr *AllocExpr) const {
1588
Anton Yartsev05789592013-03-28 17:05:19 +00001589
Anton Yartseve5c0c142015-02-18 00:39:06 +00001590 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1591 CK_MallocPessimistic,
1592 CK_NewDeleteChecker),
1593 C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001594 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001595 return;
1596
Anna Zaksc89ad072013-02-07 23:05:47 +00001597 ExplodedNode *N = C.generateSink();
Craig Topper0dbb7832014-05-27 02:45:47 +00001598 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001599 return;
1600
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001601 if (!BT_OffsetFree[*CheckKind])
1602 BT_OffsetFree[*CheckKind].reset(
1603 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001604
1605 SmallString<100> buf;
1606 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001607 SmallString<20> AllocNameBuf;
1608 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001609
1610 const MemRegion *MR = ArgVal.getAsRegion();
1611 assert(MR && "Only MemRegion based symbols can have offset free errors");
1612
1613 RegionOffset Offset = MR->getAsOffset();
1614 assert((Offset.isValid() &&
1615 !Offset.hasSymbolicOffset() &&
1616 Offset.getOffset() != 0) &&
1617 "Only symbols with a valid offset can have offset free errors");
1618
1619 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1620
Anton Yartsev05789592013-03-28 17:05:19 +00001621 os << "Argument to ";
1622 if (!printAllocDeallocName(os, C, DeallocExpr))
1623 os << "deallocator";
1624 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001625 << offsetBytes
1626 << " "
1627 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001628 << " from the start of ";
1629 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1630 os << "memory allocated by " << AllocNameOs.str();
1631 else
1632 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001633
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001634 BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001635 R->markInteresting(MR->getBaseRegion());
1636 R->addRange(Range);
1637 C.emitReport(R);
1638}
1639
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001640void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1641 SymbolRef Sym) const {
1642
Anton Yartseve5c0c142015-02-18 00:39:06 +00001643 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1644 CK_MallocPessimistic,
1645 CK_NewDeleteChecker),
1646 C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001647 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001648 return;
1649
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001650 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001651 if (!BT_UseFree[*CheckKind])
1652 BT_UseFree[*CheckKind].reset(new BugType(
1653 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001654
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001655 BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001656 "Use of memory after it is freed", N);
1657
1658 R->markInteresting(Sym);
1659 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001660 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001661 C.emitReport(R);
1662 }
1663}
1664
1665void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1666 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001667 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001668
Anton Yartseve5c0c142015-02-18 00:39:06 +00001669 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1670 CK_MallocPessimistic,
1671 CK_NewDeleteChecker),
1672 C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001673 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001674 return;
1675
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001676 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001677 if (!BT_DoubleFree[*CheckKind])
1678 BT_DoubleFree[*CheckKind].reset(
1679 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001680
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001681 BugReport *R =
1682 new BugReport(*BT_DoubleFree[*CheckKind],
1683 (Released ? "Attempt to free released memory"
1684 : "Attempt to free non-owned memory"),
1685 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001686 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001687 R->markInteresting(Sym);
1688 if (PrevSym)
1689 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001690 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001691 C.emitReport(R);
1692 }
1693}
1694
Jordan Rose656fdd52014-01-08 18:46:55 +00001695void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1696
Anton Yartseve5c0c142015-02-18 00:39:06 +00001697 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_NewDeleteChecker),
1698 C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001699 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001700 return;
1701
1702 if (ExplodedNode *N = C.generateSink()) {
1703 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001704 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1705 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001706
1707 BugReport *R = new BugReport(*BT_DoubleDelete,
1708 "Attempt to delete released memory", N);
1709
1710 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001711 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Jordan Rose656fdd52014-01-08 18:46:55 +00001712 C.emitReport(R);
1713 }
1714}
1715
Anna Zaks40a7eb32012-02-22 19:24:52 +00001716ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1717 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001718 bool FreesOnFail,
1719 ProgramStateRef State) const {
1720 if (!State)
1721 return nullptr;
1722
Anna Zaksb508d292012-04-10 23:41:11 +00001723 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001724 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001725
Ted Kremenek90af9092010-12-02 07:49:45 +00001726 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001727 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001728 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001729 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001730 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001731 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001732
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001733 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001734
Ted Kremenek90af9092010-12-02 07:49:45 +00001735 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001736 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001737
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001738 // Get the size argument. If there is no size arg then give up.
1739 const Expr *Arg1 = CE->getArg(1);
1740 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00001741 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001742
1743 // Get the value of the size argument.
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001744 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001745 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001746 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001747 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001748
1749 // Compare the size argument to 0.
1750 DefinedOrUnknownSVal SizeZero =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001751 svalBuilder.evalEQ(State, Arg1Val,
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001752 svalBuilder.makeIntValWithPtrWidth(0, false));
1753
Anna Zaksd56c8792012-02-13 18:05:39 +00001754 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001755 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001756 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001757 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001758 // We only assume exceptional states if they are definitely true; if the
1759 // state is under-constrained, assume regular realloc behavior.
1760 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1761 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1762
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001763 // If the ptr is NULL and the size is not 0, the call is equivalent to
1764 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001765 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001766 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001767 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001768 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001769 }
1770
Anna Zaksd56c8792012-02-13 18:05:39 +00001771 if (PrtIsNull && SizeIsZero)
Craig Topper0dbb7832014-05-27 02:45:47 +00001772 return nullptr;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001773
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001774 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001775 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001776 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001777 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001778 SymbolRef ToPtr = RetVal.getAsSymbol();
1779 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00001780 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00001781
Anna Zaksfe6eb672012-08-24 02:28:20 +00001782 bool ReleasedAllocated = false;
1783
Anna Zaksd56c8792012-02-13 18:05:39 +00001784 // If the size is 0, free the memory.
1785 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001786 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1787 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001788 // The semantics of the return value are:
1789 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001790 // to free() is returned. We just free the input pointer and do not add
1791 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001792 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001793 }
1794
1795 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001796 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001797 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00001798
Anna Zaksd56c8792012-02-13 18:05:39 +00001799 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1800 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001801 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001802 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001803
Anna Zaks75cfbb62012-09-12 22:57:34 +00001804 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1805 if (FreesOnFail)
1806 Kind = RPIsFreeOnFailure;
1807 else if (!ReleasedAllocated)
1808 Kind = RPDoNotTrackAfterFailure;
1809
Anna Zaksfe6eb672012-08-24 02:28:20 +00001810 // Record the info about the reallocated symbol so that we could properly
1811 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001812 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001813 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001814 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001815 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001816 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001817 }
Craig Topper0dbb7832014-05-27 02:45:47 +00001818 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001819}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001820
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001821ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
1822 ProgramStateRef State) {
1823 if (!State)
1824 return nullptr;
1825
Anna Zaksb508d292012-04-10 23:41:11 +00001826 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001827 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001828
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001829 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001830 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001831 SVal count = State->getSVal(CE->getArg(0), LCtx);
1832 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1833 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
Ted Kremenek90af9092010-12-02 07:49:45 +00001834 svalBuilder.getContext().getSizeType());
1835 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001836
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001837 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001838}
1839
Anna Zaksfc2e1532012-03-21 19:45:08 +00001840LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00001841MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1842 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00001843 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00001844 // Walk the ExplodedGraph backwards and find the first node that referred to
1845 // the tracked symbol.
1846 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001847 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00001848
1849 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00001850 ProgramStateRef State = N->getState();
1851 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00001852 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001853
1854 // Find the most recent expression bound to the symbol in the current
1855 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00001856 if (!ReferenceRegion) {
1857 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1858 SVal Val = State->getSVal(MR);
1859 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00001860 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00001861 // Do not show local variables belonging to a function other than
1862 // where the error is reported.
1863 if (!VR ||
1864 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1865 ReferenceRegion = MR;
1866 }
1867 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00001868 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00001869
Anna Zaks486a0ff2015-02-05 01:02:53 +00001870 // Allocation node, is the last node in the current or parent context in
1871 // which the symbol was tracked.
1872 const LocationContext *NContext = N->getLocationContext();
1873 if (NContext == LeakContext ||
1874 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00001875 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001876 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00001877 }
1878
Anna Zaksa043d0c2013-01-08 00:25:29 +00001879 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00001880}
1881
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001882void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1883 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001884
Anton Yartseve5c0c142015-02-18 00:39:06 +00001885 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1886 CK_MallocPessimistic,
1887 CK_NewDeleteLeaksChecker),
1888 C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001889 if (!CheckKind.hasValue())
Anton Yartsev6e499252013-04-05 02:25:02 +00001890 return;
1891
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001892 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001893 if (!BT_Leak[*CheckKind]) {
1894 BT_Leak[*CheckKind].reset(
1895 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001896 // Leaks should not be reported if they are post-dominated by a sink:
1897 // (1) Sinks are higher importance bugs.
1898 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1899 // with __noreturn functions such as assert() or exit(). We choose not
1900 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001901 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001902 }
1903
Anna Zaksdf901a42012-02-23 21:38:21 +00001904 // Most bug reports are cached at the location where they occurred.
1905 // With leaks, we want to unique them by the location where they were
1906 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00001907 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00001908 const ExplodedNode *AllocNode = nullptr;
1909 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001910 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Anna Zaksa043d0c2013-01-08 00:25:29 +00001911
1912 ProgramPoint P = AllocNode->getLocation();
Craig Topper0dbb7832014-05-27 02:45:47 +00001913 const Stmt *AllocationStmt = nullptr;
David Blaikie87396b92013-02-21 22:23:56 +00001914 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001915 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00001916 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001917 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00001918 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00001919 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1920 C.getSourceManager(),
1921 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00001922
Anna Zaksfc2e1532012-03-21 19:45:08 +00001923 SmallString<200> buf;
1924 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001925 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00001926 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001927 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00001928 } else {
1929 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00001930 }
1931
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001932 BugReport *R =
1933 new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1934 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00001935 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001936 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Jordan Rosee10d5a72012-11-02 01:53:40 +00001937 C.emitReport(R);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001938}
1939
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00001940void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1941 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00001942{
Zhongxing Xubce831f2010-08-15 08:19:57 +00001943 if (!SymReaper.hasDeadSymbols())
1944 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00001945
Ted Kremenek49b1e382012-01-26 21:29:00 +00001946 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001947 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00001948 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001949
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001950 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00001951 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1952 if (SymReaper.isDead(I->first)) {
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001953 if (I->second.isAllocated())
Anna Zaks78edc2f2012-02-09 06:48:19 +00001954 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00001955 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001956 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00001957
Zhongxing Xuc7460962009-11-13 07:48:11 +00001958 }
1959 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001960
Anna Zaksd56c8792012-02-13 18:05:39 +00001961 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00001962 ReallocPairsTy RP = state->get<ReallocPairs>();
1963 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00001964 if (SymReaper.isDead(I->first) ||
1965 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00001966 state = state->remove<ReallocPairs>(I->first);
1967 }
1968 }
1969
Anna Zaks67291b92012-11-13 03:18:01 +00001970 // Cleanup the FreeReturnValue Map.
1971 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1972 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1973 if (SymReaper.isDead(I->first) ||
1974 SymReaper.isDead(I->second)) {
1975 state = state->remove<FreeReturnValue>(I->first);
1976 }
1977 }
1978
Anna Zaksdf901a42012-02-23 21:38:21 +00001979 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001980 ExplodedNode *N = C.getPredecessor();
1981 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00001982 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001983 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper2341c0d2013-07-04 03:08:24 +00001984 for (SmallVectorImpl<SymbolRef>::iterator
1985 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001986 reportLeak(*I, N, C);
Anna Zaks78edc2f2012-02-09 06:48:19 +00001987 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001988 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001989
Anna Zaksdf901a42012-02-23 21:38:21 +00001990 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001991}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00001992
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001993void MallocChecker::checkPreCall(const CallEvent &Call,
1994 CheckerContext &C) const {
1995
Jordan Rose656fdd52014-01-08 18:46:55 +00001996 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
1997 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
1998 if (!Sym || checkDoubleDelete(Sym, C))
1999 return;
2000 }
2001
Anna Zaks46d01602012-05-18 01:16:10 +00002002 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002003 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2004 const FunctionDecl *FD = FC->getDecl();
2005 if (!FD)
2006 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002007
Anna Zaksd79b8402014-10-03 21:48:59 +00002008 ASTContext &Ctx = C.getASTContext();
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002009 if ((ChecksEnabled[CK_MallocOptimistic] ||
2010 ChecksEnabled[CK_MallocPessimistic]) &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002011 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2012 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2013 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002014 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002015
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002016 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002017 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002018 return;
2019 }
2020
2021 // Check if the callee of a method is deleted.
2022 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2023 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2024 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2025 return;
2026 }
2027
2028 // Check arguments for being used after free.
2029 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2030 SVal ArgSVal = Call.getArgSVal(I);
2031 if (ArgSVal.getAs<Loc>()) {
2032 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002033 if (!Sym)
2034 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002035 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002036 return;
2037 }
2038 }
2039}
2040
Anna Zaksa1b227b2012-02-08 23:16:56 +00002041void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2042 const Expr *E = S->getRetValue();
2043 if (!E)
2044 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002045
2046 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002047 ProgramStateRef State = C.getState();
2048 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002049 SymbolRef Sym = RetVal.getAsSymbol();
2050 if (!Sym)
2051 // If we are returning a field of the allocated struct or an array element,
2052 // the callee could still free the memory.
2053 // TODO: This logic should be a part of generic symbol escape callback.
2054 if (const MemRegion *MR = RetVal.getAsRegion())
2055 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2056 if (const SymbolicRegion *BMR =
2057 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2058 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002059
Anna Zaks3aa52252012-02-11 21:44:39 +00002060 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002061 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002062 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002063}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002064
Anna Zaks9fe80982012-03-22 00:57:20 +00002065// TODO: Blocks should be either inlined or should call invalidate regions
2066// upon invocation. After that's in place, special casing here will not be
2067// needed.
2068void MallocChecker::checkPostStmt(const BlockExpr *BE,
2069 CheckerContext &C) const {
2070
2071 // Scan the BlockDecRefExprs for any object the retain count checker
2072 // may be tracking.
2073 if (!BE->getBlockDecl()->hasCaptures())
2074 return;
2075
2076 ProgramStateRef state = C.getState();
2077 const BlockDataRegion *R =
2078 cast<BlockDataRegion>(state->getSVal(BE,
2079 C.getLocationContext()).getAsRegion());
2080
2081 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2082 E = R->referenced_vars_end();
2083
2084 if (I == E)
2085 return;
2086
2087 SmallVector<const MemRegion*, 10> Regions;
2088 const LocationContext *LC = C.getLocationContext();
2089 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2090
2091 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002092 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002093 if (VR->getSuperRegion() == R) {
2094 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2095 }
2096 Regions.push_back(VR);
2097 }
2098
2099 state =
2100 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2101 Regions.data() + Regions.size()).getState();
2102 C.addTransition(state);
2103}
2104
Anna Zaks46d01602012-05-18 01:16:10 +00002105bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002106 assert(Sym);
2107 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002108 return (RS && RS->isReleased());
2109}
2110
2111bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2112 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002113
Jordan Rose656fdd52014-01-08 18:46:55 +00002114 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002115 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2116 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002117 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002118
Anna Zaksa1b227b2012-02-08 23:16:56 +00002119 return false;
2120}
2121
Jordan Rose656fdd52014-01-08 18:46:55 +00002122bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2123
2124 if (isReleased(Sym, C)) {
2125 ReportDoubleDelete(C, Sym);
2126 return true;
2127 }
2128 return false;
2129}
2130
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002131// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002132void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2133 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002134 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaksa1b227b2012-02-08 23:16:56 +00002135 if (Sym)
Anna Zaks46d01602012-05-18 01:16:10 +00002136 checkUseAfterFree(Sym, C, S);
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002137}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002138
Anna Zaksbb1ef902012-02-11 21:02:35 +00002139// If a symbolic region is assumed to NULL (or another constant), stop tracking
2140// it - assuming that allocation failed on this path.
2141ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2142 SVal Cond,
2143 bool Assumption) const {
2144 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002145 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002146 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002147 ConstraintManager &CMgr = state->getConstraintManager();
2148 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2149 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002150 state = state->remove<RegionState>(I.getKey());
2151 }
2152
Anna Zaksd56c8792012-02-13 18:05:39 +00002153 // Realloc returns 0 when reallocation fails, which means that we should
2154 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002155 ReallocPairsTy RP = state->get<ReallocPairs>();
2156 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002157 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002158 ConstraintManager &CMgr = state->getConstraintManager();
2159 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002160 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002161 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002162
Anna Zaks75cfbb62012-09-12 22:57:34 +00002163 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2164 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2165 if (RS->isReleased()) {
2166 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002167 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002168 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002169 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2170 state = state->remove<RegionState>(ReallocSym);
2171 else
2172 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002173 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002174 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002175 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002176 }
2177
Anna Zaksbb1ef902012-02-11 21:02:35 +00002178 return state;
2179}
2180
Anna Zaks8ebeb642013-06-08 00:29:29 +00002181bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002182 const CallEvent *Call,
2183 ProgramStateRef State,
2184 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002185 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002186 EscapingSymbol = nullptr;
2187
Jordan Rose2a833ca2014-01-15 17:25:15 +00002188 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002189 // TODO: If we want to be more optimistic here, we'll need to make sure that
2190 // regions escape to C++ containers. They seem to do that even now, but for
2191 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002192 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002193 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002194
Jordan Rose742920c2012-07-02 19:27:35 +00002195 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002196 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002197 // If it's not a framework call, or if it takes a callback, assume it
2198 // can free memory.
2199 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002200 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002201
Jordan Rose613f3c02013-03-09 00:59:10 +00002202 // If it's a method we know about, handle it explicitly post-call.
2203 // This should happen before the "freeWhenDone" check below.
2204 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002205 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002206
Jordan Rose613f3c02013-03-09 00:59:10 +00002207 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2208 // about, we can't be sure that the object will use free() to deallocate the
2209 // memory, so we can't model it explicitly. The best we can do is use it to
2210 // decide whether the pointer escapes.
2211 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002212 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002213
Jordan Rose613f3c02013-03-09 00:59:10 +00002214 // If the first selector piece ends with "NoCopy", and there is no
2215 // "freeWhenDone" parameter set to zero, we know ownership is being
2216 // transferred. Again, though, we can't be sure that the object will use
2217 // free() to deallocate the memory, so we can't model it explicitly.
2218 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002219 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002220 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002221
Anna Zaks42908c72012-06-19 05:10:32 +00002222 // If the first selector starts with addPointer, insertPointer,
2223 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2224 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002225 // that the pointers get freed by following the container itself.
2226 if (FirstSlot.startswith("addPointer") ||
2227 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002228 FirstSlot.startswith("replacePointer") ||
2229 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002230 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002231 }
2232
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002233 // We should escape receiver on call to 'init'. This is especially relevant
2234 // to the receiver, as the corresponding symbol is usually not referenced
2235 // after the call.
2236 if (Msg->getMethodFamily() == OMF_init) {
2237 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2238 return true;
2239 }
Anna Zaks737926b2013-05-31 22:39:13 +00002240
Jordan Rose742920c2012-07-02 19:27:35 +00002241 // Otherwise, assume that the method does not free memory.
2242 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002243 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002244 }
2245
Jordan Rose742920c2012-07-02 19:27:35 +00002246 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002247 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002248 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002249 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002250
Jordan Rose742920c2012-07-02 19:27:35 +00002251 ASTContext &ASTC = State->getStateManager().getContext();
2252
2253 // If it's one of the allocation functions we can reason about, we model
2254 // its behavior explicitly.
2255 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002256 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002257
2258 // If it's not a system call, assume it frees memory.
2259 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002260 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002261
2262 // White list the system functions whose arguments escape.
2263 const IdentifierInfo *II = FD->getIdentifier();
2264 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002265 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002266 StringRef FName = II->getName();
2267
Jordan Rose742920c2012-07-02 19:27:35 +00002268 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose7ab01822012-07-02 19:27:51 +00002269 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002270 if (FName.endswith("NoCopy")) {
2271 // Look for the deallocator argument. We know that the memory ownership
2272 // is not transferred only if the deallocator argument is
2273 // 'kCFAllocatorNull'.
2274 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2275 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2276 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2277 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2278 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002279 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002280 }
2281 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002282 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002283 }
2284
Jordan Rose742920c2012-07-02 19:27:35 +00002285 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002286 // 'closefn' is specified (and if that function does free memory),
2287 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002288 // Currently, we do not inspect the 'closefn' function (PR12101).
2289 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002290 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002291 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002292
2293 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2294 // these leaks might be intentional when setting the buffer for stdio.
2295 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2296 if (FName == "setbuf" || FName =="setbuffer" ||
2297 FName == "setlinebuf" || FName == "setvbuf") {
2298 if (Call->getNumArgs() >= 1) {
2299 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2300 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2301 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2302 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002303 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002304 }
2305 }
2306
2307 // A bunch of other functions which either take ownership of a pointer or
2308 // wrap the result up in a struct or object, meaning it can be freed later.
2309 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2310 // but the Malloc checker cannot differentiate between them. The right way
2311 // of doing this would be to implement a pointer escapes callback.
2312 if (FName == "CGBitmapContextCreate" ||
2313 FName == "CGBitmapContextCreateWithData" ||
2314 FName == "CVPixelBufferCreateWithBytes" ||
2315 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2316 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002317 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002318 }
2319
Jordan Rose7ab01822012-07-02 19:27:51 +00002320 // Handle cases where we know a buffer's /address/ can escape.
2321 // Note that the above checks handle some special cases where we know that
2322 // even though the address escapes, it's still our responsibility to free the
2323 // buffer.
2324 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002325 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002326
2327 // Otherwise, assume that the function does not free memory.
2328 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002329 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002330}
2331
Anna Zaks333481b2013-03-28 23:15:29 +00002332static bool retTrue(const RefState *RS) {
2333 return true;
2334}
2335
2336static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2337 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2338 RS->getAllocationFamily() == AF_CXXNew);
2339}
2340
Anna Zaksdc154152012-12-20 00:38:25 +00002341ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2342 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002343 const CallEvent *Call,
2344 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002345 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2346}
2347
2348ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2349 const InvalidatedSymbols &Escaped,
2350 const CallEvent *Call,
2351 PointerEscapeKind Kind) const {
2352 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2353 &checkIfNewOrNewArrayFamily);
2354}
2355
2356ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2357 const InvalidatedSymbols &Escaped,
2358 const CallEvent *Call,
2359 PointerEscapeKind Kind,
2360 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002361 // If we know that the call does not free memory, or we want to process the
2362 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002363 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002364 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002365 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2366 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002367 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002368 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002369 }
Anna Zaks3d348342012-02-14 21:55:24 +00002370
Anna Zaksdc154152012-12-20 00:38:25 +00002371 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002372 E = Escaped.end();
2373 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002374 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002375
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002376 if (EscapingSymbol && EscapingSymbol != sym)
2377 continue;
2378
Anna Zaks0d6989b2012-06-22 02:04:31 +00002379 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks93a21a82013-04-09 00:30:28 +00002380 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002381 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002382 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2383 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002384 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002385 }
Anna Zaks3d348342012-02-14 21:55:24 +00002386 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002387}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002388
Jordy Rosebf38f202012-03-18 07:43:35 +00002389static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2390 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002391 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2392 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002393
Jordan Rose0c153cb2012-11-02 01:54:06 +00002394 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002395 I != E; ++I) {
2396 SymbolRef sym = I.getKey();
2397 if (!currMap.lookup(sym))
2398 return sym;
2399 }
2400
Craig Topper0dbb7832014-05-27 02:45:47 +00002401 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002402}
2403
Anna Zaks2b5bb972012-02-09 06:25:51 +00002404PathDiagnosticPiece *
2405MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2406 const ExplodedNode *PrevN,
2407 BugReporterContext &BRC,
2408 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002409 ProgramStateRef state = N->getState();
2410 ProgramStateRef statePrev = PrevN->getState();
2411
2412 const RefState *RS = state->get<RegionState>(Sym);
2413 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002414 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002415 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002416
Craig Topper0dbb7832014-05-27 02:45:47 +00002417 const Stmt *S = nullptr;
2418 const char *Msg = nullptr;
2419 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002420
2421 // Retrieve the associated statement.
2422 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002423 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002424 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002425 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002426 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002427 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002428 // If an assumption was made on a branch, it should be caught
2429 // here by looking at the state transition.
2430 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002431 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002432
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002433 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002434 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002435
Jordan Rose681cce92012-07-10 22:07:42 +00002436 // FIXME: We will eventually need to handle non-statement-based events
2437 // (__attribute__((cleanup))).
2438
Anna Zaks2b5bb972012-02-09 06:25:51 +00002439 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002440 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002441 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002442 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002443 StackHint = new StackHintGeneratorForSymbol(Sym,
2444 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002445 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002446 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002447 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002448 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002449 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002450 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002451 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002452 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002453 Mode = ReallocationFailed;
2454 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002455 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002456 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002457
Jordy Rose21ff76e2012-03-24 03:15:09 +00002458 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2459 // Is it possible to fail two reallocs WITHOUT testing in between?
2460 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2461 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002462 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002463 FailedReallocSymbol = sym;
2464 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002465 }
2466
2467 // We are in a special mode if a reallocation failed later in the path.
2468 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002469 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002470
Jordy Rose21ff76e2012-03-24 03:15:09 +00002471 // Is this is the first appearance of the reallocated symbol?
2472 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002473 // We're at the reallocation point.
2474 Msg = "Attempt to reallocate memory";
2475 StackHint = new StackHintGeneratorForSymbol(Sym,
2476 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002477 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002478 Mode = Normal;
2479 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002480 }
2481
Anna Zaks2b5bb972012-02-09 06:25:51 +00002482 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002483 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002484 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002485
2486 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002487 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002488 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002489 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002490}
2491
Anna Zaks263b7e02012-05-02 00:05:20 +00002492void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2493 const char *NL, const char *Sep) const {
2494
2495 RegionStateTy RS = State->get<RegionState>();
2496
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002497 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002498 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002499 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002500 const RefState *RefS = State->get<RegionState>(I.getKey());
2501 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartseve5c0c142015-02-18 00:39:06 +00002502 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
2503 CK_MallocPessimistic,
2504 CK_NewDeleteChecker),
2505 Family);
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002506 I.getKey()->dumpToStream(Out);
2507 Out << " : ";
2508 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002509 if (CheckKind.hasValue())
2510 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002511 Out << NL;
2512 }
2513 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002514}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002515
Anna Zakse4cfcd42013-04-16 00:22:55 +00002516void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2517 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002518 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2519 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2520 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2521 mgr.getCurrentCheckName();
Anna Zakse4cfcd42013-04-16 00:22:55 +00002522 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2523 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002524 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002525 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002526}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002527
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002528#define REGISTER_CHECKER(name) \
2529 void ento::register##name(CheckerManager &mgr) { \
2530 registerCStringCheckerBasic(mgr); \
2531 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2532 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2533 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2534 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002535
2536REGISTER_CHECKER(MallocPessimistic)
2537REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev13df0362013-03-25 01:35:45 +00002538REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002539REGISTER_CHECKER(MismatchedDeallocatorChecker)