blob: 7dd18d56651ed1406c465d8b260c356a18d10b05 [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,
45 AF_CXXNewArray
46};
47
Zhongxing Xu1239de12009-12-11 00:55:44 +000048class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000049 enum Kind { // Reference to allocated memory.
50 Allocated,
51 // Reference to released/freed memory.
52 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000053 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000054 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000055 Relinquished,
56 // We are no longer guaranteed to have observed all manipulations
57 // of this pointer/memory. For example, it could have been
58 // passed as a parameter to an opaque function.
59 Escaped
60 };
Anton Yartsev05789592013-03-28 17:05:19 +000061
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000062 const Stmt *S;
Anton Yartsev05789592013-03-28 17:05:19 +000063 unsigned K : 2; // Kind enum, but stored as a bitfield.
64 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
65 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000066
Anton Yartsev05789592013-03-28 17:05:19 +000067 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000068 : S(s), K(k), Family(family) {
69 assert(family != AF_None);
70 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000071public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000072 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000073 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000074 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000075 bool isEscaped() const { return K == Escaped; }
76 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000077 return (AllocationFamily)Family;
78 }
Anna Zaksd56c8792012-02-13 18:05:39 +000079 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000080
81 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000082 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000083 }
84
Anton Yartsev05789592013-03-28 17:05:19 +000085 static RefState getAllocated(unsigned family, const Stmt *s) {
86 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000087 }
Anton Yartsev05789592013-03-28 17:05:19 +000088 static RefState getReleased(unsigned family, const Stmt *s) {
89 return RefState(Released, s, family);
90 }
91 static RefState getRelinquished(unsigned family, const Stmt *s) {
92 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +000093 }
Anna Zaks93a21a82013-04-09 00:30:28 +000094 static RefState getEscaped(const RefState *RS) {
95 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
96 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000097
98 void Profile(llvm::FoldingSetNodeID &ID) const {
99 ID.AddInteger(K);
100 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +0000101 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000102 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000103
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000104 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000105 switch (static_cast<Kind>(K)) {
106#define CASE(ID) case ID: OS << #ID; break;
107 CASE(Allocated)
108 CASE(Released)
109 CASE(Relinquished)
110 CASE(Escaped)
111 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000112 }
113
Alp Tokeref6b0072014-01-04 13:47:14 +0000114 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000115};
116
Anna Zaks75cfbb62012-09-12 22:57:34 +0000117enum ReallocPairKind {
118 RPToBeFreedAfterFailure,
119 // The symbol has been freed when reallocation failed.
120 RPIsFreeOnFailure,
121 // The symbol does not need to be freed after reallocation fails.
122 RPDoNotTrackAfterFailure
123};
124
Anna Zaksfe6eb672012-08-24 02:28:20 +0000125/// \class ReallocPair
126/// \brief Stores information about the symbol being reallocated by a call to
127/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000128struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000129 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000130 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000131 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000132
Anna Zaks75cfbb62012-09-12 22:57:34 +0000133 ReallocPair(SymbolRef S, ReallocPairKind K) :
134 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000135 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000136 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000137 ID.AddPointer(ReallocatedSym);
138 }
139 bool operator==(const ReallocPair &X) const {
140 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000141 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000142 }
143};
144
Anna Zaksa043d0c2013-01-08 00:25:29 +0000145typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000146
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000147class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000148 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000149 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000150 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000151 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000152 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000153 check::PostStmt<CXXNewExpr>,
154 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000155 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000156 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000157 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000158 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000159{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000160public:
Craig Topper0dbb7832014-05-27 02:45:47 +0000161 MallocChecker()
162 : II_malloc(nullptr), II_free(nullptr), II_realloc(nullptr),
163 II_calloc(nullptr), II_valloc(nullptr), II_reallocf(nullptr),
164 II_strndup(nullptr), II_strdup(nullptr), II_kmalloc(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000165
166 /// In pessimistic mode, the checker assumes that it does not know which
167 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000168 enum CheckKind {
169 CK_MallocPessimistic,
170 CK_MallocOptimistic,
171 CK_NewDeleteChecker,
172 CK_NewDeleteLeaksChecker,
173 CK_MismatchedDeallocatorChecker,
174 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000175 };
176
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000177 DefaultBool ChecksEnabled[CK_NumCheckKinds];
178 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000179
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000180 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000181 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000182 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
183 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000184 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000185 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000186 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000187 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000188 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000189 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000190 void checkLocation(SVal l, bool isLoad, const Stmt *S,
191 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000192
193 ProgramStateRef checkPointerEscape(ProgramStateRef State,
194 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000195 const CallEvent *Call,
196 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000197 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
198 const InvalidatedSymbols &Escaped,
199 const CallEvent *Call,
200 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000201
Anna Zaks263b7e02012-05-02 00:05:20 +0000202 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000203 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000204
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000205private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000206 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
207 mutable std::unique_ptr<BugType> BT_DoubleDelete;
208 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
209 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
210 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
211 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
212 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000213 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000214 *II_valloc, *II_reallocf, *II_strndup, *II_strdup,
215 *II_kmalloc;
216 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000217
Anna Zaks3d348342012-02-14 21:55:24 +0000218 void initIdentifierInfo(ASTContext &C) const;
219
Anton Yartsev05789592013-03-28 17:05:19 +0000220 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000221 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000222
223 /// \brief Print names of allocators and deallocators.
224 ///
225 /// \returns true on success.
226 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
227 const Expr *E) const;
228
229 /// \brief Print expected name of an allocator based on the deallocator's
230 /// family derived from the DeallocExpr.
231 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
232 const Expr *DeallocExpr) const;
233 /// \brief Print expected name of a deallocator based on the allocator's
234 /// family.
235 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
236
Jordan Rose613f3c02013-03-09 00:59:10 +0000237 ///@{
Anna Zaks3d348342012-02-14 21:55:24 +0000238 /// Check if this is one of the functions which can allocate/reallocate memory
239 /// pointed to by one of its arguments.
240 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks46d01602012-05-18 01:16:10 +0000241 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
242 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000243 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000244 ///@}
Richard Smith852e9ce2013-11-27 01:46:48 +0000245 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
246 const CallExpr *CE,
247 const OwnershipAttr* Att) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000248 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000249 const Expr *SizeEx, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000250 ProgramStateRef State,
251 AllocationFamily Family = AF_Malloc) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000252 return MallocMemAux(C, CE,
Anton Yartsev05789592013-03-28 17:05:19 +0000253 State->getSVal(SizeEx, C.getLocationContext()),
254 Init, State, Family);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000255 }
Anna Zaks40a7eb32012-02-22 19:24:52 +0000256
Ted Kremenek49b1e382012-01-26 21:29:00 +0000257 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000258 SVal SizeEx, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000259 ProgramStateRef State,
260 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000261
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000262 // Check if this malloc() for special flags. At present that means M_ZERO or
263 // __GFP_ZERO (in which case, treat it like calloc).
264 llvm::Optional<ProgramStateRef>
265 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
266 const ProgramStateRef &State) const;
267
Anna Zaks40a7eb32012-02-22 19:24:52 +0000268 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev05789592013-03-28 17:05:19 +0000269 static ProgramStateRef
270 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
271 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000272
273 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
274 const OwnershipAttr* Att) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000275 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000276 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000277 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000278 bool &ReleasedAllocated,
279 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000280 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
281 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000282 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000283 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000284 bool &ReleasedAllocated,
285 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000286
Anna Zaks40a7eb32012-02-22 19:24:52 +0000287 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
288 bool FreesMemOnFailure) const;
289 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose3597b212010-06-07 19:32:37 +0000290
Anna Zaks46d01602012-05-18 01:16:10 +0000291 ///\brief Check if the memory associated with this symbol was released.
292 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
293
Anton Yartsev13df0362013-03-25 01:35:45 +0000294 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000295
Jordan Rose656fdd52014-01-08 18:46:55 +0000296 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
297
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000298 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000299 /// "interesting" and should be modeled explicitly.
300 ///
Anna Zaks8ebeb642013-06-08 00:29:29 +0000301 /// \param [out] EscapingSymbol A function might not free memory in general,
302 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000303 /// returned and the single escaping symbol is returned through the out
304 /// parameter.
305 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000306 /// We assume that pointers do not escape through calls to system functions
307 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000308 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000309 ProgramStateRef State,
310 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000311
Anna Zaks333481b2013-03-28 23:15:29 +0000312 // Implementation of the checkPointerEscape callabcks.
313 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
314 const InvalidatedSymbols &Escaped,
315 const CallEvent *Call,
316 PointerEscapeKind Kind,
317 bool(*CheckRefState)(const RefState*)) const;
318
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000319 ///@{
320 /// Tells if a given family/call/symbol is tracked by the current checker.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000321 /// Sets CheckKind to the kind of the checker responsible for this
322 /// family/call/symbol.
323 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family) const;
324 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
325 const Stmt *AllocDeallocStmt) const;
326 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000327 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000328 static bool SummarizeValue(raw_ostream &os, SVal V);
329 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev05789592013-03-28 17:05:19 +0000330 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
331 const Expr *DeallocExpr) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000332 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000333 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000334 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000335 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
336 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000337 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000338 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
339 SymbolRef Sym) const;
340 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000341 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000342
Jordan Rose656fdd52014-01-08 18:46:55 +0000343 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
344
Anna Zaksdf901a42012-02-23 21:38:21 +0000345 /// Find the location of the allocation for Sym on the path leading to the
346 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000347 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
348 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000349
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000350 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
351
Anna Zaks2b5bb972012-02-09 06:25:51 +0000352 /// The bug visitor which allows us to print extra diagnostics along the
353 /// BugReport path. For example, showing the allocation site of the leaked
354 /// region.
Jordy Rosef78877e2012-03-24 02:45:35 +0000355 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000356 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000357 enum NotificationMode {
358 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000359 ReallocationFailed
360 };
361
Anna Zaks2b5bb972012-02-09 06:25:51 +0000362 // The allocated region symbol tracked by the main analysis.
363 SymbolRef Sym;
364
Anna Zaks62cce9e2012-05-10 01:37:40 +0000365 // The mode we are in, i.e. what kind of diagnostics will be emitted.
366 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000367
Anna Zaks62cce9e2012-05-10 01:37:40 +0000368 // A symbol from when the primary region should have been reallocated.
369 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000370
Anna Zaks62cce9e2012-05-10 01:37:40 +0000371 bool IsLeak;
372
373 public:
374 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000375 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000376
Anna Zaks2b5bb972012-02-09 06:25:51 +0000377 virtual ~MallocBugVisitor() {}
378
Craig Topperfb6b25b2014-03-15 04:29:04 +0000379 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000380 static int X = 0;
381 ID.AddPointer(&X);
382 ID.AddPointer(Sym);
383 }
384
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000385 inline bool isAllocated(const RefState *S, const RefState *SPrev,
386 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000387 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000388 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000389 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000390 }
391
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000392 inline bool isReleased(const RefState *S, const RefState *SPrev,
393 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000394 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000395 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000396 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
397 }
398
Anna Zaks0d6989b2012-06-22 02:04:31 +0000399 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
400 const Stmt *Stmt) {
401 // Did not track -> relinquished. Other state (allocated) -> relinquished.
402 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
403 isa<ObjCPropertyRefExpr>(Stmt)) &&
404 (S && S->isRelinquished()) &&
405 (!SPrev || !SPrev->isRelinquished()));
406 }
407
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000408 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
409 const Stmt *Stmt) {
410 // If the expression is not a call, and the state change is
411 // released -> allocated, it must be the realloc return value
412 // check. If we have to handle more cases here, it might be cleaner just
413 // to track this extra bit in the state itself.
414 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
415 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000416 }
417
418 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
419 const ExplodedNode *PrevN,
420 BugReporterContext &BRC,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000421 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000422
David Blaikied15481c2014-08-29 18:18:43 +0000423 std::unique_ptr<PathDiagnosticPiece>
424 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
425 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000426 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000427 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000428
429 PathDiagnosticLocation L =
430 PathDiagnosticLocation::createEndOfPath(EndPathNode,
431 BRC.getSourceManager());
432 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000433 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
434 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000435 }
436
Anna Zakscba4f292012-03-16 23:24:20 +0000437 private:
438 class StackHintGeneratorForReallocationFailed
439 : public StackHintGeneratorForSymbol {
440 public:
441 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
442 : StackHintGeneratorForSymbol(S, M) {}
443
Craig Topperfb6b25b2014-03-15 04:29:04 +0000444 std::string getMessageForArg(const Expr *ArgE,
445 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000446 // Printed parameters start at 1, not 0.
447 ++ArgIndex;
448
Anna Zakscba4f292012-03-16 23:24:20 +0000449 SmallString<200> buf;
450 llvm::raw_svector_ostream os(buf);
451
Jordan Rosec102b352012-09-22 01:24:42 +0000452 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
453 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000454
455 return os.str();
456 }
457
Craig Topperfb6b25b2014-03-15 04:29:04 +0000458 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000459 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000460 }
461 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000462 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000463};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000464} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000465
Jordan Rose0c153cb2012-11-02 01:54:06 +0000466REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
467REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000468
Anna Zaks67291b92012-11-13 03:18:01 +0000469// A map from the freed symbol to the symbol representing the return value of
470// the free function.
471REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
472
Anna Zaksbb1ef902012-02-11 21:02:35 +0000473namespace {
474class StopTrackingCallback : public SymbolVisitor {
475 ProgramStateRef state;
476public:
477 StopTrackingCallback(ProgramStateRef st) : state(st) {}
478 ProgramStateRef getState() const { return state; }
479
Craig Topperfb6b25b2014-03-15 04:29:04 +0000480 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000481 state = state->remove<RegionState>(sym);
482 return true;
483 }
484};
485} // end anonymous namespace
486
Anna Zaks3d348342012-02-14 21:55:24 +0000487void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000488 if (II_malloc)
489 return;
490 II_malloc = &Ctx.Idents.get("malloc");
491 II_free = &Ctx.Idents.get("free");
492 II_realloc = &Ctx.Idents.get("realloc");
493 II_reallocf = &Ctx.Idents.get("reallocf");
494 II_calloc = &Ctx.Idents.get("calloc");
495 II_valloc = &Ctx.Idents.get("valloc");
496 II_strdup = &Ctx.Idents.get("strdup");
497 II_strndup = &Ctx.Idents.get("strndup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000498 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000499}
500
Anna Zaks3d348342012-02-14 21:55:24 +0000501bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks46d01602012-05-18 01:16:10 +0000502 if (isFreeFunction(FD, C))
503 return true;
504
505 if (isAllocationFunction(FD, C))
506 return true;
507
Anton Yartsev13df0362013-03-25 01:35:45 +0000508 if (isStandardNewDelete(FD, C))
509 return true;
510
Anna Zaks46d01602012-05-18 01:16:10 +0000511 return false;
512}
513
514bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
515 ASTContext &C) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000516 if (!FD)
517 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000518
Jordan Rose6cd16c52012-07-10 23:13:01 +0000519 if (FD->getKind() == Decl::Function) {
520 IdentifierInfo *FunI = FD->getIdentifier();
521 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000522
Jordan Rose6cd16c52012-07-10 23:13:01 +0000523 if (FunI == II_malloc || FunI == II_realloc ||
524 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000525 FunI == II_strdup || FunI == II_strndup || FunI == II_kmalloc)
Jordan Rose6cd16c52012-07-10 23:13:01 +0000526 return true;
527 }
Anna Zaks3d348342012-02-14 21:55:24 +0000528
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000529 if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000530 for (const auto *I : FD->specific_attrs<OwnershipAttr>())
531 if (I->getOwnKind() == OwnershipAttr::Returns)
Anna Zaks46d01602012-05-18 01:16:10 +0000532 return true;
533 return false;
534}
535
536bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
537 if (!FD)
538 return false;
539
Jordan Rose6cd16c52012-07-10 23:13:01 +0000540 if (FD->getKind() == Decl::Function) {
541 IdentifierInfo *FunI = FD->getIdentifier();
542 initIdentifierInfo(C);
Anna Zaks46d01602012-05-18 01:16:10 +0000543
Jordan Rose6cd16c52012-07-10 23:13:01 +0000544 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
545 return true;
546 }
Anna Zaks3d348342012-02-14 21:55:24 +0000547
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000548 if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000549 for (const auto *I : FD->specific_attrs<OwnershipAttr>())
550 if (I->getOwnKind() == OwnershipAttr::Takes ||
551 I->getOwnKind() == OwnershipAttr::Holds)
Anna Zaks46d01602012-05-18 01:16:10 +0000552 return true;
Anna Zaks3d348342012-02-14 21:55:24 +0000553 return false;
554}
555
Anton Yartsev8b662702013-03-28 16:10:38 +0000556// Tells if the callee is one of the following:
557// 1) A global non-placement new/delete operator function.
558// 2) A global placement operator function with the single placement argument
559// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000560bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
561 ASTContext &C) const {
562 if (!FD)
563 return false;
564
565 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
566 if (Kind != OO_New && Kind != OO_Array_New &&
567 Kind != OO_Delete && Kind != OO_Array_Delete)
568 return false;
569
Anton Yartsev8b662702013-03-28 16:10:38 +0000570 // Skip all operator new/delete methods.
571 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000572 return false;
573
574 // Return true if tested operator is a standard placement nothrow operator.
575 if (FD->getNumParams() == 2) {
576 QualType T = FD->getParamDecl(1)->getType();
577 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
578 return II->getName().equals("nothrow_t");
579 }
580
581 // Skip placement operators.
582 if (FD->getNumParams() != 1 || FD->isVariadic())
583 return false;
584
585 // One of the standard new/new[]/delete/delete[] non-placement operators.
586 return true;
587}
588
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000589llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
590 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
591 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
592 //
593 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
594 //
595 // One of the possible flags is M_ZERO, which means 'give me back an
596 // allocation which is already zeroed', like calloc.
597
598 // 2-argument kmalloc(), as used in the Linux kernel:
599 //
600 // void *kmalloc(size_t size, gfp_t flags);
601 //
602 // Has the similar flag value __GFP_ZERO.
603
604 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
605 // code could be shared.
606
607 ASTContext &Ctx = C.getASTContext();
608 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
609
610 if (!KernelZeroFlagVal.hasValue()) {
611 if (OS == llvm::Triple::FreeBSD)
612 KernelZeroFlagVal = 0x0100;
613 else if (OS == llvm::Triple::NetBSD)
614 KernelZeroFlagVal = 0x0002;
615 else if (OS == llvm::Triple::OpenBSD)
616 KernelZeroFlagVal = 0x0008;
617 else if (OS == llvm::Triple::Linux)
618 // __GFP_ZERO
619 KernelZeroFlagVal = 0x8000;
620 else
621 // FIXME: We need a more general way of getting the M_ZERO value.
622 // See also: O_CREAT in UnixAPIChecker.cpp.
623
624 // Fall back to normal malloc behavior on platforms where we don't
625 // know M_ZERO.
626 return None;
627 }
628
629 // We treat the last argument as the flags argument, and callers fall-back to
630 // normal malloc on a None return. This works for the FreeBSD kernel malloc
631 // as well as Linux kmalloc.
632 if (CE->getNumArgs() < 2)
633 return None;
634
635 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
636 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
637 if (!V.getAs<NonLoc>()) {
638 // The case where 'V' can be a location can only be due to a bad header,
639 // so in this case bail out.
640 return None;
641 }
642
643 NonLoc Flags = V.castAs<NonLoc>();
644 NonLoc ZeroFlag = C.getSValBuilder()
645 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
646 .castAs<NonLoc>();
647 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
648 Flags, ZeroFlag,
649 FlagsEx->getType());
650 if (MaskedFlagsUC.isUnknownOrUndef())
651 return None;
652 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
653
654 // Check if maskedFlags is non-zero.
655 ProgramStateRef TrueState, FalseState;
656 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
657
658 // If M_ZERO is set, treat this like calloc (initialized).
659 if (TrueState && !FalseState) {
660 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
661 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
662 }
663
664 return None;
665}
666
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000667void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000668 if (C.wasInlined)
669 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000670
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000671 const FunctionDecl *FD = C.getCalleeDecl(CE);
672 if (!FD)
673 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000674
Anna Zaks40a7eb32012-02-22 19:24:52 +0000675 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000676 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000677
678 if (FD->getKind() == Decl::Function) {
679 initIdentifierInfo(C.getASTContext());
680 IdentifierInfo *FunI = FD->getIdentifier();
681
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000682 if (FunI == II_malloc) {
683 if (CE->getNumArgs() < 1)
684 return;
685 if (CE->getNumArgs() < 3) {
686 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
687 } else if (CE->getNumArgs() == 3) {
688 llvm::Optional<ProgramStateRef> MaybeState =
689 performKernelMalloc(CE, C, State);
690 if (MaybeState.hasValue())
691 State = MaybeState.getValue();
692 else
693 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
694 }
695 } else if (FunI == II_kmalloc) {
696 llvm::Optional<ProgramStateRef> MaybeState =
697 performKernelMalloc(CE, C, State);
698 if (MaybeState.hasValue())
699 State = MaybeState.getValue();
700 else
701 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
702 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000703 if (CE->getNumArgs() < 1)
704 return;
705 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
706 } else if (FunI == II_realloc) {
707 State = ReallocMem(C, CE, false);
708 } else if (FunI == II_reallocf) {
709 State = ReallocMem(C, CE, true);
710 } else if (FunI == II_calloc) {
711 State = CallocMem(C, CE);
712 } else if (FunI == II_free) {
713 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
714 } else if (FunI == II_strdup) {
715 State = MallocUpdateRefState(C, CE, State);
716 } else if (FunI == II_strndup) {
717 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev13df0362013-03-25 01:35:45 +0000718 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000719 else if (isStandardNewDelete(FD, C.getASTContext())) {
720 // Process direct calls to operator new/new[]/delete/delete[] functions
721 // as distinct from new/new[]/delete/delete[] expressions that are
722 // processed by the checkPostStmt callbacks for CXXNewExpr and
723 // CXXDeleteExpr.
724 OverloadedOperatorKind K = FD->getOverloadedOperator();
725 if (K == OO_New)
726 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
727 AF_CXXNew);
728 else if (K == OO_Array_New)
729 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
730 AF_CXXNewArray);
731 else if (K == OO_Delete || K == OO_Array_Delete)
732 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
733 else
734 llvm_unreachable("not a new/delete operator");
Jordan Rose6cd16c52012-07-10 23:13:01 +0000735 }
736 }
737
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000738 if (ChecksEnabled[CK_MallocOptimistic] ||
739 ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000740 // Check all the attributes, if there are any.
741 // There can be multiple of these attributes.
742 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000743 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
744 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000745 case OwnershipAttr::Returns:
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000746 State = MallocMemReturnsAttr(C, CE, I);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000747 break;
748 case OwnershipAttr::Takes:
749 case OwnershipAttr::Holds:
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000750 State = FreeMemAttr(C, CE, I);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000751 break;
752 }
753 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000754 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000755 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000756}
757
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000758static QualType getDeepPointeeType(QualType T) {
759 QualType Result = T, PointeeType = T->getPointeeType();
760 while (!PointeeType.isNull()) {
761 Result = PointeeType;
762 PointeeType = PointeeType->getPointeeType();
763 }
764 return Result;
765}
766
767static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
768
769 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
770 if (!ConstructE)
771 return false;
772
773 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
774 return false;
775
776 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
777
778 // Iterate over the constructor parameters.
779 for (const auto *CtorParam : CtorD->params()) {
780
781 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
782 if (CtorParamPointeeT.isNull())
783 continue;
784
785 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
786
787 if (CtorParamPointeeT->getAsCXXRecordDecl())
788 return true;
789 }
790
791 return false;
792}
793
Anton Yartsev13df0362013-03-25 01:35:45 +0000794void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
795 CheckerContext &C) const {
796
797 if (NE->getNumPlacementArgs())
798 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
799 E = NE->placement_arg_end(); I != E; ++I)
800 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
801 checkUseAfterFree(Sym, C, *I);
802
Anton Yartsev13df0362013-03-25 01:35:45 +0000803 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
804 return;
805
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000806 ParentMap &PM = C.getLocationContext()->getParentMap();
807 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
808 return;
809
Anton Yartsev13df0362013-03-25 01:35:45 +0000810 ProgramStateRef State = C.getState();
811 // The return value from operator new is bound to a specified initialization
812 // value (if any) and we don't want to loose this value. So we call
813 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
814 // existing binding.
Anton Yartsev05789592013-03-28 17:05:19 +0000815 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
816 : AF_CXXNew);
Anton Yartsev13df0362013-03-25 01:35:45 +0000817 C.addTransition(State);
818}
819
820void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
821 CheckerContext &C) const {
822
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000823 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +0000824 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
825 checkUseAfterFree(Sym, C, DE->getArgument());
826
Anton Yartsev13df0362013-03-25 01:35:45 +0000827 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
828 return;
829
830 ProgramStateRef State = C.getState();
831 bool ReleasedAllocated;
832 State = FreeMemAux(C, DE->getArgument(), DE, State,
833 /*Hold*/false, ReleasedAllocated);
834
835 C.addTransition(State);
836}
837
Jordan Rose613f3c02013-03-09 00:59:10 +0000838static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
839 // If the first selector piece is one of the names below, assume that the
840 // object takes ownership of the memory, promising to eventually deallocate it
841 // with free().
842 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
843 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
844 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
845 if (FirstSlot == "dataWithBytesNoCopy" ||
846 FirstSlot == "initWithBytesNoCopy" ||
847 FirstSlot == "initWithCharactersNoCopy")
848 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000849
850 return false;
851}
852
Jordan Rose613f3c02013-03-09 00:59:10 +0000853static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
854 Selector S = Call.getSelector();
855
856 // FIXME: We should not rely on fully-constrained symbols being folded.
857 for (unsigned i = 1; i < S.getNumArgs(); ++i)
858 if (S.getNameForSlot(i).equals("freeWhenDone"))
859 return !Call.getArgSVal(i).isZeroConstant();
860
861 return None;
862}
863
Anna Zaks67291b92012-11-13 03:18:01 +0000864void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
865 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +0000866 if (C.wasInlined)
867 return;
868
Jordan Rose613f3c02013-03-09 00:59:10 +0000869 if (!isKnownDeallocObjCMethodName(Call))
870 return;
Anna Zaks67291b92012-11-13 03:18:01 +0000871
Jordan Rose613f3c02013-03-09 00:59:10 +0000872 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
873 if (!*FreeWhenDone)
874 return;
875
876 bool ReleasedAllocatedMemory;
877 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
878 Call.getOriginExpr(), C.getState(),
879 /*Hold=*/true, ReleasedAllocatedMemory,
880 /*RetNullOnFailure=*/true);
881
882 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +0000883}
884
Richard Smith852e9ce2013-11-27 01:46:48 +0000885ProgramStateRef
886MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
887 const OwnershipAttr *Att) const {
888 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +0000889 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000890
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000891 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000892 if (I != E) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000893 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekd21139a2010-07-31 01:52:11 +0000894 }
Anna Zaks40a7eb32012-02-22 19:24:52 +0000895 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekd21139a2010-07-31 01:52:11 +0000896}
897
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000898ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000899 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000900 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000901 ProgramStateRef State,
902 AllocationFamily Family) {
Anna Zaks3563fde2012-06-07 03:57:32 +0000903
904 // Bind the return value to the symbolic value from the heap region.
905 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
906 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +0000907 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +0000908 SValBuilder &svalBuilder = C.getSValBuilder();
909 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000910 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
911 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +0000912 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000913
Anna Zaksd5157482012-02-15 00:11:22 +0000914 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000915 if (!RetVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +0000916 return nullptr;
Anna Zaksd5157482012-02-15 00:11:22 +0000917
Jordy Rose674bd552010-07-04 00:00:41 +0000918 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +0000919 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000920
Jordy Rose674bd552010-07-04 00:00:41 +0000921 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +0000922 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +0000923 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +0000924 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +0000925 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +0000926 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000927 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000928 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +0000929 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +0000930 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +0000931 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +0000932
Anton Yartsev05789592013-03-28 17:05:19 +0000933 State = State->assume(extentMatchesSize, true);
934 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +0000935 }
Ted Kremenek90af9092010-12-02 07:49:45 +0000936
Anton Yartsev05789592013-03-28 17:05:19 +0000937 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000938}
939
940ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +0000941 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +0000942 ProgramStateRef State,
943 AllocationFamily Family) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000944 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +0000945 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +0000946
947 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000948 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +0000949 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +0000950
Ted Kremenek90af9092010-12-02 07:49:45 +0000951 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000952 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +0000953
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000954 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +0000955 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000956}
957
Anna Zaks40a7eb32012-02-22 19:24:52 +0000958ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
959 const CallExpr *CE,
Richard Smith852e9ce2013-11-27 01:46:48 +0000960 const OwnershipAttr *Att) const {
961 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +0000962 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000963
Anna Zaks8dc53af2012-03-01 22:06:06 +0000964 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000965 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +0000966
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000967 for (const auto &Arg : Att->args()) {
968 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000969 Att->getOwnKind() == OwnershipAttr::Holds,
970 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +0000971 if (StateI)
972 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000973 }
Anna Zaks8dc53af2012-03-01 22:06:06 +0000974 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000975}
976
Ted Kremenek49b1e382012-01-26 21:29:00 +0000977ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +0000978 const CallExpr *CE,
979 ProgramStateRef state,
980 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000981 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000982 bool &ReleasedAllocated,
983 bool ReturnsNullOnFailure) const {
Anna Zaksb508d292012-04-10 23:41:11 +0000984 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +0000985 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +0000986
Anna Zaks67291b92012-11-13 03:18:01 +0000987 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
988 ReleasedAllocated, ReturnsNullOnFailure);
989}
990
Anna Zaksa14c1d02012-11-13 19:47:40 +0000991/// Checks if the previous call to free on the given symbol failed - if free
992/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +0000993static bool didPreviousFreeFail(ProgramStateRef State,
994 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +0000995 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +0000996 if (Ret) {
997 assert(*Ret && "We should not store the null return symbol");
998 ConstraintManager &CMgr = State->getConstraintManager();
999 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001000 RetStatusSymbol = *Ret;
1001 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001002 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001003 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001004}
1005
Anton Yartsev05789592013-03-28 17:05:19 +00001006AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001007 const Stmt *S) const {
1008 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001009 return AF_None;
1010
Anton Yartseve3377fb2013-04-04 23:46:29 +00001011 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001012 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001013
1014 if (!FD)
1015 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1016
Anton Yartsev05789592013-03-28 17:05:19 +00001017 ASTContext &Ctx = C.getASTContext();
1018
Anton Yartseve3377fb2013-04-04 23:46:29 +00001019 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx))
Anton Yartsev05789592013-03-28 17:05:19 +00001020 return AF_Malloc;
1021
1022 if (isStandardNewDelete(FD, Ctx)) {
1023 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001024 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001025 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001026 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001027 return AF_CXXNewArray;
1028 }
1029
1030 return AF_None;
1031 }
1032
Anton Yartseve3377fb2013-04-04 23:46:29 +00001033 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1034 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1035
1036 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001037 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1038
Anton Yartseve3377fb2013-04-04 23:46:29 +00001039 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001040 return AF_Malloc;
1041
1042 return AF_None;
1043}
1044
1045bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1046 const Expr *E) const {
1047 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1048 // FIXME: This doesn't handle indirect calls.
1049 const FunctionDecl *FD = CE->getDirectCallee();
1050 if (!FD)
1051 return false;
1052
1053 os << *FD;
1054 if (!FD->isOverloadedOperator())
1055 os << "()";
1056 return true;
1057 }
1058
1059 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1060 if (Msg->isInstanceMessage())
1061 os << "-";
1062 else
1063 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001064 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001065 return true;
1066 }
1067
1068 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1069 os << "'"
1070 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1071 << "'";
1072 return true;
1073 }
1074
1075 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1076 os << "'"
1077 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1078 << "'";
1079 return true;
1080 }
1081
1082 return false;
1083}
1084
1085void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1086 const Expr *E) const {
1087 AllocationFamily Family = getAllocationFamily(C, E);
1088
1089 switch(Family) {
1090 case AF_Malloc: os << "malloc()"; return;
1091 case AF_CXXNew: os << "'new'"; return;
1092 case AF_CXXNewArray: os << "'new[]'"; return;
1093 case AF_None: llvm_unreachable("not a deallocation expression");
1094 }
1095}
1096
1097void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1098 AllocationFamily Family) const {
1099 switch(Family) {
1100 case AF_Malloc: os << "free()"; return;
1101 case AF_CXXNew: os << "'delete'"; return;
1102 case AF_CXXNewArray: os << "'delete[]'"; return;
1103 case AF_None: llvm_unreachable("suspicious AF_None argument");
1104 }
1105}
1106
Anna Zaks0d6989b2012-06-22 02:04:31 +00001107ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1108 const Expr *ArgExpr,
1109 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001110 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001111 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001112 bool &ReleasedAllocated,
1113 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001114
Anna Zaks67291b92012-11-13 03:18:01 +00001115 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001116 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001117 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001118 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001119
1120 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001121 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001122 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001123
Anna Zaksad01ef52012-02-14 00:26:13 +00001124 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001125 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001126 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001127 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001128 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001129
Jordy Rose3597b212010-06-07 19:32:37 +00001130 // Unknown values could easily be okay
1131 // Undefined values are handled elsewhere
1132 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001133 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001134
Jordy Rose3597b212010-06-07 19:32:37 +00001135 const MemRegion *R = ArgVal.getAsRegion();
1136
1137 // Nonlocs can't be freed, of course.
1138 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1139 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001140 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001141 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001142 }
1143
1144 R = R->StripCasts();
1145
1146 // Blocks might show up as heap data, but should not be free()d
1147 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001148 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001149 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001150 }
1151
1152 const MemSpaceRegion *MS = R->getMemorySpace();
1153
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001154 // Parameters, locals, statics, globals, and memory returned by alloca()
1155 // shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001156 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1157 // FIXME: at the time this code was written, malloc() regions were
1158 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1159 // This means that there isn't actually anything from HeapSpaceRegion
1160 // that should be freed, even though we allow it here.
1161 // Of course, free() can work on memory allocated outside the current
1162 // function, so UnknownSpaceRegion is always a possibility.
1163 // False negatives are better than false positives.
1164
Anton Yartsev05789592013-03-28 17:05:19 +00001165 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001166 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001167 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001168
1169 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001170 // Various cases could lead to non-symbol values here.
1171 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001172 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001173 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001174
Anna Zaksc89ad072013-02-07 23:05:47 +00001175 SymbolRef SymBase = SrBase->getSymbol();
1176 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001177 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001178
Anton Yartseve3377fb2013-04-04 23:46:29 +00001179 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001180
Anna Zaks93a21a82013-04-09 00:30:28 +00001181 // Check for double free first.
1182 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001183 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1184 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1185 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001186 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001187
Anna Zaks93a21a82013-04-09 00:30:28 +00001188 // If the pointer is allocated or escaped, but we are now trying to free it,
1189 // check that the call to free is proper.
1190 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1191
1192 // Check if an expected deallocation function matches the real one.
1193 bool DeallocMatchesAlloc =
1194 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1195 if (!DeallocMatchesAlloc) {
1196 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001197 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001198 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001199 }
1200
1201 // Check if the memory location being freed is the actual location
1202 // allocated, or an offset.
1203 RegionOffset Offset = R->getAsOffset();
1204 if (Offset.isValid() &&
1205 !Offset.hasSymbolicOffset() &&
1206 Offset.getOffset() != 0) {
1207 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1208 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1209 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001210 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001211 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001212 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001213 }
1214
Craig Topper0dbb7832014-05-27 02:45:47 +00001215 ReleasedAllocated = (RsBase != nullptr) && RsBase->isAllocated();
Anna Zaksfe6eb672012-08-24 02:28:20 +00001216
Anna Zaksa14c1d02012-11-13 19:47:40 +00001217 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001218 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001219
Anna Zaks67291b92012-11-13 03:18:01 +00001220 // Keep track of the return value. If it is NULL, we will know that free
1221 // failed.
1222 if (ReturnsNullOnFailure) {
1223 SVal RetVal = C.getSVal(ParentExpr);
1224 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1225 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001226 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1227 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001228 }
1229 }
1230
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001231 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1232 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001233 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001234 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001235 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001236 RefState::getRelinquished(Family,
1237 ParentExpr));
1238
1239 return State->set<RegionState>(SymBase,
1240 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001241}
1242
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001243Optional<MallocChecker::CheckKind>
1244MallocChecker::getCheckIfTracked(AllocationFamily Family) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001245 switch (Family) {
1246 case AF_Malloc: {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001247 if (ChecksEnabled[CK_MallocOptimistic]) {
1248 return CK_MallocOptimistic;
1249 } else if (ChecksEnabled[CK_MallocPessimistic]) {
1250 return CK_MallocPessimistic;
1251 }
1252 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001253 }
1254 case AF_CXXNew:
1255 case AF_CXXNewArray: {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001256 if (ChecksEnabled[CK_NewDeleteChecker]) {
1257 return CK_NewDeleteChecker;
1258 }
1259 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001260 }
1261 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001262 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001263 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001264 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001265 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001266}
1267
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001268Optional<MallocChecker::CheckKind>
1269MallocChecker::getCheckIfTracked(CheckerContext &C,
1270 const Stmt *AllocDeallocStmt) const {
1271 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt));
Anton Yartseve3377fb2013-04-04 23:46:29 +00001272}
1273
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001274Optional<MallocChecker::CheckKind>
1275MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001276
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001277 const RefState *RS = C.getState()->get<RegionState>(Sym);
1278 assert(RS);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001279 return getCheckIfTracked(RS->getAllocationFamily());
Anton Yartseve3377fb2013-04-04 23:46:29 +00001280}
1281
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001282bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001283 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001284 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001285 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001286 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001287 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001288 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001289 else
1290 return false;
1291
1292 return true;
1293}
1294
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001295bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001296 const MemRegion *MR) {
1297 switch (MR->getKind()) {
1298 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001299 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001300 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001301 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001302 else
1303 os << "the address of a function";
1304 return true;
1305 }
1306 case MemRegion::BlockTextRegionKind:
1307 os << "block text";
1308 return true;
1309 case MemRegion::BlockDataRegionKind:
1310 // FIXME: where the block came from?
1311 os << "a block";
1312 return true;
1313 default: {
1314 const MemSpaceRegion *MS = MR->getMemorySpace();
1315
Anna Zaks8158ef02012-01-04 23:54:01 +00001316 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001317 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1318 const VarDecl *VD;
1319 if (VR)
1320 VD = VR->getDecl();
1321 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001322 VD = nullptr;
1323
Jordy Rose3597b212010-06-07 19:32:37 +00001324 if (VD)
1325 os << "the address of the local variable '" << VD->getName() << "'";
1326 else
1327 os << "the address of a local stack variable";
1328 return true;
1329 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001330
1331 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001332 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1333 const VarDecl *VD;
1334 if (VR)
1335 VD = VR->getDecl();
1336 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001337 VD = nullptr;
1338
Jordy Rose3597b212010-06-07 19:32:37 +00001339 if (VD)
1340 os << "the address of the parameter '" << VD->getName() << "'";
1341 else
1342 os << "the address of a parameter";
1343 return true;
1344 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001345
1346 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001347 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1348 const VarDecl *VD;
1349 if (VR)
1350 VD = VR->getDecl();
1351 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001352 VD = nullptr;
1353
Jordy Rose3597b212010-06-07 19:32:37 +00001354 if (VD) {
1355 if (VD->isStaticLocal())
1356 os << "the address of the static variable '" << VD->getName() << "'";
1357 else
1358 os << "the address of the global variable '" << VD->getName() << "'";
1359 } else
1360 os << "the address of a global variable";
1361 return true;
1362 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001363
1364 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001365 }
1366 }
1367}
1368
Anton Yartsev05789592013-03-28 17:05:19 +00001369void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1370 SourceRange Range,
1371 const Expr *DeallocExpr) const {
1372
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001373 if (!ChecksEnabled[CK_MallocOptimistic] &&
1374 !ChecksEnabled[CK_MallocPessimistic] &&
1375 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001376 return;
1377
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001378 Optional<MallocChecker::CheckKind> CheckKind =
1379 getCheckIfTracked(C, DeallocExpr);
1380 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001381 return;
1382
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001383 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001384 if (!BT_BadFree[*CheckKind])
1385 BT_BadFree[*CheckKind].reset(
1386 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1387
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001388 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001389 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001390
Jordy Rose3597b212010-06-07 19:32:37 +00001391 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001392 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1393 MR = ER->getSuperRegion();
1394
1395 if (MR && isa<AllocaRegion>(MR))
1396 os << "Memory allocated by alloca() should not be deallocated";
1397 else {
1398 os << "Argument to ";
1399 if (!printAllocDeallocName(os, C, DeallocExpr))
1400 os << "deallocator";
1401
1402 os << " is ";
1403 bool Summarized = MR ? SummarizeRegion(os, MR)
1404 : SummarizeValue(os, ArgVal);
1405 if (Summarized)
1406 os << ", which is not memory allocated by ";
Jordy Rose3597b212010-06-07 19:32:37 +00001407 else
Anton Yartsev05789592013-03-28 17:05:19 +00001408 os << "not memory allocated by ";
1409
1410 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose3597b212010-06-07 19:32:37 +00001411 }
Anton Yartsev05789592013-03-28 17:05:19 +00001412
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001413 BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001414 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001415 R->addRange(Range);
Jordan Rosee10d5a72012-11-02 01:53:40 +00001416 C.emitReport(R);
Jordy Rose3597b212010-06-07 19:32:37 +00001417 }
1418}
1419
Anton Yartseve3377fb2013-04-04 23:46:29 +00001420void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1421 SourceRange Range,
1422 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001423 const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001424 SymbolRef Sym,
1425 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001426
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001427 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001428 return;
1429
1430 if (ExplodedNode *N = C.generateSink()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001431 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001432 BT_MismatchedDealloc.reset(
1433 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1434 "Bad deallocator", "Memory Error"));
1435
Anton Yartsev05789592013-03-28 17:05:19 +00001436 SmallString<100> buf;
1437 llvm::raw_svector_ostream os(buf);
1438
1439 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1440 SmallString<20> AllocBuf;
1441 llvm::raw_svector_ostream AllocOs(AllocBuf);
1442 SmallString<20> DeallocBuf;
1443 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1444
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001445 if (OwnershipTransferred) {
1446 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1447 os << DeallocOs.str() << " cannot";
1448 else
1449 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001450
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001451 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001452
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001453 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1454 os << " allocated by " << AllocOs.str();
1455 } else {
1456 os << "Memory";
1457 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1458 os << " allocated by " << AllocOs.str();
1459
1460 os << " should be deallocated by ";
1461 printExpectedDeallocName(os, RS->getAllocationFamily());
1462
1463 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1464 os << ", not " << DeallocOs.str();
1465 }
Anton Yartsev05789592013-03-28 17:05:19 +00001466
Anton Yartseve3377fb2013-04-04 23:46:29 +00001467 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001468 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001469 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001470 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev05789592013-03-28 17:05:19 +00001471 C.emitReport(R);
1472 }
1473}
1474
Anna Zaksc89ad072013-02-07 23:05:47 +00001475void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001476 SourceRange Range, const Expr *DeallocExpr,
1477 const Expr *AllocExpr) const {
1478
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001479 if (!ChecksEnabled[CK_MallocOptimistic] &&
1480 !ChecksEnabled[CK_MallocPessimistic] &&
1481 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001482 return;
1483
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001484 Optional<MallocChecker::CheckKind> CheckKind =
1485 getCheckIfTracked(C, AllocExpr);
1486 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001487 return;
1488
Anna Zaksc89ad072013-02-07 23:05:47 +00001489 ExplodedNode *N = C.generateSink();
Craig Topper0dbb7832014-05-27 02:45:47 +00001490 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001491 return;
1492
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001493 if (!BT_OffsetFree[*CheckKind])
1494 BT_OffsetFree[*CheckKind].reset(
1495 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001496
1497 SmallString<100> buf;
1498 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001499 SmallString<20> AllocNameBuf;
1500 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001501
1502 const MemRegion *MR = ArgVal.getAsRegion();
1503 assert(MR && "Only MemRegion based symbols can have offset free errors");
1504
1505 RegionOffset Offset = MR->getAsOffset();
1506 assert((Offset.isValid() &&
1507 !Offset.hasSymbolicOffset() &&
1508 Offset.getOffset() != 0) &&
1509 "Only symbols with a valid offset can have offset free errors");
1510
1511 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1512
Anton Yartsev05789592013-03-28 17:05:19 +00001513 os << "Argument to ";
1514 if (!printAllocDeallocName(os, C, DeallocExpr))
1515 os << "deallocator";
1516 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001517 << offsetBytes
1518 << " "
1519 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001520 << " from the start of ";
1521 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1522 os << "memory allocated by " << AllocNameOs.str();
1523 else
1524 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001525
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001526 BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001527 R->markInteresting(MR->getBaseRegion());
1528 R->addRange(Range);
1529 C.emitReport(R);
1530}
1531
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001532void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1533 SymbolRef Sym) const {
1534
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001535 if (!ChecksEnabled[CK_MallocOptimistic] &&
1536 !ChecksEnabled[CK_MallocPessimistic] &&
1537 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001538 return;
1539
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001540 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1541 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001542 return;
1543
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001544 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001545 if (!BT_UseFree[*CheckKind])
1546 BT_UseFree[*CheckKind].reset(new BugType(
1547 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001548
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001549 BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001550 "Use of memory after it is freed", N);
1551
1552 R->markInteresting(Sym);
1553 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001554 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001555 C.emitReport(R);
1556 }
1557}
1558
1559void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1560 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001561 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001562
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001563 if (!ChecksEnabled[CK_MallocOptimistic] &&
1564 !ChecksEnabled[CK_MallocPessimistic] &&
1565 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001566 return;
1567
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001568 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1569 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001570 return;
1571
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001572 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001573 if (!BT_DoubleFree[*CheckKind])
1574 BT_DoubleFree[*CheckKind].reset(
1575 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001576
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001577 BugReport *R =
1578 new BugReport(*BT_DoubleFree[*CheckKind],
1579 (Released ? "Attempt to free released memory"
1580 : "Attempt to free non-owned memory"),
1581 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001582 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001583 R->markInteresting(Sym);
1584 if (PrevSym)
1585 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001586 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001587 C.emitReport(R);
1588 }
1589}
1590
Jordan Rose656fdd52014-01-08 18:46:55 +00001591void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1592
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001593 if (!ChecksEnabled[CK_NewDeleteChecker])
Jordan Rose656fdd52014-01-08 18:46:55 +00001594 return;
1595
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001596 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1597 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001598 return;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001599 assert(*CheckKind == CK_NewDeleteChecker && "invalid check kind");
Jordan Rose656fdd52014-01-08 18:46:55 +00001600
1601 if (ExplodedNode *N = C.generateSink()) {
1602 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001603 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1604 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001605
1606 BugReport *R = new BugReport(*BT_DoubleDelete,
1607 "Attempt to delete released memory", N);
1608
1609 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001610 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Jordan Rose656fdd52014-01-08 18:46:55 +00001611 C.emitReport(R);
1612 }
1613}
1614
Anna Zaks40a7eb32012-02-22 19:24:52 +00001615ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1616 const CallExpr *CE,
1617 bool FreesOnFail) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001618 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001619 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001620
Ted Kremenek49b1e382012-01-26 21:29:00 +00001621 ProgramStateRef state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +00001622 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001623 const LocationContext *LCtx = C.getLocationContext();
Anna Zaks31886862012-02-10 01:11:00 +00001624 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001625 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001626 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001627 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001628
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001629 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001630
Ted Kremenek90af9092010-12-02 07:49:45 +00001631 DefinedOrUnknownSVal PtrEQ =
1632 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001633
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001634 // Get the size argument. If there is no size arg then give up.
1635 const Expr *Arg1 = CE->getArg(1);
1636 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00001637 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001638
1639 // Get the value of the size argument.
Anna Zaks31886862012-02-10 01:11:00 +00001640 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001641 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001642 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001643 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001644
1645 // Compare the size argument to 0.
1646 DefinedOrUnknownSVal SizeZero =
1647 svalBuilder.evalEQ(state, Arg1Val,
1648 svalBuilder.makeIntValWithPtrWidth(0, false));
1649
Anna Zaksd56c8792012-02-13 18:05:39 +00001650 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001651 std::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001652 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001653 std::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001654 // We only assume exceptional states if they are definitely true; if the
1655 // state is under-constrained, assume regular realloc behavior.
1656 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1657 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1658
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001659 // If the ptr is NULL and the size is not 0, the call is equivalent to
1660 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001661 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001662 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001663 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001664 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001665 }
1666
Anna Zaksd56c8792012-02-13 18:05:39 +00001667 if (PrtIsNull && SizeIsZero)
Craig Topper0dbb7832014-05-27 02:45:47 +00001668 return nullptr;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001669
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001670 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001671 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001672 SymbolRef FromPtr = arg0Val.getAsSymbol();
1673 SVal RetVal = state->getSVal(CE, LCtx);
1674 SymbolRef ToPtr = RetVal.getAsSymbol();
1675 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00001676 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00001677
Anna Zaksfe6eb672012-08-24 02:28:20 +00001678 bool ReleasedAllocated = false;
1679
Anna Zaksd56c8792012-02-13 18:05:39 +00001680 // If the size is 0, free the memory.
1681 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001682 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1683 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001684 // The semantics of the return value are:
1685 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001686 // to free() is returned. We just free the input pointer and do not add
1687 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001688 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001689 }
1690
1691 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001692 if (ProgramStateRef stateFree =
1693 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1694
Anna Zaksd56c8792012-02-13 18:05:39 +00001695 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1696 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001697 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001698 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001699
Anna Zaks75cfbb62012-09-12 22:57:34 +00001700 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1701 if (FreesOnFail)
1702 Kind = RPIsFreeOnFailure;
1703 else if (!ReleasedAllocated)
1704 Kind = RPDoNotTrackAfterFailure;
1705
Anna Zaksfe6eb672012-08-24 02:28:20 +00001706 // Record the info about the reallocated symbol so that we could properly
1707 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001708 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001709 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001710 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001711 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001712 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001713 }
Craig Topper0dbb7832014-05-27 02:45:47 +00001714 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001715}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001716
Anna Zaks40a7eb32012-02-22 19:24:52 +00001717ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaksb508d292012-04-10 23:41:11 +00001718 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001719 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001720
Ted Kremenek49b1e382012-01-26 21:29:00 +00001721 ProgramStateRef state = C.getState();
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001722 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001723 const LocationContext *LCtx = C.getLocationContext();
1724 SVal count = state->getSVal(CE->getArg(0), LCtx);
1725 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001726 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1727 svalBuilder.getContext().getSizeType());
1728 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001729
Anna Zaks40a7eb32012-02-22 19:24:52 +00001730 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001731}
1732
Anna Zaksfc2e1532012-03-21 19:45:08 +00001733LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00001734MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1735 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00001736 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00001737 // Walk the ExplodedGraph backwards and find the first node that referred to
1738 // the tracked symbol.
1739 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001740 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00001741
1742 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00001743 ProgramStateRef State = N->getState();
1744 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00001745 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001746
1747 // Find the most recent expression bound to the symbol in the current
1748 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00001749 if (!ReferenceRegion) {
1750 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1751 SVal Val = State->getSVal(MR);
1752 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00001753 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00001754 // Do not show local variables belonging to a function other than
1755 // where the error is reported.
1756 if (!VR ||
1757 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1758 ReferenceRegion = MR;
1759 }
1760 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00001761 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00001762
Anna Zaks43ffba22012-02-27 23:40:55 +00001763 // Allocation node, is the last node in the current context in which the
1764 // symbol was tracked.
1765 if (N->getLocationContext() == LeakContext)
1766 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001767 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00001768 }
1769
Anna Zaksa043d0c2013-01-08 00:25:29 +00001770 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00001771}
1772
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001773void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1774 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001775
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001776 if (!ChecksEnabled[CK_MallocOptimistic] &&
1777 !ChecksEnabled[CK_MallocPessimistic] &&
1778 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001779 return;
1780
Jordan Rose26330562013-04-05 17:55:00 +00001781 const RefState *RS = C.getState()->get<RegionState>(Sym);
1782 assert(RS && "cannot leak an untracked symbol");
1783 AllocationFamily Family = RS->getAllocationFamily();
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001784 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
1785 if (!CheckKind.hasValue())
Anton Yartsev6e499252013-04-05 02:25:02 +00001786 return;
1787
Jordan Rose26330562013-04-05 17:55:00 +00001788 // Special case for new and new[]; these are controlled by a separate checker
1789 // flag so that they can be selectively disabled.
1790 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001791 if (!ChecksEnabled[CK_NewDeleteLeaksChecker])
Jordan Rose26330562013-04-05 17:55:00 +00001792 return;
1793
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001794 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001795 if (!BT_Leak[*CheckKind]) {
1796 BT_Leak[*CheckKind].reset(
1797 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001798 // Leaks should not be reported if they are post-dominated by a sink:
1799 // (1) Sinks are higher importance bugs.
1800 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1801 // with __noreturn functions such as assert() or exit(). We choose not
1802 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001803 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001804 }
1805
Anna Zaksdf901a42012-02-23 21:38:21 +00001806 // Most bug reports are cached at the location where they occurred.
1807 // With leaks, we want to unique them by the location where they were
1808 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00001809 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00001810 const ExplodedNode *AllocNode = nullptr;
1811 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001812 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Anna Zaksa043d0c2013-01-08 00:25:29 +00001813
1814 ProgramPoint P = AllocNode->getLocation();
Craig Topper0dbb7832014-05-27 02:45:47 +00001815 const Stmt *AllocationStmt = nullptr;
David Blaikie87396b92013-02-21 22:23:56 +00001816 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001817 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00001818 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001819 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00001820 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00001821 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1822 C.getSourceManager(),
1823 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00001824
Anna Zaksfc2e1532012-03-21 19:45:08 +00001825 SmallString<200> buf;
1826 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001827 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00001828 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001829 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00001830 } else {
1831 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00001832 }
1833
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001834 BugReport *R =
1835 new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1836 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00001837 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001838 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Jordan Rosee10d5a72012-11-02 01:53:40 +00001839 C.emitReport(R);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001840}
1841
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00001842void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1843 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00001844{
Zhongxing Xubce831f2010-08-15 08:19:57 +00001845 if (!SymReaper.hasDeadSymbols())
1846 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00001847
Ted Kremenek49b1e382012-01-26 21:29:00 +00001848 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001849 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00001850 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001851
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001852 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00001853 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1854 if (SymReaper.isDead(I->first)) {
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001855 if (I->second.isAllocated())
Anna Zaks78edc2f2012-02-09 06:48:19 +00001856 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00001857 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001858 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00001859
Zhongxing Xuc7460962009-11-13 07:48:11 +00001860 }
1861 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001862
Anna Zaksd56c8792012-02-13 18:05:39 +00001863 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00001864 ReallocPairsTy RP = state->get<ReallocPairs>();
1865 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00001866 if (SymReaper.isDead(I->first) ||
1867 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00001868 state = state->remove<ReallocPairs>(I->first);
1869 }
1870 }
1871
Anna Zaks67291b92012-11-13 03:18:01 +00001872 // Cleanup the FreeReturnValue Map.
1873 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1874 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1875 if (SymReaper.isDead(I->first) ||
1876 SymReaper.isDead(I->second)) {
1877 state = state->remove<FreeReturnValue>(I->first);
1878 }
1879 }
1880
Anna Zaksdf901a42012-02-23 21:38:21 +00001881 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001882 ExplodedNode *N = C.getPredecessor();
1883 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00001884 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001885 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper2341c0d2013-07-04 03:08:24 +00001886 for (SmallVectorImpl<SymbolRef>::iterator
1887 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001888 reportLeak(*I, N, C);
Anna Zaks78edc2f2012-02-09 06:48:19 +00001889 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001890 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001891
Anna Zaksdf901a42012-02-23 21:38:21 +00001892 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001893}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00001894
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001895void MallocChecker::checkPreCall(const CallEvent &Call,
1896 CheckerContext &C) const {
1897
Jordan Rose656fdd52014-01-08 18:46:55 +00001898 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
1899 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
1900 if (!Sym || checkDoubleDelete(Sym, C))
1901 return;
1902 }
1903
Anna Zaks46d01602012-05-18 01:16:10 +00001904 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001905 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
1906 const FunctionDecl *FD = FC->getDecl();
1907 if (!FD)
1908 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00001909
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001910 if ((ChecksEnabled[CK_MallocOptimistic] ||
1911 ChecksEnabled[CK_MallocPessimistic]) &&
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001912 isFreeFunction(FD, C.getASTContext()))
1913 return;
Anna Zaks3d348342012-02-14 21:55:24 +00001914
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001915 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001916 isStandardNewDelete(FD, C.getASTContext()))
1917 return;
1918 }
1919
1920 // Check if the callee of a method is deleted.
1921 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
1922 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
1923 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
1924 return;
1925 }
1926
1927 // Check arguments for being used after free.
1928 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
1929 SVal ArgSVal = Call.getArgSVal(I);
1930 if (ArgSVal.getAs<Loc>()) {
1931 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00001932 if (!Sym)
1933 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001934 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00001935 return;
1936 }
1937 }
1938}
1939
Anna Zaksa1b227b2012-02-08 23:16:56 +00001940void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1941 const Expr *E = S->getRetValue();
1942 if (!E)
1943 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00001944
1945 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00001946 ProgramStateRef State = C.getState();
1947 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00001948 SymbolRef Sym = RetVal.getAsSymbol();
1949 if (!Sym)
1950 // If we are returning a field of the allocated struct or an array element,
1951 // the callee could still free the memory.
1952 // TODO: This logic should be a part of generic symbol escape callback.
1953 if (const MemRegion *MR = RetVal.getAsRegion())
1954 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1955 if (const SymbolicRegion *BMR =
1956 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1957 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00001958
Anna Zaks3aa52252012-02-11 21:44:39 +00001959 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00001960 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00001961 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00001962}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00001963
Anna Zaks9fe80982012-03-22 00:57:20 +00001964// TODO: Blocks should be either inlined or should call invalidate regions
1965// upon invocation. After that's in place, special casing here will not be
1966// needed.
1967void MallocChecker::checkPostStmt(const BlockExpr *BE,
1968 CheckerContext &C) const {
1969
1970 // Scan the BlockDecRefExprs for any object the retain count checker
1971 // may be tracking.
1972 if (!BE->getBlockDecl()->hasCaptures())
1973 return;
1974
1975 ProgramStateRef state = C.getState();
1976 const BlockDataRegion *R =
1977 cast<BlockDataRegion>(state->getSVal(BE,
1978 C.getLocationContext()).getAsRegion());
1979
1980 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1981 E = R->referenced_vars_end();
1982
1983 if (I == E)
1984 return;
1985
1986 SmallVector<const MemRegion*, 10> Regions;
1987 const LocationContext *LC = C.getLocationContext();
1988 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1989
1990 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00001991 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00001992 if (VR->getSuperRegion() == R) {
1993 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1994 }
1995 Regions.push_back(VR);
1996 }
1997
1998 state =
1999 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2000 Regions.data() + Regions.size()).getState();
2001 C.addTransition(state);
2002}
2003
Anna Zaks46d01602012-05-18 01:16:10 +00002004bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002005 assert(Sym);
2006 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002007 return (RS && RS->isReleased());
2008}
2009
2010bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2011 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002012
Jordan Rose656fdd52014-01-08 18:46:55 +00002013 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002014 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2015 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002016 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002017
Anna Zaksa1b227b2012-02-08 23:16:56 +00002018 return false;
2019}
2020
Jordan Rose656fdd52014-01-08 18:46:55 +00002021bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2022
2023 if (isReleased(Sym, C)) {
2024 ReportDoubleDelete(C, Sym);
2025 return true;
2026 }
2027 return false;
2028}
2029
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002030// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002031void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2032 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002033 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaksa1b227b2012-02-08 23:16:56 +00002034 if (Sym)
Anna Zaks46d01602012-05-18 01:16:10 +00002035 checkUseAfterFree(Sym, C, S);
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002036}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002037
Anna Zaksbb1ef902012-02-11 21:02:35 +00002038// If a symbolic region is assumed to NULL (or another constant), stop tracking
2039// it - assuming that allocation failed on this path.
2040ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2041 SVal Cond,
2042 bool Assumption) const {
2043 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002044 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002045 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002046 ConstraintManager &CMgr = state->getConstraintManager();
2047 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2048 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002049 state = state->remove<RegionState>(I.getKey());
2050 }
2051
Anna Zaksd56c8792012-02-13 18:05:39 +00002052 // Realloc returns 0 when reallocation fails, which means that we should
2053 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002054 ReallocPairsTy RP = state->get<ReallocPairs>();
2055 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002056 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002057 ConstraintManager &CMgr = state->getConstraintManager();
2058 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002059 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002060 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002061
Anna Zaks75cfbb62012-09-12 22:57:34 +00002062 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2063 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2064 if (RS->isReleased()) {
2065 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002066 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002067 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002068 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2069 state = state->remove<RegionState>(ReallocSym);
2070 else
2071 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002072 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002073 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002074 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002075 }
2076
Anna Zaksbb1ef902012-02-11 21:02:35 +00002077 return state;
2078}
2079
Anna Zaks8ebeb642013-06-08 00:29:29 +00002080bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002081 const CallEvent *Call,
2082 ProgramStateRef State,
2083 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002084 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002085 EscapingSymbol = nullptr;
2086
Jordan Rose2a833ca2014-01-15 17:25:15 +00002087 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002088 // TODO: If we want to be more optimistic here, we'll need to make sure that
2089 // regions escape to C++ containers. They seem to do that even now, but for
2090 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002091 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002092 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002093
Jordan Rose742920c2012-07-02 19:27:35 +00002094 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002095 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002096 // If it's not a framework call, or if it takes a callback, assume it
2097 // can free memory.
2098 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002099 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002100
Jordan Rose613f3c02013-03-09 00:59:10 +00002101 // If it's a method we know about, handle it explicitly post-call.
2102 // This should happen before the "freeWhenDone" check below.
2103 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002104 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002105
Jordan Rose613f3c02013-03-09 00:59:10 +00002106 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2107 // about, we can't be sure that the object will use free() to deallocate the
2108 // memory, so we can't model it explicitly. The best we can do is use it to
2109 // decide whether the pointer escapes.
2110 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002111 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002112
Jordan Rose613f3c02013-03-09 00:59:10 +00002113 // If the first selector piece ends with "NoCopy", and there is no
2114 // "freeWhenDone" parameter set to zero, we know ownership is being
2115 // transferred. Again, though, we can't be sure that the object will use
2116 // free() to deallocate the memory, so we can't model it explicitly.
2117 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002118 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002119 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002120
Anna Zaks42908c72012-06-19 05:10:32 +00002121 // If the first selector starts with addPointer, insertPointer,
2122 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2123 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002124 // that the pointers get freed by following the container itself.
2125 if (FirstSlot.startswith("addPointer") ||
2126 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002127 FirstSlot.startswith("replacePointer") ||
2128 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002129 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002130 }
2131
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002132 // We should escape receiver on call to 'init'. This is especially relevant
2133 // to the receiver, as the corresponding symbol is usually not referenced
2134 // after the call.
2135 if (Msg->getMethodFamily() == OMF_init) {
2136 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2137 return true;
2138 }
Anna Zaks737926b2013-05-31 22:39:13 +00002139
Jordan Rose742920c2012-07-02 19:27:35 +00002140 // Otherwise, assume that the method does not free memory.
2141 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002142 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002143 }
2144
Jordan Rose742920c2012-07-02 19:27:35 +00002145 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002146 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002147 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002148 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002149
Jordan Rose742920c2012-07-02 19:27:35 +00002150 ASTContext &ASTC = State->getStateManager().getContext();
2151
2152 // If it's one of the allocation functions we can reason about, we model
2153 // its behavior explicitly.
2154 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002155 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002156
2157 // If it's not a system call, assume it frees memory.
2158 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002159 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002160
2161 // White list the system functions whose arguments escape.
2162 const IdentifierInfo *II = FD->getIdentifier();
2163 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002164 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002165 StringRef FName = II->getName();
2166
Jordan Rose742920c2012-07-02 19:27:35 +00002167 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose7ab01822012-07-02 19:27:51 +00002168 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002169 if (FName.endswith("NoCopy")) {
2170 // Look for the deallocator argument. We know that the memory ownership
2171 // is not transferred only if the deallocator argument is
2172 // 'kCFAllocatorNull'.
2173 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2174 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2175 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2176 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2177 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002178 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002179 }
2180 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002181 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002182 }
2183
Jordan Rose742920c2012-07-02 19:27:35 +00002184 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002185 // 'closefn' is specified (and if that function does free memory),
2186 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002187 // Currently, we do not inspect the 'closefn' function (PR12101).
2188 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002189 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002190 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002191
2192 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2193 // these leaks might be intentional when setting the buffer for stdio.
2194 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2195 if (FName == "setbuf" || FName =="setbuffer" ||
2196 FName == "setlinebuf" || FName == "setvbuf") {
2197 if (Call->getNumArgs() >= 1) {
2198 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2199 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2200 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2201 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002202 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002203 }
2204 }
2205
2206 // A bunch of other functions which either take ownership of a pointer or
2207 // wrap the result up in a struct or object, meaning it can be freed later.
2208 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2209 // but the Malloc checker cannot differentiate between them. The right way
2210 // of doing this would be to implement a pointer escapes callback.
2211 if (FName == "CGBitmapContextCreate" ||
2212 FName == "CGBitmapContextCreateWithData" ||
2213 FName == "CVPixelBufferCreateWithBytes" ||
2214 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2215 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002216 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002217 }
2218
Jordan Rose7ab01822012-07-02 19:27:51 +00002219 // Handle cases where we know a buffer's /address/ can escape.
2220 // Note that the above checks handle some special cases where we know that
2221 // even though the address escapes, it's still our responsibility to free the
2222 // buffer.
2223 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002224 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002225
2226 // Otherwise, assume that the function does not free memory.
2227 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002228 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002229}
2230
Anna Zaks333481b2013-03-28 23:15:29 +00002231static bool retTrue(const RefState *RS) {
2232 return true;
2233}
2234
2235static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2236 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2237 RS->getAllocationFamily() == AF_CXXNew);
2238}
2239
Anna Zaksdc154152012-12-20 00:38:25 +00002240ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2241 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002242 const CallEvent *Call,
2243 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002244 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2245}
2246
2247ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2248 const InvalidatedSymbols &Escaped,
2249 const CallEvent *Call,
2250 PointerEscapeKind Kind) const {
2251 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2252 &checkIfNewOrNewArrayFamily);
2253}
2254
2255ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2256 const InvalidatedSymbols &Escaped,
2257 const CallEvent *Call,
2258 PointerEscapeKind Kind,
2259 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002260 // If we know that the call does not free memory, or we want to process the
2261 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002262 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002263 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002264 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2265 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002266 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002267 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002268 }
Anna Zaks3d348342012-02-14 21:55:24 +00002269
Anna Zaksdc154152012-12-20 00:38:25 +00002270 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002271 E = Escaped.end();
2272 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002273 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002274
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002275 if (EscapingSymbol && EscapingSymbol != sym)
2276 continue;
2277
Anna Zaks0d6989b2012-06-22 02:04:31 +00002278 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks93a21a82013-04-09 00:30:28 +00002279 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002280 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002281 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2282 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002283 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002284 }
Anna Zaks3d348342012-02-14 21:55:24 +00002285 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002286}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002287
Jordy Rosebf38f202012-03-18 07:43:35 +00002288static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2289 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002290 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2291 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002292
Jordan Rose0c153cb2012-11-02 01:54:06 +00002293 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002294 I != E; ++I) {
2295 SymbolRef sym = I.getKey();
2296 if (!currMap.lookup(sym))
2297 return sym;
2298 }
2299
Craig Topper0dbb7832014-05-27 02:45:47 +00002300 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002301}
2302
Anna Zaks2b5bb972012-02-09 06:25:51 +00002303PathDiagnosticPiece *
2304MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2305 const ExplodedNode *PrevN,
2306 BugReporterContext &BRC,
2307 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002308 ProgramStateRef state = N->getState();
2309 ProgramStateRef statePrev = PrevN->getState();
2310
2311 const RefState *RS = state->get<RegionState>(Sym);
2312 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002313 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002314 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002315
Craig Topper0dbb7832014-05-27 02:45:47 +00002316 const Stmt *S = nullptr;
2317 const char *Msg = nullptr;
2318 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002319
2320 // Retrieve the associated statement.
2321 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002322 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002323 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002324 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002325 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002326 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002327 // If an assumption was made on a branch, it should be caught
2328 // here by looking at the state transition.
2329 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002330 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002331
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002332 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002333 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002334
Jordan Rose681cce92012-07-10 22:07:42 +00002335 // FIXME: We will eventually need to handle non-statement-based events
2336 // (__attribute__((cleanup))).
2337
Anna Zaks2b5bb972012-02-09 06:25:51 +00002338 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002339 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002340 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002341 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002342 StackHint = new StackHintGeneratorForSymbol(Sym,
2343 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002344 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002345 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002346 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002347 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002348 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002349 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002350 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002351 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002352 Mode = ReallocationFailed;
2353 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002354 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002355 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002356
Jordy Rose21ff76e2012-03-24 03:15:09 +00002357 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2358 // Is it possible to fail two reallocs WITHOUT testing in between?
2359 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2360 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002361 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002362 FailedReallocSymbol = sym;
2363 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002364 }
2365
2366 // We are in a special mode if a reallocation failed later in the path.
2367 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002368 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002369
Jordy Rose21ff76e2012-03-24 03:15:09 +00002370 // Is this is the first appearance of the reallocated symbol?
2371 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002372 // We're at the reallocation point.
2373 Msg = "Attempt to reallocate memory";
2374 StackHint = new StackHintGeneratorForSymbol(Sym,
2375 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002376 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002377 Mode = Normal;
2378 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002379 }
2380
Anna Zaks2b5bb972012-02-09 06:25:51 +00002381 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002382 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002383 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002384
2385 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002386 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002387 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002388 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002389}
2390
Anna Zaks263b7e02012-05-02 00:05:20 +00002391void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2392 const char *NL, const char *Sep) const {
2393
2394 RegionStateTy RS = State->get<RegionState>();
2395
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002396 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002397 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002398 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002399 const RefState *RefS = State->get<RegionState>(I.getKey());
2400 AllocationFamily Family = RefS->getAllocationFamily();
2401 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2402
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002403 I.getKey()->dumpToStream(Out);
2404 Out << " : ";
2405 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002406 if (CheckKind.hasValue())
2407 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002408 Out << NL;
2409 }
2410 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002411}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002412
Anna Zakse4cfcd42013-04-16 00:22:55 +00002413void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2414 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002415 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2416 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2417 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2418 mgr.getCurrentCheckName();
Anna Zakse4cfcd42013-04-16 00:22:55 +00002419 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2420 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002421 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002422 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002423}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002424
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002425#define REGISTER_CHECKER(name) \
2426 void ento::register##name(CheckerManager &mgr) { \
2427 registerCStringCheckerBasic(mgr); \
2428 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2429 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2430 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2431 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002432
2433REGISTER_CHECKER(MallocPessimistic)
2434REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev13df0362013-03-25 01:35:45 +00002435REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002436REGISTER_CHECKER(MismatchedDeallocatorChecker)