blob: c2ace7b35db6fd9fdfb70d44c4efa428881d2541 [file] [log] [blame]
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines malloc/free checker, which checks for potential memory
11// leaks, double free, and use-after-free problems.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zakse56167e2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +000018#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/SourceManager.h"
Jordan Rose6b33c6f2014-03-26 17:05:46 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000023#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000029#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000030#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000032#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000033#include <climits>
34
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000035using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000036using namespace ento;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000037
38namespace {
39
Anton Yartsev05789592013-03-28 17:05:19 +000040// Used to check correspondence between allocators and deallocators.
41enum AllocationFamily {
42 AF_None,
43 AF_Malloc,
44 AF_CXXNew,
Anna Zaksd79b8402014-10-03 21:48:59 +000045 AF_CXXNewArray,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +000046 AF_IfNameIndex,
47 AF_Alloca
Anton Yartsev05789592013-03-28 17:05:19 +000048};
49
Zhongxing Xu1239de12009-12-11 00:55:44 +000050class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000051 enum Kind { // Reference to allocated memory.
52 Allocated,
53 // Reference to released/freed memory.
54 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000055 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000056 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000057 Relinquished,
58 // We are no longer guaranteed to have observed all manipulations
59 // of this pointer/memory. For example, it could have been
60 // passed as a parameter to an opaque function.
61 Escaped
62 };
Anton Yartsev05789592013-03-28 17:05:19 +000063
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000064 const Stmt *S;
Anton Yartsev05789592013-03-28 17:05:19 +000065 unsigned K : 2; // Kind enum, but stored as a bitfield.
66 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
67 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000068
Anton Yartsev05789592013-03-28 17:05:19 +000069 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000070 : S(s), K(k), Family(family) {
71 assert(family != AF_None);
72 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000073public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000074 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000075 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000076 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000077 bool isEscaped() const { return K == Escaped; }
78 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000079 return (AllocationFamily)Family;
80 }
Anna Zaksd56c8792012-02-13 18:05:39 +000081 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000082
83 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000084 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000085 }
86
Anton Yartsev05789592013-03-28 17:05:19 +000087 static RefState getAllocated(unsigned family, const Stmt *s) {
88 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000089 }
Anton Yartsev05789592013-03-28 17:05:19 +000090 static RefState getReleased(unsigned family, const Stmt *s) {
91 return RefState(Released, s, family);
92 }
93 static RefState getRelinquished(unsigned family, const Stmt *s) {
94 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +000095 }
Anna Zaks93a21a82013-04-09 00:30:28 +000096 static RefState getEscaped(const RefState *RS) {
97 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
98 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000099
100 void Profile(llvm::FoldingSetNodeID &ID) const {
101 ID.AddInteger(K);
102 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +0000103 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000104 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000105
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000106 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000107 switch (static_cast<Kind>(K)) {
108#define CASE(ID) case ID: OS << #ID; break;
109 CASE(Allocated)
110 CASE(Released)
111 CASE(Relinquished)
112 CASE(Escaped)
113 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000114 }
115
Alp Tokeref6b0072014-01-04 13:47:14 +0000116 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000117};
118
Anna Zaks75cfbb62012-09-12 22:57:34 +0000119enum ReallocPairKind {
120 RPToBeFreedAfterFailure,
121 // The symbol has been freed when reallocation failed.
122 RPIsFreeOnFailure,
123 // The symbol does not need to be freed after reallocation fails.
124 RPDoNotTrackAfterFailure
125};
126
Anna Zaksfe6eb672012-08-24 02:28:20 +0000127/// \class ReallocPair
128/// \brief Stores information about the symbol being reallocated by a call to
129/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000130struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000131 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000132 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000133 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000134
Anna Zaks75cfbb62012-09-12 22:57:34 +0000135 ReallocPair(SymbolRef S, ReallocPairKind K) :
136 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000137 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000138 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000139 ID.AddPointer(ReallocatedSym);
140 }
141 bool operator==(const ReallocPair &X) const {
142 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000143 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000144 }
145};
146
Anna Zaksa043d0c2013-01-08 00:25:29 +0000147typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000148
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000149class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000150 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000151 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000152 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000153 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000154 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000155 check::PostStmt<CXXNewExpr>,
156 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000157 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000158 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000159 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000160 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000161{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000162public:
Craig Topper0dbb7832014-05-27 02:45:47 +0000163 MallocChecker()
Anton Yartsevc38d7952015-03-03 22:58:46 +0000164 : II_alloca(nullptr), II_malloc(nullptr), II_free(nullptr),
165 II_realloc(nullptr), II_calloc(nullptr), II_valloc(nullptr),
166 II_reallocf(nullptr), II_strndup(nullptr), II_strdup(nullptr),
167 II_kmalloc(nullptr), II_if_nameindex(nullptr),
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000168 II_if_freenameindex(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000169
170 /// In pessimistic mode, the checker assumes that it does not know which
171 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000172 enum CheckKind {
173 CK_MallocPessimistic,
174 CK_MallocOptimistic,
175 CK_NewDeleteChecker,
176 CK_NewDeleteLeaksChecker,
177 CK_MismatchedDeallocatorChecker,
178 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000179 };
180
Anna Zaksd79b8402014-10-03 21:48:59 +0000181 enum class MemoryOperationKind {
182 MOK_Allocate,
183 MOK_Free,
184 MOK_Any
185 };
186
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000187 DefaultBool ChecksEnabled[CK_NumCheckKinds];
188 CheckName CheckNames[CK_NumCheckKinds];
Anton Yartseve5c0c142015-02-18 00:39:06 +0000189 typedef llvm::SmallVector<CheckKind, CK_NumCheckKinds> CKVecTy;
Anna Zakscd37bf42012-02-08 23:16:52 +0000190
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000191 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000192 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000193 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
194 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000195 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000196 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000197 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000198 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000199 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000200 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000201 void checkLocation(SVal l, bool isLoad, const Stmt *S,
202 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000203
204 ProgramStateRef checkPointerEscape(ProgramStateRef State,
205 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000206 const CallEvent *Call,
207 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000208 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
209 const InvalidatedSymbols &Escaped,
210 const CallEvent *Call,
211 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000212
Anna Zaks263b7e02012-05-02 00:05:20 +0000213 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000214 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000215
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000216private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000217 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
218 mutable std::unique_ptr<BugType> BT_DoubleDelete;
219 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
220 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
221 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000222 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000223 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
224 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevc38d7952015-03-03 22:58:46 +0000225 mutable IdentifierInfo *II_alloca, *II_malloc, *II_free, *II_realloc,
226 *II_calloc, *II_valloc, *II_reallocf, *II_strndup,
227 *II_strdup, *II_kmalloc, *II_if_nameindex,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000228 *II_if_freenameindex;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000229 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000230
Anna Zaks3d348342012-02-14 21:55:24 +0000231 void initIdentifierInfo(ASTContext &C) const;
232
Anton Yartsev05789592013-03-28 17:05:19 +0000233 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000234 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000235
236 /// \brief Print names of allocators and deallocators.
237 ///
238 /// \returns true on success.
239 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
240 const Expr *E) const;
241
242 /// \brief Print expected name of an allocator based on the deallocator's
243 /// family derived from the DeallocExpr.
244 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
245 const Expr *DeallocExpr) const;
246 /// \brief Print expected name of a deallocator based on the allocator's
247 /// family.
248 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
249
Jordan Rose613f3c02013-03-09 00:59:10 +0000250 ///@{
Anna Zaks3d348342012-02-14 21:55:24 +0000251 /// Check if this is one of the functions which can allocate/reallocate memory
252 /// pointed to by one of its arguments.
253 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000254 bool isCMemFunction(const FunctionDecl *FD,
255 ASTContext &C,
256 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000257 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000258 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000259 ///@}
Richard Smith852e9ce2013-11-27 01:46:48 +0000260 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
261 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000262 const OwnershipAttr* Att,
263 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000264 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000265 const Expr *SizeEx, SVal Init,
266 ProgramStateRef State,
267 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000268 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000269 SVal SizeEx, SVal Init,
270 ProgramStateRef State,
271 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000272
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000273 // Check if this malloc() for special flags. At present that means M_ZERO or
274 // __GFP_ZERO (in which case, treat it like calloc).
275 llvm::Optional<ProgramStateRef>
276 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
277 const ProgramStateRef &State) const;
278
Anna Zaks40a7eb32012-02-22 19:24:52 +0000279 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev05789592013-03-28 17:05:19 +0000280 static ProgramStateRef
281 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
282 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000283
284 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000285 const OwnershipAttr* Att,
286 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000287 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000288 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000289 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000290 bool &ReleasedAllocated,
291 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000292 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
293 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000294 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000295 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000296 bool &ReleasedAllocated,
297 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000298
Anna Zaks40a7eb32012-02-22 19:24:52 +0000299 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000300 bool FreesMemOnFailure,
301 ProgramStateRef State) const;
302 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
303 ProgramStateRef State);
Jordy Rose3597b212010-06-07 19:32:37 +0000304
Anna Zaks46d01602012-05-18 01:16:10 +0000305 ///\brief Check if the memory associated with this symbol was released.
306 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
307
Anton Yartsev13df0362013-03-25 01:35:45 +0000308 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000309
Jordan Rose656fdd52014-01-08 18:46:55 +0000310 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
311
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000312 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000313 /// "interesting" and should be modeled explicitly.
314 ///
Anna Zaks8ebeb642013-06-08 00:29:29 +0000315 /// \param [out] EscapingSymbol A function might not free memory in general,
316 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000317 /// returned and the single escaping symbol is returned through the out
318 /// parameter.
319 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000320 /// We assume that pointers do not escape through calls to system functions
321 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000322 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000323 ProgramStateRef State,
324 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000325
Anna Zaks333481b2013-03-28 23:15:29 +0000326 // Implementation of the checkPointerEscape callabcks.
327 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
328 const InvalidatedSymbols &Escaped,
329 const CallEvent *Call,
330 PointerEscapeKind Kind,
331 bool(*CheckRefState)(const RefState*)) const;
332
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000333 ///@{
334 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartseve5c0c142015-02-18 00:39:06 +0000335 /// Looks through incoming CheckKind(s) and returns the kind of the checker
336 /// responsible for this family/call/symbol.
337 Optional<CheckKind> getCheckIfTracked(CheckKind CK,
338 AllocationFamily Family) const;
339 Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec,
340 AllocationFamily Family) const;
341 Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000342 const Stmt *AllocDeallocStmt) const;
Anton Yartseve5c0c142015-02-18 00:39:06 +0000343 Optional<CheckKind> getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
344 SymbolRef Sym) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000345 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000346 static bool SummarizeValue(raw_ostream &os, SVal V);
347 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev05789592013-03-28 17:05:19 +0000348 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
349 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000350 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
351 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000352 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000353 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000354 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000355 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
356 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000357 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000358 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
359 SymbolRef Sym) const;
360 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000361 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000362
Jordan Rose656fdd52014-01-08 18:46:55 +0000363 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
364
Anna Zaksdf901a42012-02-23 21:38:21 +0000365 /// Find the location of the allocation for Sym on the path leading to the
366 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000367 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
368 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000369
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000370 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
371
Anna Zaks2b5bb972012-02-09 06:25:51 +0000372 /// The bug visitor which allows us to print extra diagnostics along the
373 /// BugReport path. For example, showing the allocation site of the leaked
374 /// region.
Jordy Rosef78877e2012-03-24 02:45:35 +0000375 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000376 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000377 enum NotificationMode {
378 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000379 ReallocationFailed
380 };
381
Anna Zaks2b5bb972012-02-09 06:25:51 +0000382 // The allocated region symbol tracked by the main analysis.
383 SymbolRef Sym;
384
Anna Zaks62cce9e2012-05-10 01:37:40 +0000385 // The mode we are in, i.e. what kind of diagnostics will be emitted.
386 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000387
Anna Zaks62cce9e2012-05-10 01:37:40 +0000388 // A symbol from when the primary region should have been reallocated.
389 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000390
Anna Zaks62cce9e2012-05-10 01:37:40 +0000391 bool IsLeak;
392
393 public:
394 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000395 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000396
Anna Zaks2b5bb972012-02-09 06:25:51 +0000397 virtual ~MallocBugVisitor() {}
398
Craig Topperfb6b25b2014-03-15 04:29:04 +0000399 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000400 static int X = 0;
401 ID.AddPointer(&X);
402 ID.AddPointer(Sym);
403 }
404
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000405 inline bool isAllocated(const RefState *S, const RefState *SPrev,
406 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000407 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000408 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000409 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000410 }
411
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000412 inline bool isReleased(const RefState *S, const RefState *SPrev,
413 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000414 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000415 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000416 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
417 }
418
Anna Zaks0d6989b2012-06-22 02:04:31 +0000419 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
420 const Stmt *Stmt) {
421 // Did not track -> relinquished. Other state (allocated) -> relinquished.
422 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
423 isa<ObjCPropertyRefExpr>(Stmt)) &&
424 (S && S->isRelinquished()) &&
425 (!SPrev || !SPrev->isRelinquished()));
426 }
427
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000428 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
429 const Stmt *Stmt) {
430 // If the expression is not a call, and the state change is
431 // released -> allocated, it must be the realloc return value
432 // check. If we have to handle more cases here, it might be cleaner just
433 // to track this extra bit in the state itself.
434 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
435 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000436 }
437
438 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
439 const ExplodedNode *PrevN,
440 BugReporterContext &BRC,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000441 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000442
David Blaikied15481c2014-08-29 18:18:43 +0000443 std::unique_ptr<PathDiagnosticPiece>
444 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
445 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000446 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000447 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000448
449 PathDiagnosticLocation L =
450 PathDiagnosticLocation::createEndOfPath(EndPathNode,
451 BRC.getSourceManager());
452 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000453 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
454 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000455 }
456
Anna Zakscba4f292012-03-16 23:24:20 +0000457 private:
458 class StackHintGeneratorForReallocationFailed
459 : public StackHintGeneratorForSymbol {
460 public:
461 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
462 : StackHintGeneratorForSymbol(S, M) {}
463
Craig Topperfb6b25b2014-03-15 04:29:04 +0000464 std::string getMessageForArg(const Expr *ArgE,
465 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000466 // Printed parameters start at 1, not 0.
467 ++ArgIndex;
468
Anna Zakscba4f292012-03-16 23:24:20 +0000469 SmallString<200> buf;
470 llvm::raw_svector_ostream os(buf);
471
Jordan Rosec102b352012-09-22 01:24:42 +0000472 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
473 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000474
475 return os.str();
476 }
477
Craig Topperfb6b25b2014-03-15 04:29:04 +0000478 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000479 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000480 }
481 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000482 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000483};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000484} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000485
Jordan Rose0c153cb2012-11-02 01:54:06 +0000486REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
487REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000488
Anna Zaks67291b92012-11-13 03:18:01 +0000489// A map from the freed symbol to the symbol representing the return value of
490// the free function.
491REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
492
Anna Zaksbb1ef902012-02-11 21:02:35 +0000493namespace {
494class StopTrackingCallback : public SymbolVisitor {
495 ProgramStateRef state;
496public:
497 StopTrackingCallback(ProgramStateRef st) : state(st) {}
498 ProgramStateRef getState() const { return state; }
499
Craig Topperfb6b25b2014-03-15 04:29:04 +0000500 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000501 state = state->remove<RegionState>(sym);
502 return true;
503 }
504};
505} // end anonymous namespace
506
Anna Zaks3d348342012-02-14 21:55:24 +0000507void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000508 if (II_malloc)
509 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000510 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000511 II_malloc = &Ctx.Idents.get("malloc");
512 II_free = &Ctx.Idents.get("free");
513 II_realloc = &Ctx.Idents.get("realloc");
514 II_reallocf = &Ctx.Idents.get("reallocf");
515 II_calloc = &Ctx.Idents.get("calloc");
516 II_valloc = &Ctx.Idents.get("valloc");
517 II_strdup = &Ctx.Idents.get("strdup");
518 II_strndup = &Ctx.Idents.get("strndup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000519 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000520 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
521 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000522}
523
Anna Zaks3d348342012-02-14 21:55:24 +0000524bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000525 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000526 return true;
527
Anna Zaksd79b8402014-10-03 21:48:59 +0000528 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000529 return true;
530
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000531 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
532 return true;
533
Anton Yartsev13df0362013-03-25 01:35:45 +0000534 if (isStandardNewDelete(FD, C))
535 return true;
536
Anna Zaks46d01602012-05-18 01:16:10 +0000537 return false;
538}
539
Anna Zaksd79b8402014-10-03 21:48:59 +0000540bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
541 ASTContext &C,
542 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000543 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000544 if (!FD)
545 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000546
Anna Zaksd79b8402014-10-03 21:48:59 +0000547 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
548 MemKind == MemoryOperationKind::MOK_Free);
549 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
550 MemKind == MemoryOperationKind::MOK_Allocate);
551
Jordan Rose6cd16c52012-07-10 23:13:01 +0000552 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000553 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000554 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000555
Anna Zaksd79b8402014-10-03 21:48:59 +0000556 if (Family == AF_Malloc && CheckFree) {
557 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
558 return true;
559 }
560
561 if (Family == AF_Malloc && CheckAlloc) {
562 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
563 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
564 FunI == II_strndup || FunI == II_kmalloc)
565 return true;
566 }
567
568 if (Family == AF_IfNameIndex && CheckFree) {
569 if (FunI == II_if_freenameindex)
570 return true;
571 }
572
573 if (Family == AF_IfNameIndex && CheckAlloc) {
574 if (FunI == II_if_nameindex)
575 return true;
576 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000577
578 if (Family == AF_Alloca && CheckAlloc) {
Anton Yartsevc38d7952015-03-03 22:58:46 +0000579 if (FunI == II_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000580 return true;
581 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000582 }
Anna Zaks3d348342012-02-14 21:55:24 +0000583
Anna Zaksd79b8402014-10-03 21:48:59 +0000584 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000585 return false;
586
Anna Zaksd79b8402014-10-03 21:48:59 +0000587 if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs()) {
588 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
589 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
590 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
591 if (CheckFree)
592 return true;
593 } else if (OwnKind == OwnershipAttr::Returns) {
594 if (CheckAlloc)
595 return true;
596 }
597 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000598 }
Anna Zaks3d348342012-02-14 21:55:24 +0000599
Anna Zaks3d348342012-02-14 21:55:24 +0000600 return false;
601}
602
Anton Yartsev8b662702013-03-28 16:10:38 +0000603// Tells if the callee is one of the following:
604// 1) A global non-placement new/delete operator function.
605// 2) A global placement operator function with the single placement argument
606// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000607bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
608 ASTContext &C) const {
609 if (!FD)
610 return false;
611
612 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
613 if (Kind != OO_New && Kind != OO_Array_New &&
614 Kind != OO_Delete && Kind != OO_Array_Delete)
615 return false;
616
Anton Yartsev8b662702013-03-28 16:10:38 +0000617 // Skip all operator new/delete methods.
618 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000619 return false;
620
621 // Return true if tested operator is a standard placement nothrow operator.
622 if (FD->getNumParams() == 2) {
623 QualType T = FD->getParamDecl(1)->getType();
624 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
625 return II->getName().equals("nothrow_t");
626 }
627
628 // Skip placement operators.
629 if (FD->getNumParams() != 1 || FD->isVariadic())
630 return false;
631
632 // One of the standard new/new[]/delete/delete[] non-placement operators.
633 return true;
634}
635
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000636llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
637 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
638 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
639 //
640 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
641 //
642 // One of the possible flags is M_ZERO, which means 'give me back an
643 // allocation which is already zeroed', like calloc.
644
645 // 2-argument kmalloc(), as used in the Linux kernel:
646 //
647 // void *kmalloc(size_t size, gfp_t flags);
648 //
649 // Has the similar flag value __GFP_ZERO.
650
651 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
652 // code could be shared.
653
654 ASTContext &Ctx = C.getASTContext();
655 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
656
657 if (!KernelZeroFlagVal.hasValue()) {
658 if (OS == llvm::Triple::FreeBSD)
659 KernelZeroFlagVal = 0x0100;
660 else if (OS == llvm::Triple::NetBSD)
661 KernelZeroFlagVal = 0x0002;
662 else if (OS == llvm::Triple::OpenBSD)
663 KernelZeroFlagVal = 0x0008;
664 else if (OS == llvm::Triple::Linux)
665 // __GFP_ZERO
666 KernelZeroFlagVal = 0x8000;
667 else
668 // FIXME: We need a more general way of getting the M_ZERO value.
669 // See also: O_CREAT in UnixAPIChecker.cpp.
670
671 // Fall back to normal malloc behavior on platforms where we don't
672 // know M_ZERO.
673 return None;
674 }
675
676 // We treat the last argument as the flags argument, and callers fall-back to
677 // normal malloc on a None return. This works for the FreeBSD kernel malloc
678 // as well as Linux kmalloc.
679 if (CE->getNumArgs() < 2)
680 return None;
681
682 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
683 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
684 if (!V.getAs<NonLoc>()) {
685 // The case where 'V' can be a location can only be due to a bad header,
686 // so in this case bail out.
687 return None;
688 }
689
690 NonLoc Flags = V.castAs<NonLoc>();
691 NonLoc ZeroFlag = C.getSValBuilder()
692 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
693 .castAs<NonLoc>();
694 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
695 Flags, ZeroFlag,
696 FlagsEx->getType());
697 if (MaskedFlagsUC.isUnknownOrUndef())
698 return None;
699 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
700
701 // Check if maskedFlags is non-zero.
702 ProgramStateRef TrueState, FalseState;
703 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
704
705 // If M_ZERO is set, treat this like calloc (initialized).
706 if (TrueState && !FalseState) {
707 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
708 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
709 }
710
711 return None;
712}
713
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000714void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000715 if (C.wasInlined)
716 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000717
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000718 const FunctionDecl *FD = C.getCalleeDecl(CE);
719 if (!FD)
720 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000721
Anna Zaks40a7eb32012-02-22 19:24:52 +0000722 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000723 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000724
725 if (FD->getKind() == Decl::Function) {
726 initIdentifierInfo(C.getASTContext());
727 IdentifierInfo *FunI = FD->getIdentifier();
728
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000729 if (FunI == II_malloc) {
730 if (CE->getNumArgs() < 1)
731 return;
732 if (CE->getNumArgs() < 3) {
733 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
734 } else if (CE->getNumArgs() == 3) {
735 llvm::Optional<ProgramStateRef> MaybeState =
736 performKernelMalloc(CE, C, State);
737 if (MaybeState.hasValue())
738 State = MaybeState.getValue();
739 else
740 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
741 }
742 } else if (FunI == II_kmalloc) {
743 llvm::Optional<ProgramStateRef> MaybeState =
744 performKernelMalloc(CE, C, State);
745 if (MaybeState.hasValue())
746 State = MaybeState.getValue();
747 else
748 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
749 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000750 if (CE->getNumArgs() < 1)
751 return;
752 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
753 } else if (FunI == II_realloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000754 State = ReallocMem(C, CE, false, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000755 } else if (FunI == II_reallocf) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000756 State = ReallocMem(C, CE, true, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000757 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000758 State = CallocMem(C, CE, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000759 } else if (FunI == II_free) {
760 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
761 } else if (FunI == II_strdup) {
762 State = MallocUpdateRefState(C, CE, State);
763 } else if (FunI == II_strndup) {
764 State = MallocUpdateRefState(C, CE, State);
Anton Yartsevc38d7952015-03-03 22:58:46 +0000765 } else if (FunI == II_alloca) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000766 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
767 AF_Alloca);
768 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000769 // Process direct calls to operator new/new[]/delete/delete[] functions
770 // as distinct from new/new[]/delete/delete[] expressions that are
771 // processed by the checkPostStmt callbacks for CXXNewExpr and
772 // CXXDeleteExpr.
773 OverloadedOperatorKind K = FD->getOverloadedOperator();
774 if (K == OO_New)
775 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
776 AF_CXXNew);
777 else if (K == OO_Array_New)
778 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
779 AF_CXXNewArray);
780 else if (K == OO_Delete || K == OO_Array_Delete)
781 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
782 else
783 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000784 } else if (FunI == II_if_nameindex) {
785 // Should we model this differently? We can allocate a fixed number of
786 // elements with zeros in the last one.
787 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
788 AF_IfNameIndex);
789 } else if (FunI == II_if_freenameindex) {
790 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000791 }
792 }
793
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000794 if (ChecksEnabled[CK_MallocOptimistic] ||
795 ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000796 // Check all the attributes, if there are any.
797 // There can be multiple of these attributes.
798 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000799 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
800 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000801 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000802 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000803 break;
804 case OwnershipAttr::Takes:
805 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000806 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000807 break;
808 }
809 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000810 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000811 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000812}
813
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000814static QualType getDeepPointeeType(QualType T) {
815 QualType Result = T, PointeeType = T->getPointeeType();
816 while (!PointeeType.isNull()) {
817 Result = PointeeType;
818 PointeeType = PointeeType->getPointeeType();
819 }
820 return Result;
821}
822
823static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
824
825 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
826 if (!ConstructE)
827 return false;
828
829 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
830 return false;
831
832 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
833
834 // Iterate over the constructor parameters.
835 for (const auto *CtorParam : CtorD->params()) {
836
837 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
838 if (CtorParamPointeeT.isNull())
839 continue;
840
841 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
842
843 if (CtorParamPointeeT->getAsCXXRecordDecl())
844 return true;
845 }
846
847 return false;
848}
849
Anton Yartsev13df0362013-03-25 01:35:45 +0000850void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
851 CheckerContext &C) const {
852
853 if (NE->getNumPlacementArgs())
854 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
855 E = NE->placement_arg_end(); I != E; ++I)
856 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
857 checkUseAfterFree(Sym, C, *I);
858
Anton Yartsev13df0362013-03-25 01:35:45 +0000859 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
860 return;
861
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000862 ParentMap &PM = C.getLocationContext()->getParentMap();
863 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
864 return;
865
Anton Yartsev13df0362013-03-25 01:35:45 +0000866 ProgramStateRef State = C.getState();
867 // The return value from operator new is bound to a specified initialization
868 // value (if any) and we don't want to loose this value. So we call
869 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
870 // existing binding.
Anton Yartsev05789592013-03-28 17:05:19 +0000871 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
872 : AF_CXXNew);
Anton Yartsev13df0362013-03-25 01:35:45 +0000873 C.addTransition(State);
874}
875
876void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
877 CheckerContext &C) const {
878
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000879 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +0000880 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
881 checkUseAfterFree(Sym, C, DE->getArgument());
882
Anton Yartsev13df0362013-03-25 01:35:45 +0000883 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
884 return;
885
886 ProgramStateRef State = C.getState();
887 bool ReleasedAllocated;
888 State = FreeMemAux(C, DE->getArgument(), DE, State,
889 /*Hold*/false, ReleasedAllocated);
890
891 C.addTransition(State);
892}
893
Jordan Rose613f3c02013-03-09 00:59:10 +0000894static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
895 // If the first selector piece is one of the names below, assume that the
896 // object takes ownership of the memory, promising to eventually deallocate it
897 // with free().
898 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
899 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
900 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
901 if (FirstSlot == "dataWithBytesNoCopy" ||
902 FirstSlot == "initWithBytesNoCopy" ||
903 FirstSlot == "initWithCharactersNoCopy")
904 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000905
906 return false;
907}
908
Jordan Rose613f3c02013-03-09 00:59:10 +0000909static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
910 Selector S = Call.getSelector();
911
912 // FIXME: We should not rely on fully-constrained symbols being folded.
913 for (unsigned i = 1; i < S.getNumArgs(); ++i)
914 if (S.getNameForSlot(i).equals("freeWhenDone"))
915 return !Call.getArgSVal(i).isZeroConstant();
916
917 return None;
918}
919
Anna Zaks67291b92012-11-13 03:18:01 +0000920void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
921 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +0000922 if (C.wasInlined)
923 return;
924
Jordan Rose613f3c02013-03-09 00:59:10 +0000925 if (!isKnownDeallocObjCMethodName(Call))
926 return;
Anna Zaks67291b92012-11-13 03:18:01 +0000927
Jordan Rose613f3c02013-03-09 00:59:10 +0000928 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
929 if (!*FreeWhenDone)
930 return;
931
932 bool ReleasedAllocatedMemory;
933 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
934 Call.getOriginExpr(), C.getState(),
935 /*Hold=*/true, ReleasedAllocatedMemory,
936 /*RetNullOnFailure=*/true);
937
938 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +0000939}
940
Richard Smith852e9ce2013-11-27 01:46:48 +0000941ProgramStateRef
942MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000943 const OwnershipAttr *Att,
944 ProgramStateRef State) const {
945 if (!State)
946 return nullptr;
947
Richard Smith852e9ce2013-11-27 01:46:48 +0000948 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +0000949 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000950
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000951 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000952 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000953 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000954 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000955 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
956}
957
958ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
959 const CallExpr *CE,
960 const Expr *SizeEx, SVal Init,
961 ProgramStateRef State,
962 AllocationFamily Family) {
963 if (!State)
964 return nullptr;
965
966 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
967 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000968}
969
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000970ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000971 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000972 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000973 ProgramStateRef State,
974 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000975 if (!State)
976 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +0000977
Jordan Rosef69e65f2014-09-05 16:33:51 +0000978 // We expect the malloc functions to return a pointer.
979 if (!Loc::isLocType(CE->getType()))
980 return nullptr;
981
Anna Zaks3563fde2012-06-07 03:57:32 +0000982 // Bind the return value to the symbolic value from the heap region.
983 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
984 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +0000985 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +0000986 SValBuilder &svalBuilder = C.getSValBuilder();
987 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000988 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
989 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +0000990 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000991
Jordy Rose674bd552010-07-04 00:00:41 +0000992 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +0000993 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000994
Jordy Rose674bd552010-07-04 00:00:41 +0000995 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +0000996 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +0000997 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +0000998 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +0000999 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +00001000 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +00001001 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001002 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001003 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001004 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001005 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001006
Anton Yartsev05789592013-03-28 17:05:19 +00001007 State = State->assume(extentMatchesSize, true);
1008 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001009 }
Ted Kremenek90af9092010-12-02 07:49:45 +00001010
Anton Yartsev05789592013-03-28 17:05:19 +00001011 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001012}
1013
1014ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001015 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001016 ProgramStateRef State,
1017 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001018 if (!State)
1019 return nullptr;
1020
Anna Zaks40a7eb32012-02-22 19:24:52 +00001021 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001022 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001023
1024 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001025 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001026 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001027
Ted Kremenek90af9092010-12-02 07:49:45 +00001028 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001029 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001030
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001031 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001032 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001033}
1034
Anna Zaks40a7eb32012-02-22 19:24:52 +00001035ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1036 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001037 const OwnershipAttr *Att,
1038 ProgramStateRef State) const {
1039 if (!State)
1040 return nullptr;
1041
Richard Smith852e9ce2013-11-27 01:46:48 +00001042 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001043 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001044
Anna Zaksfe6eb672012-08-24 02:28:20 +00001045 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001046
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001047 for (const auto &Arg : Att->args()) {
1048 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001049 Att->getOwnKind() == OwnershipAttr::Holds,
1050 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001051 if (StateI)
1052 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001053 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001054 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001055}
1056
Ted Kremenek49b1e382012-01-26 21:29:00 +00001057ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001058 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001059 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001060 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001061 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001062 bool &ReleasedAllocated,
1063 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001064 if (!State)
1065 return nullptr;
1066
Anna Zaksb508d292012-04-10 23:41:11 +00001067 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001068 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001069
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001070 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001071 ReleasedAllocated, ReturnsNullOnFailure);
1072}
1073
Anna Zaksa14c1d02012-11-13 19:47:40 +00001074/// Checks if the previous call to free on the given symbol failed - if free
1075/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001076static bool didPreviousFreeFail(ProgramStateRef State,
1077 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001078 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001079 if (Ret) {
1080 assert(*Ret && "We should not store the null return symbol");
1081 ConstraintManager &CMgr = State->getConstraintManager();
1082 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001083 RetStatusSymbol = *Ret;
1084 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001085 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001086 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001087}
1088
Anton Yartsev05789592013-03-28 17:05:19 +00001089AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001090 const Stmt *S) const {
1091 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001092 return AF_None;
1093
Anton Yartseve3377fb2013-04-04 23:46:29 +00001094 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001095 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001096
1097 if (!FD)
1098 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1099
Anton Yartsev05789592013-03-28 17:05:19 +00001100 ASTContext &Ctx = C.getASTContext();
1101
Anna Zaksd79b8402014-10-03 21:48:59 +00001102 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001103 return AF_Malloc;
1104
1105 if (isStandardNewDelete(FD, Ctx)) {
1106 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001107 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001108 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001109 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001110 return AF_CXXNewArray;
1111 }
1112
Anna Zaksd79b8402014-10-03 21:48:59 +00001113 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1114 return AF_IfNameIndex;
1115
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001116 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1117 return AF_Alloca;
1118
Anton Yartsev05789592013-03-28 17:05:19 +00001119 return AF_None;
1120 }
1121
Anton Yartseve3377fb2013-04-04 23:46:29 +00001122 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1123 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1124
1125 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001126 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1127
Anton Yartseve3377fb2013-04-04 23:46:29 +00001128 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001129 return AF_Malloc;
1130
1131 return AF_None;
1132}
1133
1134bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1135 const Expr *E) const {
1136 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1137 // FIXME: This doesn't handle indirect calls.
1138 const FunctionDecl *FD = CE->getDirectCallee();
1139 if (!FD)
1140 return false;
1141
1142 os << *FD;
1143 if (!FD->isOverloadedOperator())
1144 os << "()";
1145 return true;
1146 }
1147
1148 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1149 if (Msg->isInstanceMessage())
1150 os << "-";
1151 else
1152 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001153 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001154 return true;
1155 }
1156
1157 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1158 os << "'"
1159 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1160 << "'";
1161 return true;
1162 }
1163
1164 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1165 os << "'"
1166 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1167 << "'";
1168 return true;
1169 }
1170
1171 return false;
1172}
1173
1174void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1175 const Expr *E) const {
1176 AllocationFamily Family = getAllocationFamily(C, E);
1177
1178 switch(Family) {
1179 case AF_Malloc: os << "malloc()"; return;
1180 case AF_CXXNew: os << "'new'"; return;
1181 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001182 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001183 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001184 case AF_None: llvm_unreachable("not a deallocation expression");
1185 }
1186}
1187
1188void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1189 AllocationFamily Family) const {
1190 switch(Family) {
1191 case AF_Malloc: os << "free()"; return;
1192 case AF_CXXNew: os << "'delete'"; return;
1193 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001194 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001195 case AF_Alloca:
1196 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001197 }
1198}
1199
Anna Zaks0d6989b2012-06-22 02:04:31 +00001200ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1201 const Expr *ArgExpr,
1202 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001203 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001204 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001205 bool &ReleasedAllocated,
1206 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001207
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001208 if (!State)
1209 return nullptr;
1210
Anna Zaks67291b92012-11-13 03:18:01 +00001211 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001212 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001213 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001214 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001215
1216 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001217 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001218 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001219
Anna Zaksad01ef52012-02-14 00:26:13 +00001220 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001221 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001222 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001223 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001224 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001225
Jordy Rose3597b212010-06-07 19:32:37 +00001226 // Unknown values could easily be okay
1227 // Undefined values are handled elsewhere
1228 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001229 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001230
Jordy Rose3597b212010-06-07 19:32:37 +00001231 const MemRegion *R = ArgVal.getAsRegion();
1232
1233 // Nonlocs can't be freed, of course.
1234 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1235 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001236 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001237 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001238 }
1239
1240 R = R->StripCasts();
1241
1242 // Blocks might show up as heap data, but should not be free()d
1243 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001244 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001245 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001246 }
1247
1248 const MemSpaceRegion *MS = R->getMemorySpace();
1249
Anton Yartsevc38d7952015-03-03 22:58:46 +00001250 // Parameters, locals, statics, globals, and memory returned by
1251 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001252 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1253 // FIXME: at the time this code was written, malloc() regions were
1254 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1255 // This means that there isn't actually anything from HeapSpaceRegion
1256 // that should be freed, even though we allow it here.
1257 // Of course, free() can work on memory allocated outside the current
1258 // function, so UnknownSpaceRegion is always a possibility.
1259 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001260
1261 if (isa<AllocaRegion>(R))
1262 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1263 else
1264 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1265
Craig Topper0dbb7832014-05-27 02:45:47 +00001266 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001267 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001268
1269 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001270 // Various cases could lead to non-symbol values here.
1271 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001272 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001273 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001274
Anna Zaksc89ad072013-02-07 23:05:47 +00001275 SymbolRef SymBase = SrBase->getSymbol();
1276 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001277 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001278
Anton Yartseve3377fb2013-04-04 23:46:29 +00001279 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001280
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001281 // Memory returned by alloca() shouldn't be freed.
1282 if (RsBase->getAllocationFamily() == AF_Alloca) {
1283 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1284 return nullptr;
1285 }
1286
Anna Zaks93a21a82013-04-09 00:30:28 +00001287 // Check for double free first.
1288 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001289 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1290 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1291 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001292 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001293
Anna Zaks93a21a82013-04-09 00:30:28 +00001294 // If the pointer is allocated or escaped, but we are now trying to free it,
1295 // check that the call to free is proper.
1296 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1297
1298 // Check if an expected deallocation function matches the real one.
1299 bool DeallocMatchesAlloc =
1300 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1301 if (!DeallocMatchesAlloc) {
1302 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001303 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001304 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001305 }
1306
1307 // Check if the memory location being freed is the actual location
1308 // allocated, or an offset.
1309 RegionOffset Offset = R->getAsOffset();
1310 if (Offset.isValid() &&
1311 !Offset.hasSymbolicOffset() &&
1312 Offset.getOffset() != 0) {
1313 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1314 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1315 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001316 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001317 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001318 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001319 }
1320
Craig Topper0dbb7832014-05-27 02:45:47 +00001321 ReleasedAllocated = (RsBase != nullptr) && RsBase->isAllocated();
Anna Zaksfe6eb672012-08-24 02:28:20 +00001322
Anna Zaksa14c1d02012-11-13 19:47:40 +00001323 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001324 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001325
Anna Zaks67291b92012-11-13 03:18:01 +00001326 // Keep track of the return value. If it is NULL, we will know that free
1327 // failed.
1328 if (ReturnsNullOnFailure) {
1329 SVal RetVal = C.getSVal(ParentExpr);
1330 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1331 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001332 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1333 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001334 }
1335 }
1336
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001337 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1338 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001339 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001340 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001341 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001342 RefState::getRelinquished(Family,
1343 ParentExpr));
1344
1345 return State->set<RegionState>(SymBase,
1346 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001347}
1348
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001349Optional<MallocChecker::CheckKind>
Anton Yartseve5c0c142015-02-18 00:39:06 +00001350MallocChecker::getCheckIfTracked(MallocChecker::CheckKind CK,
1351 AllocationFamily Family) const {
1352
1353 if (CK == CK_NumCheckKinds || !ChecksEnabled[CK])
1354 return Optional<MallocChecker::CheckKind>();
1355
1356 // C/C++ checkers.
1357 if (CK == CK_MismatchedDeallocatorChecker)
1358 return CK;
1359
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001360 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001361 case AF_Malloc:
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001362 case AF_IfNameIndex:
1363 case AF_Alloca: {
Anton Yartseve5c0c142015-02-18 00:39:06 +00001364 // C checkers.
1365 if (CK == CK_MallocOptimistic ||
1366 CK == CK_MallocPessimistic) {
1367 return CK;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001368 }
1369 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001370 }
1371 case AF_CXXNew:
1372 case AF_CXXNewArray: {
Anton Yartseve5c0c142015-02-18 00:39:06 +00001373 // C++ checkers.
1374 if (CK == CK_NewDeleteChecker ||
1375 CK == CK_NewDeleteLeaksChecker) {
1376 return CK;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001377 }
1378 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001379 }
1380 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001381 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001382 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001383 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001384 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001385}
1386
Anton Yartseve5c0c142015-02-18 00:39:06 +00001387static MallocChecker::CKVecTy MakeVecFromCK(MallocChecker::CheckKind CK1,
1388 MallocChecker::CheckKind CK2 = MallocChecker::CK_NumCheckKinds,
1389 MallocChecker::CheckKind CK3 = MallocChecker::CK_NumCheckKinds,
1390 MallocChecker::CheckKind CK4 = MallocChecker::CK_NumCheckKinds) {
1391 MallocChecker::CKVecTy CKVec;
1392 CKVec.push_back(CK1);
1393 if (CK2 != MallocChecker::CK_NumCheckKinds) {
1394 CKVec.push_back(CK2);
1395 if (CK3 != MallocChecker::CK_NumCheckKinds) {
1396 CKVec.push_back(CK3);
1397 if (CK4 != MallocChecker::CK_NumCheckKinds)
1398 CKVec.push_back(CK4);
1399 }
1400 }
1401 return CKVec;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001402}
1403
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001404Optional<MallocChecker::CheckKind>
Anton Yartseve5c0c142015-02-18 00:39:06 +00001405MallocChecker::getCheckIfTracked(CKVecTy CKVec, AllocationFamily Family) const {
1406 for (auto CK: CKVec) {
1407 auto RetCK = getCheckIfTracked(CK, Family);
1408 if (RetCK.hasValue())
1409 return RetCK;
1410 }
1411 return Optional<MallocChecker::CheckKind>();
1412}
Anton Yartseve3377fb2013-04-04 23:46:29 +00001413
Anton Yartseve5c0c142015-02-18 00:39:06 +00001414Optional<MallocChecker::CheckKind>
1415MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
1416 const Stmt *AllocDeallocStmt) const {
1417 return getCheckIfTracked(CKVec, getAllocationFamily(C, AllocDeallocStmt));
1418}
1419
1420Optional<MallocChecker::CheckKind>
1421MallocChecker::getCheckIfTracked(CKVecTy CKVec, CheckerContext &C,
1422 SymbolRef Sym) const {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001423 const RefState *RS = C.getState()->get<RegionState>(Sym);
1424 assert(RS);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001425 return getCheckIfTracked(CKVec, RS->getAllocationFamily());
Anton Yartseve3377fb2013-04-04 23:46:29 +00001426}
1427
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001428bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001429 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001430 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001431 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001432 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001433 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001434 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001435 else
1436 return false;
1437
1438 return true;
1439}
1440
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001441bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001442 const MemRegion *MR) {
1443 switch (MR->getKind()) {
1444 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001445 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001446 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001447 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001448 else
1449 os << "the address of a function";
1450 return true;
1451 }
1452 case MemRegion::BlockTextRegionKind:
1453 os << "block text";
1454 return true;
1455 case MemRegion::BlockDataRegionKind:
1456 // FIXME: where the block came from?
1457 os << "a block";
1458 return true;
1459 default: {
1460 const MemSpaceRegion *MS = MR->getMemorySpace();
1461
Anna Zaks8158ef02012-01-04 23:54:01 +00001462 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001463 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1464 const VarDecl *VD;
1465 if (VR)
1466 VD = VR->getDecl();
1467 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001468 VD = nullptr;
1469
Jordy Rose3597b212010-06-07 19:32:37 +00001470 if (VD)
1471 os << "the address of the local variable '" << VD->getName() << "'";
1472 else
1473 os << "the address of a local stack variable";
1474 return true;
1475 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001476
1477 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001478 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1479 const VarDecl *VD;
1480 if (VR)
1481 VD = VR->getDecl();
1482 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001483 VD = nullptr;
1484
Jordy Rose3597b212010-06-07 19:32:37 +00001485 if (VD)
1486 os << "the address of the parameter '" << VD->getName() << "'";
1487 else
1488 os << "the address of a parameter";
1489 return true;
1490 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001491
1492 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001493 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1494 const VarDecl *VD;
1495 if (VR)
1496 VD = VR->getDecl();
1497 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001498 VD = nullptr;
1499
Jordy Rose3597b212010-06-07 19:32:37 +00001500 if (VD) {
1501 if (VD->isStaticLocal())
1502 os << "the address of the static variable '" << VD->getName() << "'";
1503 else
1504 os << "the address of the global variable '" << VD->getName() << "'";
1505 } else
1506 os << "the address of a global variable";
1507 return true;
1508 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001509
1510 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001511 }
1512 }
1513}
1514
Anton Yartsev05789592013-03-28 17:05:19 +00001515void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1516 SourceRange Range,
1517 const Expr *DeallocExpr) const {
1518
Anton Yartseve5c0c142015-02-18 00:39:06 +00001519 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1520 CK_MallocPessimistic,
1521 CK_NewDeleteChecker),
1522 C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001523 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001524 return;
1525
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001526 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001527 if (!BT_BadFree[*CheckKind])
1528 BT_BadFree[*CheckKind].reset(
1529 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1530
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001531 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001532 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001533
Jordy Rose3597b212010-06-07 19:32:37 +00001534 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001535 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1536 MR = ER->getSuperRegion();
1537
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001538 os << "Argument to ";
1539 if (!printAllocDeallocName(os, C, DeallocExpr))
1540 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001541
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001542 os << " is ";
1543 bool Summarized = MR ? SummarizeRegion(os, MR)
1544 : SummarizeValue(os, ArgVal);
1545 if (Summarized)
1546 os << ", which is not memory allocated by ";
1547 else
1548 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001549
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001550 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001551
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001552 BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001553 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001554 R->addRange(Range);
Jordan Rosee10d5a72012-11-02 01:53:40 +00001555 C.emitReport(R);
Jordy Rose3597b212010-06-07 19:32:37 +00001556 }
1557}
1558
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001559void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1560 SourceRange Range) const {
1561
1562 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1563 CK_MallocPessimistic,
1564 CK_MismatchedDeallocatorChecker),
1565 AF_Alloca);
1566 if (!CheckKind.hasValue())
1567 return;
1568
1569 if (ExplodedNode *N = C.generateSink()) {
1570 if (!BT_FreeAlloca[*CheckKind])
1571 BT_FreeAlloca[*CheckKind].reset(
1572 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1573
1574 BugReport *R = new BugReport(*BT_FreeAlloca[*CheckKind],
1575 "Memory allocated by alloca() should not be deallocated", N);
1576 R->markInteresting(ArgVal.getAsRegion());
1577 R->addRange(Range);
1578 C.emitReport(R);
1579 }
1580}
1581
Anton Yartseve3377fb2013-04-04 23:46:29 +00001582void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1583 SourceRange Range,
1584 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001585 const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001586 SymbolRef Sym,
1587 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001588
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001589 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001590 return;
1591
1592 if (ExplodedNode *N = C.generateSink()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001593 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001594 BT_MismatchedDealloc.reset(
1595 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1596 "Bad deallocator", "Memory Error"));
1597
Anton Yartsev05789592013-03-28 17:05:19 +00001598 SmallString<100> buf;
1599 llvm::raw_svector_ostream os(buf);
1600
1601 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1602 SmallString<20> AllocBuf;
1603 llvm::raw_svector_ostream AllocOs(AllocBuf);
1604 SmallString<20> DeallocBuf;
1605 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1606
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001607 if (OwnershipTransferred) {
1608 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1609 os << DeallocOs.str() << " cannot";
1610 else
1611 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001612
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001613 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001614
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001615 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1616 os << " allocated by " << AllocOs.str();
1617 } else {
1618 os << "Memory";
1619 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1620 os << " allocated by " << AllocOs.str();
1621
1622 os << " should be deallocated by ";
1623 printExpectedDeallocName(os, RS->getAllocationFamily());
1624
1625 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1626 os << ", not " << DeallocOs.str();
1627 }
Anton Yartsev05789592013-03-28 17:05:19 +00001628
Anton Yartseve3377fb2013-04-04 23:46:29 +00001629 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001630 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001631 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001632 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev05789592013-03-28 17:05:19 +00001633 C.emitReport(R);
1634 }
1635}
1636
Anna Zaksc89ad072013-02-07 23:05:47 +00001637void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001638 SourceRange Range, const Expr *DeallocExpr,
1639 const Expr *AllocExpr) const {
1640
Anton Yartsev05789592013-03-28 17:05:19 +00001641
Anton Yartseve5c0c142015-02-18 00:39:06 +00001642 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1643 CK_MallocPessimistic,
1644 CK_NewDeleteChecker),
1645 C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001646 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001647 return;
1648
Anna Zaksc89ad072013-02-07 23:05:47 +00001649 ExplodedNode *N = C.generateSink();
Craig Topper0dbb7832014-05-27 02:45:47 +00001650 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001651 return;
1652
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001653 if (!BT_OffsetFree[*CheckKind])
1654 BT_OffsetFree[*CheckKind].reset(
1655 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001656
1657 SmallString<100> buf;
1658 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001659 SmallString<20> AllocNameBuf;
1660 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001661
1662 const MemRegion *MR = ArgVal.getAsRegion();
1663 assert(MR && "Only MemRegion based symbols can have offset free errors");
1664
1665 RegionOffset Offset = MR->getAsOffset();
1666 assert((Offset.isValid() &&
1667 !Offset.hasSymbolicOffset() &&
1668 Offset.getOffset() != 0) &&
1669 "Only symbols with a valid offset can have offset free errors");
1670
1671 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1672
Anton Yartsev05789592013-03-28 17:05:19 +00001673 os << "Argument to ";
1674 if (!printAllocDeallocName(os, C, DeallocExpr))
1675 os << "deallocator";
1676 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001677 << offsetBytes
1678 << " "
1679 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001680 << " from the start of ";
1681 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1682 os << "memory allocated by " << AllocNameOs.str();
1683 else
1684 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001685
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001686 BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001687 R->markInteresting(MR->getBaseRegion());
1688 R->addRange(Range);
1689 C.emitReport(R);
1690}
1691
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001692void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1693 SymbolRef Sym) const {
1694
Anton Yartseve5c0c142015-02-18 00:39:06 +00001695 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1696 CK_MallocPessimistic,
1697 CK_NewDeleteChecker),
1698 C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001699 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001700 return;
1701
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001702 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001703 if (!BT_UseFree[*CheckKind])
1704 BT_UseFree[*CheckKind].reset(new BugType(
1705 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001706
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001707 BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001708 "Use of memory after it is freed", N);
1709
1710 R->markInteresting(Sym);
1711 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001712 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001713 C.emitReport(R);
1714 }
1715}
1716
1717void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1718 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001719 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001720
Anton Yartseve5c0c142015-02-18 00:39:06 +00001721 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1722 CK_MallocPessimistic,
1723 CK_NewDeleteChecker),
1724 C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001725 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001726 return;
1727
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001728 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001729 if (!BT_DoubleFree[*CheckKind])
1730 BT_DoubleFree[*CheckKind].reset(
1731 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001732
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001733 BugReport *R =
1734 new BugReport(*BT_DoubleFree[*CheckKind],
1735 (Released ? "Attempt to free released memory"
1736 : "Attempt to free non-owned memory"),
1737 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001738 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001739 R->markInteresting(Sym);
1740 if (PrevSym)
1741 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001742 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001743 C.emitReport(R);
1744 }
1745}
1746
Jordan Rose656fdd52014-01-08 18:46:55 +00001747void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1748
Anton Yartseve5c0c142015-02-18 00:39:06 +00001749 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_NewDeleteChecker),
1750 C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001751 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001752 return;
1753
1754 if (ExplodedNode *N = C.generateSink()) {
1755 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001756 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1757 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001758
1759 BugReport *R = new BugReport(*BT_DoubleDelete,
1760 "Attempt to delete released memory", N);
1761
1762 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001763 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Jordan Rose656fdd52014-01-08 18:46:55 +00001764 C.emitReport(R);
1765 }
1766}
1767
Anna Zaks40a7eb32012-02-22 19:24:52 +00001768ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1769 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001770 bool FreesOnFail,
1771 ProgramStateRef State) const {
1772 if (!State)
1773 return nullptr;
1774
Anna Zaksb508d292012-04-10 23:41:11 +00001775 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001776 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001777
Ted Kremenek90af9092010-12-02 07:49:45 +00001778 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001779 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001780 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001781 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001782 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001783 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001784
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001785 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001786
Ted Kremenek90af9092010-12-02 07:49:45 +00001787 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001788 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001789
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001790 // Get the size argument. If there is no size arg then give up.
1791 const Expr *Arg1 = CE->getArg(1);
1792 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00001793 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001794
1795 // Get the value of the size argument.
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001796 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001797 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001798 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001799 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001800
1801 // Compare the size argument to 0.
1802 DefinedOrUnknownSVal SizeZero =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001803 svalBuilder.evalEQ(State, Arg1Val,
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001804 svalBuilder.makeIntValWithPtrWidth(0, false));
1805
Anna Zaksd56c8792012-02-13 18:05:39 +00001806 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001807 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001808 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001809 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001810 // We only assume exceptional states if they are definitely true; if the
1811 // state is under-constrained, assume regular realloc behavior.
1812 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1813 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1814
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001815 // If the ptr is NULL and the size is not 0, the call is equivalent to
1816 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001817 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001818 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001819 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001820 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001821 }
1822
Anna Zaksd56c8792012-02-13 18:05:39 +00001823 if (PrtIsNull && SizeIsZero)
Craig Topper0dbb7832014-05-27 02:45:47 +00001824 return nullptr;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001825
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001826 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001827 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001828 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001829 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001830 SymbolRef ToPtr = RetVal.getAsSymbol();
1831 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00001832 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00001833
Anna Zaksfe6eb672012-08-24 02:28:20 +00001834 bool ReleasedAllocated = false;
1835
Anna Zaksd56c8792012-02-13 18:05:39 +00001836 // If the size is 0, free the memory.
1837 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001838 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1839 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001840 // The semantics of the return value are:
1841 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001842 // to free() is returned. We just free the input pointer and do not add
1843 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001844 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001845 }
1846
1847 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001848 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001849 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00001850
Anna Zaksd56c8792012-02-13 18:05:39 +00001851 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1852 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001853 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001854 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001855
Anna Zaks75cfbb62012-09-12 22:57:34 +00001856 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1857 if (FreesOnFail)
1858 Kind = RPIsFreeOnFailure;
1859 else if (!ReleasedAllocated)
1860 Kind = RPDoNotTrackAfterFailure;
1861
Anna Zaksfe6eb672012-08-24 02:28:20 +00001862 // Record the info about the reallocated symbol so that we could properly
1863 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001864 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001865 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001866 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001867 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001868 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001869 }
Craig Topper0dbb7832014-05-27 02:45:47 +00001870 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001871}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001872
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001873ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
1874 ProgramStateRef State) {
1875 if (!State)
1876 return nullptr;
1877
Anna Zaksb508d292012-04-10 23:41:11 +00001878 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001879 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001880
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001881 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001882 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001883 SVal count = State->getSVal(CE->getArg(0), LCtx);
1884 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1885 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
Ted Kremenek90af9092010-12-02 07:49:45 +00001886 svalBuilder.getContext().getSizeType());
1887 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001888
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001889 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001890}
1891
Anna Zaksfc2e1532012-03-21 19:45:08 +00001892LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00001893MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1894 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00001895 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00001896 // Walk the ExplodedGraph backwards and find the first node that referred to
1897 // the tracked symbol.
1898 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001899 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00001900
1901 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00001902 ProgramStateRef State = N->getState();
1903 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00001904 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001905
1906 // Find the most recent expression bound to the symbol in the current
1907 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00001908 if (!ReferenceRegion) {
1909 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1910 SVal Val = State->getSVal(MR);
1911 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00001912 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00001913 // Do not show local variables belonging to a function other than
1914 // where the error is reported.
1915 if (!VR ||
1916 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1917 ReferenceRegion = MR;
1918 }
1919 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00001920 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00001921
Anna Zaks486a0ff2015-02-05 01:02:53 +00001922 // Allocation node, is the last node in the current or parent context in
1923 // which the symbol was tracked.
1924 const LocationContext *NContext = N->getLocationContext();
1925 if (NContext == LeakContext ||
1926 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00001927 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001928 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00001929 }
1930
Anna Zaksa043d0c2013-01-08 00:25:29 +00001931 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00001932}
1933
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001934void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1935 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001936
Anton Yartseve5c0c142015-02-18 00:39:06 +00001937 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
1938 CK_MallocPessimistic,
1939 CK_NewDeleteLeaksChecker),
1940 C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001941 if (!CheckKind.hasValue())
Anton Yartsev6e499252013-04-05 02:25:02 +00001942 return;
1943
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001944 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001945 if (!BT_Leak[*CheckKind]) {
1946 BT_Leak[*CheckKind].reset(
1947 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001948 // Leaks should not be reported if they are post-dominated by a sink:
1949 // (1) Sinks are higher importance bugs.
1950 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1951 // with __noreturn functions such as assert() or exit(). We choose not
1952 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001953 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001954 }
1955
Anna Zaksdf901a42012-02-23 21:38:21 +00001956 // Most bug reports are cached at the location where they occurred.
1957 // With leaks, we want to unique them by the location where they were
1958 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00001959 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00001960 const ExplodedNode *AllocNode = nullptr;
1961 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001962 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Anna Zaksa043d0c2013-01-08 00:25:29 +00001963
1964 ProgramPoint P = AllocNode->getLocation();
Craig Topper0dbb7832014-05-27 02:45:47 +00001965 const Stmt *AllocationStmt = nullptr;
David Blaikie87396b92013-02-21 22:23:56 +00001966 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001967 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00001968 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001969 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00001970 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00001971 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1972 C.getSourceManager(),
1973 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00001974
Anna Zaksfc2e1532012-03-21 19:45:08 +00001975 SmallString<200> buf;
1976 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001977 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00001978 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001979 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00001980 } else {
1981 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00001982 }
1983
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001984 BugReport *R =
1985 new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1986 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00001987 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001988 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Jordan Rosee10d5a72012-11-02 01:53:40 +00001989 C.emitReport(R);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001990}
1991
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00001992void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1993 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00001994{
Zhongxing Xubce831f2010-08-15 08:19:57 +00001995 if (!SymReaper.hasDeadSymbols())
1996 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00001997
Ted Kremenek49b1e382012-01-26 21:29:00 +00001998 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001999 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00002000 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00002001
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002002 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00002003 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2004 if (SymReaper.isDead(I->first)) {
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002005 if (I->second.isAllocated())
Anna Zaks78edc2f2012-02-09 06:48:19 +00002006 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00002007 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00002008 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00002009
Zhongxing Xuc7460962009-11-13 07:48:11 +00002010 }
2011 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002012
Anna Zaksd56c8792012-02-13 18:05:39 +00002013 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002014 ReallocPairsTy RP = state->get<ReallocPairs>();
2015 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002016 if (SymReaper.isDead(I->first) ||
2017 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002018 state = state->remove<ReallocPairs>(I->first);
2019 }
2020 }
2021
Anna Zaks67291b92012-11-13 03:18:01 +00002022 // Cleanup the FreeReturnValue Map.
2023 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2024 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2025 if (SymReaper.isDead(I->first) ||
2026 SymReaper.isDead(I->second)) {
2027 state = state->remove<FreeReturnValue>(I->first);
2028 }
2029 }
2030
Anna Zaksdf901a42012-02-23 21:38:21 +00002031 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002032 ExplodedNode *N = C.getPredecessor();
2033 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002034 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002035 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper2341c0d2013-07-04 03:08:24 +00002036 for (SmallVectorImpl<SymbolRef>::iterator
2037 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002038 reportLeak(*I, N, C);
Anna Zaks78edc2f2012-02-09 06:48:19 +00002039 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002040 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002041
Anna Zaksdf901a42012-02-23 21:38:21 +00002042 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002043}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002044
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002045void MallocChecker::checkPreCall(const CallEvent &Call,
2046 CheckerContext &C) const {
2047
Jordan Rose656fdd52014-01-08 18:46:55 +00002048 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2049 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2050 if (!Sym || checkDoubleDelete(Sym, C))
2051 return;
2052 }
2053
Anna Zaks46d01602012-05-18 01:16:10 +00002054 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002055 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2056 const FunctionDecl *FD = FC->getDecl();
2057 if (!FD)
2058 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002059
Anna Zaksd79b8402014-10-03 21:48:59 +00002060 ASTContext &Ctx = C.getASTContext();
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002061 if ((ChecksEnabled[CK_MallocOptimistic] ||
2062 ChecksEnabled[CK_MallocPessimistic]) &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002063 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2064 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2065 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002066 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002067
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002068 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002069 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002070 return;
2071 }
2072
2073 // Check if the callee of a method is deleted.
2074 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2075 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2076 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2077 return;
2078 }
2079
2080 // Check arguments for being used after free.
2081 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2082 SVal ArgSVal = Call.getArgSVal(I);
2083 if (ArgSVal.getAs<Loc>()) {
2084 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002085 if (!Sym)
2086 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002087 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002088 return;
2089 }
2090 }
2091}
2092
Anna Zaksa1b227b2012-02-08 23:16:56 +00002093void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2094 const Expr *E = S->getRetValue();
2095 if (!E)
2096 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002097
2098 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002099 ProgramStateRef State = C.getState();
2100 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002101 SymbolRef Sym = RetVal.getAsSymbol();
2102 if (!Sym)
2103 // If we are returning a field of the allocated struct or an array element,
2104 // the callee could still free the memory.
2105 // TODO: This logic should be a part of generic symbol escape callback.
2106 if (const MemRegion *MR = RetVal.getAsRegion())
2107 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2108 if (const SymbolicRegion *BMR =
2109 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2110 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002111
Anna Zaks3aa52252012-02-11 21:44:39 +00002112 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002113 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002114 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002115}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002116
Anna Zaks9fe80982012-03-22 00:57:20 +00002117// TODO: Blocks should be either inlined or should call invalidate regions
2118// upon invocation. After that's in place, special casing here will not be
2119// needed.
2120void MallocChecker::checkPostStmt(const BlockExpr *BE,
2121 CheckerContext &C) const {
2122
2123 // Scan the BlockDecRefExprs for any object the retain count checker
2124 // may be tracking.
2125 if (!BE->getBlockDecl()->hasCaptures())
2126 return;
2127
2128 ProgramStateRef state = C.getState();
2129 const BlockDataRegion *R =
2130 cast<BlockDataRegion>(state->getSVal(BE,
2131 C.getLocationContext()).getAsRegion());
2132
2133 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2134 E = R->referenced_vars_end();
2135
2136 if (I == E)
2137 return;
2138
2139 SmallVector<const MemRegion*, 10> Regions;
2140 const LocationContext *LC = C.getLocationContext();
2141 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2142
2143 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002144 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002145 if (VR->getSuperRegion() == R) {
2146 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2147 }
2148 Regions.push_back(VR);
2149 }
2150
2151 state =
2152 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2153 Regions.data() + Regions.size()).getState();
2154 C.addTransition(state);
2155}
2156
Anna Zaks46d01602012-05-18 01:16:10 +00002157bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002158 assert(Sym);
2159 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002160 return (RS && RS->isReleased());
2161}
2162
2163bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2164 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002165
Jordan Rose656fdd52014-01-08 18:46:55 +00002166 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002167 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2168 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002169 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002170
Anna Zaksa1b227b2012-02-08 23:16:56 +00002171 return false;
2172}
2173
Jordan Rose656fdd52014-01-08 18:46:55 +00002174bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2175
2176 if (isReleased(Sym, C)) {
2177 ReportDoubleDelete(C, Sym);
2178 return true;
2179 }
2180 return false;
2181}
2182
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002183// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002184void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2185 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002186 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaksa1b227b2012-02-08 23:16:56 +00002187 if (Sym)
Anna Zaks46d01602012-05-18 01:16:10 +00002188 checkUseAfterFree(Sym, C, S);
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002189}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002190
Anna Zaksbb1ef902012-02-11 21:02:35 +00002191// If a symbolic region is assumed to NULL (or another constant), stop tracking
2192// it - assuming that allocation failed on this path.
2193ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2194 SVal Cond,
2195 bool Assumption) const {
2196 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002197 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002198 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002199 ConstraintManager &CMgr = state->getConstraintManager();
2200 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2201 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002202 state = state->remove<RegionState>(I.getKey());
2203 }
2204
Anna Zaksd56c8792012-02-13 18:05:39 +00002205 // Realloc returns 0 when reallocation fails, which means that we should
2206 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002207 ReallocPairsTy RP = state->get<ReallocPairs>();
2208 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002209 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002210 ConstraintManager &CMgr = state->getConstraintManager();
2211 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002212 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002213 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002214
Anna Zaks75cfbb62012-09-12 22:57:34 +00002215 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2216 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2217 if (RS->isReleased()) {
2218 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002219 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002220 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002221 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2222 state = state->remove<RegionState>(ReallocSym);
2223 else
2224 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002225 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002226 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002227 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002228 }
2229
Anna Zaksbb1ef902012-02-11 21:02:35 +00002230 return state;
2231}
2232
Anna Zaks8ebeb642013-06-08 00:29:29 +00002233bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002234 const CallEvent *Call,
2235 ProgramStateRef State,
2236 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002237 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002238 EscapingSymbol = nullptr;
2239
Jordan Rose2a833ca2014-01-15 17:25:15 +00002240 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002241 // TODO: If we want to be more optimistic here, we'll need to make sure that
2242 // regions escape to C++ containers. They seem to do that even now, but for
2243 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002244 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002245 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002246
Jordan Rose742920c2012-07-02 19:27:35 +00002247 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002248 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002249 // If it's not a framework call, or if it takes a callback, assume it
2250 // can free memory.
2251 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002252 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002253
Jordan Rose613f3c02013-03-09 00:59:10 +00002254 // If it's a method we know about, handle it explicitly post-call.
2255 // This should happen before the "freeWhenDone" check below.
2256 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002257 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002258
Jordan Rose613f3c02013-03-09 00:59:10 +00002259 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2260 // about, we can't be sure that the object will use free() to deallocate the
2261 // memory, so we can't model it explicitly. The best we can do is use it to
2262 // decide whether the pointer escapes.
2263 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002264 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002265
Jordan Rose613f3c02013-03-09 00:59:10 +00002266 // If the first selector piece ends with "NoCopy", and there is no
2267 // "freeWhenDone" parameter set to zero, we know ownership is being
2268 // transferred. Again, though, we can't be sure that the object will use
2269 // free() to deallocate the memory, so we can't model it explicitly.
2270 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002271 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002272 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002273
Anna Zaks42908c72012-06-19 05:10:32 +00002274 // If the first selector starts with addPointer, insertPointer,
2275 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2276 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002277 // that the pointers get freed by following the container itself.
2278 if (FirstSlot.startswith("addPointer") ||
2279 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002280 FirstSlot.startswith("replacePointer") ||
2281 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002282 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002283 }
2284
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002285 // We should escape receiver on call to 'init'. This is especially relevant
2286 // to the receiver, as the corresponding symbol is usually not referenced
2287 // after the call.
2288 if (Msg->getMethodFamily() == OMF_init) {
2289 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2290 return true;
2291 }
Anna Zaks737926b2013-05-31 22:39:13 +00002292
Jordan Rose742920c2012-07-02 19:27:35 +00002293 // Otherwise, assume that the method does not free memory.
2294 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002295 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002296 }
2297
Jordan Rose742920c2012-07-02 19:27:35 +00002298 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002299 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002300 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002301 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002302
Jordan Rose742920c2012-07-02 19:27:35 +00002303 ASTContext &ASTC = State->getStateManager().getContext();
2304
2305 // If it's one of the allocation functions we can reason about, we model
2306 // its behavior explicitly.
2307 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002308 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002309
2310 // If it's not a system call, assume it frees memory.
2311 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002312 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002313
2314 // White list the system functions whose arguments escape.
2315 const IdentifierInfo *II = FD->getIdentifier();
2316 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002317 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002318 StringRef FName = II->getName();
2319
Jordan Rose742920c2012-07-02 19:27:35 +00002320 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose7ab01822012-07-02 19:27:51 +00002321 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002322 if (FName.endswith("NoCopy")) {
2323 // Look for the deallocator argument. We know that the memory ownership
2324 // is not transferred only if the deallocator argument is
2325 // 'kCFAllocatorNull'.
2326 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2327 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2328 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2329 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2330 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002331 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002332 }
2333 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002334 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002335 }
2336
Jordan Rose742920c2012-07-02 19:27:35 +00002337 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002338 // 'closefn' is specified (and if that function does free memory),
2339 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002340 // Currently, we do not inspect the 'closefn' function (PR12101).
2341 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002342 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002343 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002344
2345 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2346 // these leaks might be intentional when setting the buffer for stdio.
2347 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2348 if (FName == "setbuf" || FName =="setbuffer" ||
2349 FName == "setlinebuf" || FName == "setvbuf") {
2350 if (Call->getNumArgs() >= 1) {
2351 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2352 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2353 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2354 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002355 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002356 }
2357 }
2358
2359 // A bunch of other functions which either take ownership of a pointer or
2360 // wrap the result up in a struct or object, meaning it can be freed later.
2361 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2362 // but the Malloc checker cannot differentiate between them. The right way
2363 // of doing this would be to implement a pointer escapes callback.
2364 if (FName == "CGBitmapContextCreate" ||
2365 FName == "CGBitmapContextCreateWithData" ||
2366 FName == "CVPixelBufferCreateWithBytes" ||
2367 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2368 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002369 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002370 }
2371
Jordan Rose7ab01822012-07-02 19:27:51 +00002372 // Handle cases where we know a buffer's /address/ can escape.
2373 // Note that the above checks handle some special cases where we know that
2374 // even though the address escapes, it's still our responsibility to free the
2375 // buffer.
2376 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002377 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002378
2379 // Otherwise, assume that the function does not free memory.
2380 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002381 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002382}
2383
Anna Zaks333481b2013-03-28 23:15:29 +00002384static bool retTrue(const RefState *RS) {
2385 return true;
2386}
2387
2388static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2389 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2390 RS->getAllocationFamily() == AF_CXXNew);
2391}
2392
Anna Zaksdc154152012-12-20 00:38:25 +00002393ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2394 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002395 const CallEvent *Call,
2396 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002397 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2398}
2399
2400ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2401 const InvalidatedSymbols &Escaped,
2402 const CallEvent *Call,
2403 PointerEscapeKind Kind) const {
2404 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2405 &checkIfNewOrNewArrayFamily);
2406}
2407
2408ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2409 const InvalidatedSymbols &Escaped,
2410 const CallEvent *Call,
2411 PointerEscapeKind Kind,
2412 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002413 // If we know that the call does not free memory, or we want to process the
2414 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002415 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002416 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002417 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2418 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002419 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002420 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002421 }
Anna Zaks3d348342012-02-14 21:55:24 +00002422
Anna Zaksdc154152012-12-20 00:38:25 +00002423 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002424 E = Escaped.end();
2425 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002426 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002427
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002428 if (EscapingSymbol && EscapingSymbol != sym)
2429 continue;
2430
Anna Zaks0d6989b2012-06-22 02:04:31 +00002431 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks93a21a82013-04-09 00:30:28 +00002432 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002433 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002434 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2435 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002436 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002437 }
Anna Zaks3d348342012-02-14 21:55:24 +00002438 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002439}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002440
Jordy Rosebf38f202012-03-18 07:43:35 +00002441static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2442 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002443 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2444 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002445
Jordan Rose0c153cb2012-11-02 01:54:06 +00002446 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002447 I != E; ++I) {
2448 SymbolRef sym = I.getKey();
2449 if (!currMap.lookup(sym))
2450 return sym;
2451 }
2452
Craig Topper0dbb7832014-05-27 02:45:47 +00002453 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002454}
2455
Anna Zaks2b5bb972012-02-09 06:25:51 +00002456PathDiagnosticPiece *
2457MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2458 const ExplodedNode *PrevN,
2459 BugReporterContext &BRC,
2460 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002461 ProgramStateRef state = N->getState();
2462 ProgramStateRef statePrev = PrevN->getState();
2463
2464 const RefState *RS = state->get<RegionState>(Sym);
2465 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002466 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002467 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002468
Craig Topper0dbb7832014-05-27 02:45:47 +00002469 const Stmt *S = nullptr;
2470 const char *Msg = nullptr;
2471 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002472
2473 // Retrieve the associated statement.
2474 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002475 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002476 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002477 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002478 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002479 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002480 // If an assumption was made on a branch, it should be caught
2481 // here by looking at the state transition.
2482 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002483 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002484
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002485 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002486 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002487
Jordan Rose681cce92012-07-10 22:07:42 +00002488 // FIXME: We will eventually need to handle non-statement-based events
2489 // (__attribute__((cleanup))).
2490
Anna Zaks2b5bb972012-02-09 06:25:51 +00002491 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002492 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002493 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002494 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002495 StackHint = new StackHintGeneratorForSymbol(Sym,
2496 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002497 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002498 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002499 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002500 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002501 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002502 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002503 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002504 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002505 Mode = ReallocationFailed;
2506 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002507 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002508 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002509
Jordy Rose21ff76e2012-03-24 03:15:09 +00002510 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2511 // Is it possible to fail two reallocs WITHOUT testing in between?
2512 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2513 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002514 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002515 FailedReallocSymbol = sym;
2516 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002517 }
2518
2519 // We are in a special mode if a reallocation failed later in the path.
2520 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002521 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002522
Jordy Rose21ff76e2012-03-24 03:15:09 +00002523 // Is this is the first appearance of the reallocated symbol?
2524 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002525 // We're at the reallocation point.
2526 Msg = "Attempt to reallocate memory";
2527 StackHint = new StackHintGeneratorForSymbol(Sym,
2528 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002529 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002530 Mode = Normal;
2531 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002532 }
2533
Anna Zaks2b5bb972012-02-09 06:25:51 +00002534 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002535 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002536 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002537
2538 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002539 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002540 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002541 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002542}
2543
Anna Zaks263b7e02012-05-02 00:05:20 +00002544void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2545 const char *NL, const char *Sep) const {
2546
2547 RegionStateTy RS = State->get<RegionState>();
2548
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002549 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002550 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002551 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002552 const RefState *RefS = State->get<RegionState>(I.getKey());
2553 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartseve5c0c142015-02-18 00:39:06 +00002554 auto CheckKind = getCheckIfTracked(MakeVecFromCK(CK_MallocOptimistic,
2555 CK_MallocPessimistic,
2556 CK_NewDeleteChecker),
2557 Family);
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002558 I.getKey()->dumpToStream(Out);
2559 Out << " : ";
2560 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002561 if (CheckKind.hasValue())
2562 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002563 Out << NL;
2564 }
2565 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002566}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002567
Anna Zakse4cfcd42013-04-16 00:22:55 +00002568void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2569 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002570 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2571 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2572 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2573 mgr.getCurrentCheckName();
Anna Zakse4cfcd42013-04-16 00:22:55 +00002574 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2575 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002576 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002577 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002578}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002579
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002580#define REGISTER_CHECKER(name) \
2581 void ento::register##name(CheckerManager &mgr) { \
2582 registerCStringCheckerBasic(mgr); \
2583 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2584 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2585 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2586 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002587
2588REGISTER_CHECKER(MallocPessimistic)
2589REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev13df0362013-03-25 01:35:45 +00002590REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002591REGISTER_CHECKER(MismatchedDeallocatorChecker)