blob: aee5a43048b95699bb2aa7985f0bb3c6182602a3 [file] [log] [blame]
Zhongxing Xu589c0f22009-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 Kyrtzidis312dbec2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
Stephen Hines176edba2014-12-01 14:53:08 -080018#include "clang/AST/ParentMap.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/Basic/SourceManager.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070020#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000023#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000029#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000030#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000031#include "llvm/ADT/SmallString.h"
Jordan Rose615a0922012-09-22 01:24:42 +000032#include "llvm/ADT/StringExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000033#include <climits>
34
Zhongxing Xu589c0f22009-11-12 08:38:56 +000035using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000036using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000037
38namespace {
39
Anton Yartsev849c7bf2013-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,
Stephen Hines176edba2014-12-01 14:53:08 -080045 AF_CXXNewArray,
46 AF_IfNameIndex
Anton Yartsev849c7bf2013-03-28 17:05:19 +000047};
48
Zhongxing Xu7fb14642009-12-11 00:55:44 +000049class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000050 enum Kind { // Reference to allocated memory.
51 Allocated,
52 // Reference to released/freed memory.
53 Released,
Stephen Hines651f13c2014-04-23 16:59:28 -070054 // The responsibility for freeing resources has transferred from
Anna Zaks050cdd72012-06-20 20:57:46 +000055 // this reference. A relinquished symbol should not be freed.
Anna Zaks04130232013-04-09 00:30:28 +000056 Relinquished,
57 // We are no longer guaranteed to have observed all manipulations
58 // of this pointer/memory. For example, it could have been
59 // passed as a parameter to an opaque function.
60 Escaped
61 };
Anton Yartsev849c7bf2013-03-28 17:05:19 +000062
Zhongxing Xu243fde92009-11-17 07:54:15 +000063 const Stmt *S;
Anton Yartsev849c7bf2013-03-28 17:05:19 +000064 unsigned K : 2; // Kind enum, but stored as a bitfield.
65 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
66 // family.
Zhongxing Xu243fde92009-11-17 07:54:15 +000067
Anton Yartsev849c7bf2013-03-28 17:05:19 +000068 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks04130232013-04-09 00:30:28 +000069 : S(s), K(k), Family(family) {
70 assert(family != AF_None);
71 }
Zhongxing Xu7fb14642009-12-11 00:55:44 +000072public:
Anna Zaks050cdd72012-06-20 20:57:46 +000073 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000074 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000075 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks04130232013-04-09 00:30:28 +000076 bool isEscaped() const { return K == Escaped; }
77 AllocationFamily getAllocationFamily() const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +000078 return (AllocationFamily)Family;
79 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000080 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000081
82 bool operator==(const RefState &X) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +000083 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu243fde92009-11-17 07:54:15 +000084 }
85
Anton Yartsev849c7bf2013-03-28 17:05:19 +000086 static RefState getAllocated(unsigned family, const Stmt *s) {
87 return RefState(Allocated, s, family);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000088 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +000089 static RefState getReleased(unsigned family, const Stmt *s) {
90 return RefState(Released, s, family);
91 }
92 static RefState getRelinquished(unsigned family, const Stmt *s) {
93 return RefState(Relinquished, s, family);
Ted Kremenekdde201b2010-08-06 21:12:55 +000094 }
Anna Zaks04130232013-04-09 00:30:28 +000095 static RefState getEscaped(const RefState *RS) {
96 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
97 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000098
99 void Profile(llvm::FoldingSetNodeID &ID) const {
100 ID.AddInteger(K);
101 ID.AddPointer(S);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000102 ID.AddInteger(Family);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000103 }
Ted Kremenekc37fad62013-01-03 01:30:12 +0000104
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000105 void dump(raw_ostream &OS) const {
Stephen Hines651f13c2014-04-23 16:59:28 -0700106 switch (static_cast<Kind>(K)) {
107#define CASE(ID) case ID: OS << #ID; break;
108 CASE(Allocated)
109 CASE(Released)
110 CASE(Relinquished)
111 CASE(Escaped)
112 }
Ted Kremenekc37fad62013-01-03 01:30:12 +0000113 }
114
Stephen Hines651f13c2014-04-23 16:59:28 -0700115 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000116};
117
Anna Zaks9dc298b2012-09-12 22:57:34 +0000118enum ReallocPairKind {
119 RPToBeFreedAfterFailure,
120 // The symbol has been freed when reallocation failed.
121 RPIsFreeOnFailure,
122 // The symbol does not need to be freed after reallocation fails.
123 RPDoNotTrackAfterFailure
124};
125
Anna Zaks55dd9562012-08-24 02:28:20 +0000126/// \class ReallocPair
127/// \brief Stores information about the symbol being reallocated by a call to
128/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +0000129struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +0000130 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000131 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +0000132 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +0000133
Anna Zaks9dc298b2012-09-12 22:57:34 +0000134 ReallocPair(SymbolRef S, ReallocPairKind K) :
135 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +0000136 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +0000137 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +0000138 ID.AddPointer(ReallocatedSym);
139 }
140 bool operator==(const ReallocPair &X) const {
141 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +0000142 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +0000143 }
144};
145
Anna Zaks97bfb552013-01-08 00:25:29 +0000146typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000147
Anna Zaksb319e022012-02-08 20:13:28 +0000148class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000149 check::PointerEscape,
Anna Zaks41988f32013-03-28 23:15:29 +0000150 check::ConstPointerEscape,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000151 check::PreStmt<ReturnStmt>,
Anton Yartsev55e57a52013-04-10 22:21:41 +0000152 check::PreCall,
Anna Zaksb319e022012-02-08 20:13:28 +0000153 check::PostStmt<CallExpr>,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000154 check::PostStmt<CXXNewExpr>,
155 check::PreStmt<CXXDeleteExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000156 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000157 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000158 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000159 eval::Assume>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000160{
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000161public:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700162 MallocChecker()
163 : II_malloc(nullptr), II_free(nullptr), II_realloc(nullptr),
164 II_calloc(nullptr), II_valloc(nullptr), II_reallocf(nullptr),
Stephen Hines176edba2014-12-01 14:53:08 -0800165 II_strndup(nullptr), II_strdup(nullptr), II_kmalloc(nullptr),
166 II_if_nameindex(nullptr), II_if_freenameindex(nullptr) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000167
168 /// In pessimistic mode, the checker assumes that it does not know which
169 /// functions might free the memory.
Stephen Hines651f13c2014-04-23 16:59:28 -0700170 enum CheckKind {
171 CK_MallocPessimistic,
172 CK_MallocOptimistic,
173 CK_NewDeleteChecker,
174 CK_NewDeleteLeaksChecker,
175 CK_MismatchedDeallocatorChecker,
176 CK_NumCheckKinds
Anna Zaks231361a2012-02-08 23:16:52 +0000177 };
178
Stephen Hines176edba2014-12-01 14:53:08 -0800179 enum class MemoryOperationKind {
180 MOK_Allocate,
181 MOK_Free,
182 MOK_Any
183 };
184
Stephen Hines651f13c2014-04-23 16:59:28 -0700185 DefaultBool ChecksEnabled[CK_NumCheckKinds];
186 CheckName CheckNames[CK_NumCheckKinds];
Anna Zaks231361a2012-02-08 23:16:52 +0000187
Anton Yartsev55e57a52013-04-10 22:21:41 +0000188 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000189 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000190 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
191 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000192 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000193 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000194 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000195 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000196 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000197 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000198 void checkLocation(SVal l, bool isLoad, const Stmt *S,
199 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000200
201 ProgramStateRef checkPointerEscape(ProgramStateRef State,
202 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000203 const CallEvent *Call,
204 PointerEscapeKind Kind) const;
Anna Zaks41988f32013-03-28 23:15:29 +0000205 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
206 const InvalidatedSymbols &Escaped,
207 const CallEvent *Call,
208 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000209
Anna Zaks93c5a242012-05-02 00:05:20 +0000210 void printState(raw_ostream &Out, ProgramStateRef State,
Stephen Hines651f13c2014-04-23 16:59:28 -0700211 const char *NL, const char *Sep) const override;
Anna Zaks93c5a242012-05-02 00:05:20 +0000212
Zhongxing Xu7b760962009-11-13 07:25:27 +0000213private:
Stephen Hines651f13c2014-04-23 16:59:28 -0700214 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
215 mutable std::unique_ptr<BugType> BT_DoubleDelete;
216 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
217 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
218 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
219 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
220 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
221 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
222 *II_valloc, *II_reallocf, *II_strndup, *II_strdup,
Stephen Hines176edba2014-12-01 14:53:08 -0800223 *II_kmalloc, *II_if_nameindex, *II_if_freenameindex;
Stephen Hines651f13c2014-04-23 16:59:28 -0700224 mutable Optional<uint64_t> KernelZeroFlagVal;
225
Anna Zaks66c40402012-02-14 21:55:24 +0000226 void initIdentifierInfo(ASTContext &C) const;
227
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000228 /// \brief Determine family of a deallocation expression.
Anton Yartsev648cb712013-04-04 23:46:29 +0000229 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000230
231 /// \brief Print names of allocators and deallocators.
232 ///
233 /// \returns true on success.
234 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
235 const Expr *E) const;
236
237 /// \brief Print expected name of an allocator based on the deallocator's
238 /// family derived from the DeallocExpr.
239 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
240 const Expr *DeallocExpr) const;
241 /// \brief Print expected name of a deallocator based on the allocator's
242 /// family.
243 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
244
Jordan Rose9fe09f32013-03-09 00:59:10 +0000245 ///@{
Anna Zaks66c40402012-02-14 21:55:24 +0000246 /// Check if this is one of the functions which can allocate/reallocate memory
247 /// pointed to by one of its arguments.
248 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Stephen Hines176edba2014-12-01 14:53:08 -0800249 bool isCMemFunction(const FunctionDecl *FD,
250 ASTContext &C,
251 AllocationFamily Family,
252 MemoryOperationKind MemKind) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000253 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose9fe09f32013-03-09 00:59:10 +0000254 ///@}
Stephen Hines651f13c2014-04-23 16:59:28 -0700255 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
256 const CallExpr *CE,
257 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000258 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000259 const Expr *SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000260 ProgramStateRef State,
261 AllocationFamily Family = AF_Malloc) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000262 return MallocMemAux(C, CE,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000263 State->getSVal(SizeEx, C.getLocationContext()),
264 Init, State, Family);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000265 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000266
Ted Kremenek8bef8232012-01-26 21:29:00 +0000267 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000268 SVal SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000269 ProgramStateRef State,
270 AllocationFamily Family = AF_Malloc);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000271
Stephen Hines651f13c2014-04-23 16:59:28 -0700272 // Check if this malloc() for special flags. At present that means M_ZERO or
273 // __GFP_ZERO (in which case, treat it like calloc).
274 llvm::Optional<ProgramStateRef>
275 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
276 const ProgramStateRef &State) const;
277
Anna Zaks87cb5be2012-02-22 19:24:52 +0000278 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000279 static ProgramStateRef
280 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
281 AllocationFamily Family = AF_Malloc);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000282
283 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
284 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000285 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000286 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000287 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000288 bool &ReleasedAllocated,
289 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000290 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
291 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000292 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000293 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000294 bool &ReleasedAllocated,
295 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000296
Anna Zaks87cb5be2012-02-22 19:24:52 +0000297 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
298 bool FreesMemOnFailure) const;
299 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000300
Anna Zaks14345182012-05-18 01:16:10 +0000301 ///\brief Check if the memory associated with this symbol was released.
302 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
303
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000304 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaks91c2a112012-02-08 23:16:56 +0000305
Stephen Hines651f13c2014-04-23 16:59:28 -0700306 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
307
Anna Zakse7a5c822013-05-31 23:47:32 +0000308 /// Check if the function is known free memory, or if it is
Jordan Rose9fe09f32013-03-09 00:59:10 +0000309 /// "interesting" and should be modeled explicitly.
310 ///
Anna Zaks33708592013-06-08 00:29:29 +0000311 /// \param [out] EscapingSymbol A function might not free memory in general,
312 /// but could be known to free a particular symbol. In this case, false is
Anna Zakse7a5c822013-05-31 23:47:32 +0000313 /// returned and the single escaping symbol is returned through the out
314 /// parameter.
315 ///
Jordan Rose9fe09f32013-03-09 00:59:10 +0000316 /// We assume that pointers do not escape through calls to system functions
317 /// not handled by this checker.
Anna Zaks33708592013-06-08 00:29:29 +0000318 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zakse7a5c822013-05-31 23:47:32 +0000319 ProgramStateRef State,
320 SymbolRef &EscapingSymbol) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000321
Anna Zaks41988f32013-03-28 23:15:29 +0000322 // Implementation of the checkPointerEscape callabcks.
323 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
324 const InvalidatedSymbols &Escaped,
325 const CallEvent *Call,
326 PointerEscapeKind Kind,
327 bool(*CheckRefState)(const RefState*)) const;
328
Anton Yartsev9ae7a922013-04-11 00:05:20 +0000329 ///@{
330 /// Tells if a given family/call/symbol is tracked by the current checker.
Stephen Hines651f13c2014-04-23 16:59:28 -0700331 /// Sets CheckKind to the kind of the checker responsible for this
332 /// family/call/symbol.
333 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family) const;
334 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
335 const Stmt *AllocDeallocStmt) const;
336 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const;
Anton Yartsev9ae7a922013-04-11 00:05:20 +0000337 ///@}
Ted Kremenek9c378f72011-08-12 23:37:29 +0000338 static bool SummarizeValue(raw_ostream &os, SVal V);
339 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000340 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
341 const Expr *DeallocExpr) const;
Anton Yartsev648cb712013-04-04 23:46:29 +0000342 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartseva3ae9372013-04-05 11:25:10 +0000343 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsev30845182013-09-16 17:51:25 +0000344 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000345 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
346 const Expr *DeallocExpr,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700347 const Expr *AllocExpr = nullptr) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000348 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
349 SymbolRef Sym) const;
350 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000351 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000352
Stephen Hines651f13c2014-04-23 16:59:28 -0700353 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
354
Anna Zaksca8e36e2012-02-23 21:38:21 +0000355 /// Find the location of the allocation for Sym on the path leading to the
356 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000357 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
358 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000359
Anna Zaksda046772012-02-11 21:02:40 +0000360 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
361
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000362 /// The bug visitor which allows us to print extra diagnostics along the
363 /// BugReport path. For example, showing the allocation site of the leaked
364 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000365 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000366 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000367 enum NotificationMode {
368 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000369 ReallocationFailed
370 };
371
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000372 // The allocated region symbol tracked by the main analysis.
373 SymbolRef Sym;
374
Anna Zaks88feba02012-05-10 01:37:40 +0000375 // The mode we are in, i.e. what kind of diagnostics will be emitted.
376 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000377
Anna Zaks88feba02012-05-10 01:37:40 +0000378 // A symbol from when the primary region should have been reallocated.
379 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000380
Anna Zaks88feba02012-05-10 01:37:40 +0000381 bool IsLeak;
382
383 public:
384 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700385 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000386
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000387 virtual ~MallocBugVisitor() {}
388
Stephen Hines651f13c2014-04-23 16:59:28 -0700389 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000390 static int X = 0;
391 ID.AddPointer(&X);
392 ID.AddPointer(Sym);
393 }
394
Anna Zaksfe571602012-02-16 22:26:07 +0000395 inline bool isAllocated(const RefState *S, const RefState *SPrev,
396 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000397 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000398 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000399 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000400 }
401
Anna Zaksfe571602012-02-16 22:26:07 +0000402 inline bool isReleased(const RefState *S, const RefState *SPrev,
403 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000404 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000405 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000406 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
407 }
408
Anna Zaks5b7aa342012-06-22 02:04:31 +0000409 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
410 const Stmt *Stmt) {
411 // Did not track -> relinquished. Other state (allocated) -> relinquished.
412 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
413 isa<ObjCPropertyRefExpr>(Stmt)) &&
414 (S && S->isRelinquished()) &&
415 (!SPrev || !SPrev->isRelinquished()));
416 }
417
Anna Zaksfe571602012-02-16 22:26:07 +0000418 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
419 const Stmt *Stmt) {
420 // If the expression is not a call, and the state change is
421 // released -> allocated, it must be the realloc return value
422 // check. If we have to handle more cases here, it might be cleaner just
423 // to track this extra bit in the state itself.
424 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
425 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000426 }
427
428 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
429 const ExplodedNode *PrevN,
430 BugReporterContext &BRC,
Stephen Hines651f13c2014-04-23 16:59:28 -0700431 BugReport &BR) override;
Anna Zaks88feba02012-05-10 01:37:40 +0000432
Stephen Hines176edba2014-12-01 14:53:08 -0800433 std::unique_ptr<PathDiagnosticPiece>
434 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
435 BugReport &BR) override {
Anna Zaks88feba02012-05-10 01:37:40 +0000436 if (!IsLeak)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700437 return nullptr;
Anna Zaks88feba02012-05-10 01:37:40 +0000438
439 PathDiagnosticLocation L =
440 PathDiagnosticLocation::createEndOfPath(EndPathNode,
441 BRC.getSourceManager());
442 // Do not add the statement itself as a range in case of leak.
Stephen Hines176edba2014-12-01 14:53:08 -0800443 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
444 false);
Anna Zaks88feba02012-05-10 01:37:40 +0000445 }
446
Anna Zaks56a938f2012-03-16 23:24:20 +0000447 private:
448 class StackHintGeneratorForReallocationFailed
449 : public StackHintGeneratorForSymbol {
450 public:
451 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
452 : StackHintGeneratorForSymbol(S, M) {}
453
Stephen Hines651f13c2014-04-23 16:59:28 -0700454 std::string getMessageForArg(const Expr *ArgE,
455 unsigned ArgIndex) override {
Jordan Rose615a0922012-09-22 01:24:42 +0000456 // Printed parameters start at 1, not 0.
457 ++ArgIndex;
458
Anna Zaks56a938f2012-03-16 23:24:20 +0000459 SmallString<200> buf;
460 llvm::raw_svector_ostream os(buf);
461
Jordan Rose615a0922012-09-22 01:24:42 +0000462 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
463 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000464
465 return os.str();
466 }
467
Stephen Hines651f13c2014-04-23 16:59:28 -0700468 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksfbd58742012-03-16 23:44:28 +0000469 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000470 }
471 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000472 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000473};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000474} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000475
Jordan Rose166d5022012-11-02 01:54:06 +0000476REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
477REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000478
Anna Zaks4141e4d2012-11-13 03:18:01 +0000479// A map from the freed symbol to the symbol representing the return value of
480// the free function.
481REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
482
Anna Zaks4fb54872012-02-11 21:02:35 +0000483namespace {
484class StopTrackingCallback : public SymbolVisitor {
485 ProgramStateRef state;
486public:
487 StopTrackingCallback(ProgramStateRef st) : state(st) {}
488 ProgramStateRef getState() const { return state; }
489
Stephen Hines651f13c2014-04-23 16:59:28 -0700490 bool VisitSymbol(SymbolRef sym) override {
Anna Zaks4fb54872012-02-11 21:02:35 +0000491 state = state->remove<RegionState>(sym);
492 return true;
493 }
494};
495} // end anonymous namespace
496
Anna Zaks66c40402012-02-14 21:55:24 +0000497void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000498 if (II_malloc)
499 return;
500 II_malloc = &Ctx.Idents.get("malloc");
501 II_free = &Ctx.Idents.get("free");
502 II_realloc = &Ctx.Idents.get("realloc");
503 II_reallocf = &Ctx.Idents.get("reallocf");
504 II_calloc = &Ctx.Idents.get("calloc");
505 II_valloc = &Ctx.Idents.get("valloc");
506 II_strdup = &Ctx.Idents.get("strdup");
507 II_strndup = &Ctx.Idents.get("strndup");
Stephen Hines651f13c2014-04-23 16:59:28 -0700508 II_kmalloc = &Ctx.Idents.get("kmalloc");
Stephen Hines176edba2014-12-01 14:53:08 -0800509 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
510 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaksb319e022012-02-08 20:13:28 +0000511}
512
Anna Zaks66c40402012-02-14 21:55:24 +0000513bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Stephen Hines176edba2014-12-01 14:53:08 -0800514 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks14345182012-05-18 01:16:10 +0000515 return true;
516
Stephen Hines176edba2014-12-01 14:53:08 -0800517 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks14345182012-05-18 01:16:10 +0000518 return true;
519
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000520 if (isStandardNewDelete(FD, C))
521 return true;
522
Anna Zaks14345182012-05-18 01:16:10 +0000523 return false;
524}
525
Stephen Hines176edba2014-12-01 14:53:08 -0800526bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
527 ASTContext &C,
528 AllocationFamily Family,
529 MemoryOperationKind MemKind) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000530 if (!FD)
531 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000532
Stephen Hines176edba2014-12-01 14:53:08 -0800533 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
534 MemKind == MemoryOperationKind::MOK_Free);
535 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
536 MemKind == MemoryOperationKind::MOK_Allocate);
537
Jordan Rose5ef6e942012-07-10 23:13:01 +0000538 if (FD->getKind() == Decl::Function) {
Stephen Hines176edba2014-12-01 14:53:08 -0800539 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose5ef6e942012-07-10 23:13:01 +0000540 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000541
Stephen Hines176edba2014-12-01 14:53:08 -0800542 if (Family == AF_Malloc && CheckFree) {
543 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
544 return true;
545 }
546
547 if (Family == AF_Malloc && CheckAlloc) {
548 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
549 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
550 FunI == II_strndup || FunI == II_kmalloc)
551 return true;
552 }
553
554 if (Family == AF_IfNameIndex && CheckFree) {
555 if (FunI == II_if_freenameindex)
556 return true;
557 }
558
559 if (Family == AF_IfNameIndex && CheckAlloc) {
560 if (FunI == II_if_nameindex)
561 return true;
562 }
Jordan Rose5ef6e942012-07-10 23:13:01 +0000563 }
Anna Zaks66c40402012-02-14 21:55:24 +0000564
Stephen Hines176edba2014-12-01 14:53:08 -0800565 if (Family != AF_Malloc)
Anna Zaks14345182012-05-18 01:16:10 +0000566 return false;
567
Stephen Hines176edba2014-12-01 14:53:08 -0800568 if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs()) {
569 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
570 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
571 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
572 if (CheckFree)
573 return true;
574 } else if (OwnKind == OwnershipAttr::Returns) {
575 if (CheckAlloc)
576 return true;
577 }
578 }
Jordan Rose5ef6e942012-07-10 23:13:01 +0000579 }
Anna Zaks66c40402012-02-14 21:55:24 +0000580
Anna Zaks66c40402012-02-14 21:55:24 +0000581 return false;
582}
583
Anton Yartsev69746282013-03-28 16:10:38 +0000584// Tells if the callee is one of the following:
585// 1) A global non-placement new/delete operator function.
586// 2) A global placement operator function with the single placement argument
587// of type std::nothrow_t.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000588bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
589 ASTContext &C) const {
590 if (!FD)
591 return false;
592
593 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
594 if (Kind != OO_New && Kind != OO_Array_New &&
595 Kind != OO_Delete && Kind != OO_Array_Delete)
596 return false;
597
Anton Yartsev69746282013-03-28 16:10:38 +0000598 // Skip all operator new/delete methods.
599 if (isa<CXXMethodDecl>(FD))
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000600 return false;
601
602 // Return true if tested operator is a standard placement nothrow operator.
603 if (FD->getNumParams() == 2) {
604 QualType T = FD->getParamDecl(1)->getType();
605 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
606 return II->getName().equals("nothrow_t");
607 }
608
609 // Skip placement operators.
610 if (FD->getNumParams() != 1 || FD->isVariadic())
611 return false;
612
613 // One of the standard new/new[]/delete/delete[] non-placement operators.
614 return true;
615}
616
Stephen Hines651f13c2014-04-23 16:59:28 -0700617llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
618 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
619 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
620 //
621 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
622 //
623 // One of the possible flags is M_ZERO, which means 'give me back an
624 // allocation which is already zeroed', like calloc.
625
626 // 2-argument kmalloc(), as used in the Linux kernel:
627 //
628 // void *kmalloc(size_t size, gfp_t flags);
629 //
630 // Has the similar flag value __GFP_ZERO.
631
632 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
633 // code could be shared.
634
635 ASTContext &Ctx = C.getASTContext();
636 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
637
638 if (!KernelZeroFlagVal.hasValue()) {
639 if (OS == llvm::Triple::FreeBSD)
640 KernelZeroFlagVal = 0x0100;
641 else if (OS == llvm::Triple::NetBSD)
642 KernelZeroFlagVal = 0x0002;
643 else if (OS == llvm::Triple::OpenBSD)
644 KernelZeroFlagVal = 0x0008;
645 else if (OS == llvm::Triple::Linux)
646 // __GFP_ZERO
647 KernelZeroFlagVal = 0x8000;
648 else
649 // FIXME: We need a more general way of getting the M_ZERO value.
650 // See also: O_CREAT in UnixAPIChecker.cpp.
651
652 // Fall back to normal malloc behavior on platforms where we don't
653 // know M_ZERO.
654 return None;
655 }
656
657 // We treat the last argument as the flags argument, and callers fall-back to
658 // normal malloc on a None return. This works for the FreeBSD kernel malloc
659 // as well as Linux kmalloc.
660 if (CE->getNumArgs() < 2)
661 return None;
662
663 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
664 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
665 if (!V.getAs<NonLoc>()) {
666 // The case where 'V' can be a location can only be due to a bad header,
667 // so in this case bail out.
668 return None;
669 }
670
671 NonLoc Flags = V.castAs<NonLoc>();
672 NonLoc ZeroFlag = C.getSValBuilder()
673 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
674 .castAs<NonLoc>();
675 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
676 Flags, ZeroFlag,
677 FlagsEx->getType());
678 if (MaskedFlagsUC.isUnknownOrUndef())
679 return None;
680 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
681
682 // Check if maskedFlags is non-zero.
683 ProgramStateRef TrueState, FalseState;
684 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
685
686 // If M_ZERO is set, treat this like calloc (initialized).
687 if (TrueState && !FalseState) {
688 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
689 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
690 }
691
692 return None;
693}
694
Anna Zaksb319e022012-02-08 20:13:28 +0000695void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000696 if (C.wasInlined)
697 return;
Stephen Hines651f13c2014-04-23 16:59:28 -0700698
Anna Zaksb319e022012-02-08 20:13:28 +0000699 const FunctionDecl *FD = C.getCalleeDecl(CE);
700 if (!FD)
701 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000702
Anna Zaks87cb5be2012-02-22 19:24:52 +0000703 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000704 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000705
706 if (FD->getKind() == Decl::Function) {
707 initIdentifierInfo(C.getASTContext());
708 IdentifierInfo *FunI = FD->getIdentifier();
709
Stephen Hines651f13c2014-04-23 16:59:28 -0700710 if (FunI == II_malloc) {
711 if (CE->getNumArgs() < 1)
712 return;
713 if (CE->getNumArgs() < 3) {
714 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
715 } else if (CE->getNumArgs() == 3) {
716 llvm::Optional<ProgramStateRef> MaybeState =
717 performKernelMalloc(CE, C, State);
718 if (MaybeState.hasValue())
719 State = MaybeState.getValue();
720 else
721 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
722 }
723 } else if (FunI == II_kmalloc) {
724 llvm::Optional<ProgramStateRef> MaybeState =
725 performKernelMalloc(CE, C, State);
726 if (MaybeState.hasValue())
727 State = MaybeState.getValue();
728 else
729 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
730 } else if (FunI == II_valloc) {
Anton Yartsev648cb712013-04-04 23:46:29 +0000731 if (CE->getNumArgs() < 1)
732 return;
733 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
734 } else if (FunI == II_realloc) {
735 State = ReallocMem(C, CE, false);
736 } else if (FunI == II_reallocf) {
737 State = ReallocMem(C, CE, true);
738 } else if (FunI == II_calloc) {
739 State = CallocMem(C, CE);
740 } else if (FunI == II_free) {
741 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
742 } else if (FunI == II_strdup) {
743 State = MallocUpdateRefState(C, CE, State);
744 } else if (FunI == II_strndup) {
745 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000746 }
Anton Yartsev648cb712013-04-04 23:46:29 +0000747 else if (isStandardNewDelete(FD, C.getASTContext())) {
748 // Process direct calls to operator new/new[]/delete/delete[] functions
749 // as distinct from new/new[]/delete/delete[] expressions that are
750 // processed by the checkPostStmt callbacks for CXXNewExpr and
751 // CXXDeleteExpr.
752 OverloadedOperatorKind K = FD->getOverloadedOperator();
753 if (K == OO_New)
754 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
755 AF_CXXNew);
756 else if (K == OO_Array_New)
757 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
758 AF_CXXNewArray);
759 else if (K == OO_Delete || K == OO_Array_Delete)
760 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
761 else
762 llvm_unreachable("not a new/delete operator");
Stephen Hines176edba2014-12-01 14:53:08 -0800763 } else if (FunI == II_if_nameindex) {
764 // Should we model this differently? We can allocate a fixed number of
765 // elements with zeros in the last one.
766 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
767 AF_IfNameIndex);
768 } else if (FunI == II_if_freenameindex) {
769 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000770 }
771 }
772
Stephen Hines651f13c2014-04-23 16:59:28 -0700773 if (ChecksEnabled[CK_MallocOptimistic] ||
774 ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000775 // Check all the attributes, if there are any.
776 // There can be multiple of these attributes.
777 if (FD->hasAttrs())
Stephen Hines651f13c2014-04-23 16:59:28 -0700778 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
779 switch (I->getOwnKind()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000780 case OwnershipAttr::Returns:
Stephen Hines651f13c2014-04-23 16:59:28 -0700781 State = MallocMemReturnsAttr(C, CE, I);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000782 break;
783 case OwnershipAttr::Takes:
784 case OwnershipAttr::Holds:
Stephen Hines651f13c2014-04-23 16:59:28 -0700785 State = FreeMemAttr(C, CE, I);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000786 break;
787 }
788 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000789 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000790 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000791}
792
Stephen Hines176edba2014-12-01 14:53:08 -0800793static QualType getDeepPointeeType(QualType T) {
794 QualType Result = T, PointeeType = T->getPointeeType();
795 while (!PointeeType.isNull()) {
796 Result = PointeeType;
797 PointeeType = PointeeType->getPointeeType();
798 }
799 return Result;
800}
801
802static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
803
804 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
805 if (!ConstructE)
806 return false;
807
808 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
809 return false;
810
811 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
812
813 // Iterate over the constructor parameters.
814 for (const auto *CtorParam : CtorD->params()) {
815
816 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
817 if (CtorParamPointeeT.isNull())
818 continue;
819
820 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
821
822 if (CtorParamPointeeT->getAsCXXRecordDecl())
823 return true;
824 }
825
826 return false;
827}
828
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000829void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
830 CheckerContext &C) const {
831
832 if (NE->getNumPlacementArgs())
833 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
834 E = NE->placement_arg_end(); I != E; ++I)
835 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
836 checkUseAfterFree(Sym, C, *I);
837
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000838 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
839 return;
840
Stephen Hines176edba2014-12-01 14:53:08 -0800841 ParentMap &PM = C.getLocationContext()->getParentMap();
842 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
843 return;
844
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000845 ProgramStateRef State = C.getState();
846 // The return value from operator new is bound to a specified initialization
847 // value (if any) and we don't want to loose this value. So we call
848 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
849 // existing binding.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000850 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
851 : AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000852 C.addTransition(State);
853}
854
855void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
856 CheckerContext &C) const {
857
Stephen Hines651f13c2014-04-23 16:59:28 -0700858 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000859 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
860 checkUseAfterFree(Sym, C, DE->getArgument());
861
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000862 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
863 return;
864
865 ProgramStateRef State = C.getState();
866 bool ReleasedAllocated;
867 State = FreeMemAux(C, DE->getArgument(), DE, State,
868 /*Hold*/false, ReleasedAllocated);
869
870 C.addTransition(State);
871}
872
Jordan Rose9fe09f32013-03-09 00:59:10 +0000873static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
874 // If the first selector piece is one of the names below, assume that the
875 // object takes ownership of the memory, promising to eventually deallocate it
876 // with free().
877 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
878 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
879 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
880 if (FirstSlot == "dataWithBytesNoCopy" ||
881 FirstSlot == "initWithBytesNoCopy" ||
882 FirstSlot == "initWithCharactersNoCopy")
883 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000884
885 return false;
886}
887
Jordan Rose9fe09f32013-03-09 00:59:10 +0000888static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
889 Selector S = Call.getSelector();
890
891 // FIXME: We should not rely on fully-constrained symbols being folded.
892 for (unsigned i = 1; i < S.getNumArgs(); ++i)
893 if (S.getNameForSlot(i).equals("freeWhenDone"))
894 return !Call.getArgSVal(i).isZeroConstant();
895
896 return None;
897}
898
Anna Zaks4141e4d2012-11-13 03:18:01 +0000899void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
900 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000901 if (C.wasInlined)
902 return;
903
Jordan Rose9fe09f32013-03-09 00:59:10 +0000904 if (!isKnownDeallocObjCMethodName(Call))
905 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000906
Jordan Rose9fe09f32013-03-09 00:59:10 +0000907 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
908 if (!*FreeWhenDone)
909 return;
910
911 bool ReleasedAllocatedMemory;
912 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
913 Call.getOriginExpr(), C.getState(),
914 /*Hold=*/true, ReleasedAllocatedMemory,
915 /*RetNullOnFailure=*/true);
916
917 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000918}
919
Stephen Hines651f13c2014-04-23 16:59:28 -0700920ProgramStateRef
921MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
922 const OwnershipAttr *Att) const {
923 if (Att->getModule() != II_malloc)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700924 return nullptr;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000925
Sean Huntcf807c42010-08-18 23:23:40 +0000926 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000927 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000928 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000929 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000930 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000931}
932
Anna Zaksb319e022012-02-08 20:13:28 +0000933ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000934 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000935 SVal Size, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000936 ProgramStateRef State,
937 AllocationFamily Family) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000938
Stephen Hines176edba2014-12-01 14:53:08 -0800939 // We expect the malloc functions to return a pointer.
940 if (!Loc::isLocType(CE->getType()))
941 return nullptr;
942
Anna Zakse17fdb22012-06-07 03:57:32 +0000943 // Bind the return value to the symbolic value from the heap region.
944 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
945 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000946 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000947 SValBuilder &svalBuilder = C.getSValBuilder();
948 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000949 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
950 .castAs<DefinedSVal>();
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000951 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000952
Jordy Rose32f26562010-07-04 00:00:41 +0000953 // Fill the region with the initialization value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000954 State = State->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000955
Jordy Rose32f26562010-07-04 00:00:41 +0000956 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000957 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000958 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000959 if (!R)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700960 return nullptr;
David Blaikiedc84cd52013-02-20 22:23:23 +0000961 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000962 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000963 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000964 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000965 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000966 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000967
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000968 State = State->assume(extentMatchesSize, true);
969 assert(State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000970 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000971
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000972 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000973}
974
975ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000976 const Expr *E,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000977 ProgramStateRef State,
978 AllocationFamily Family) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000979 // Get the return value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000980 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000981
982 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000983 if (!retVal.getAs<Loc>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700984 return nullptr;
Anna Zaks87cb5be2012-02-22 19:24:52 +0000985
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000986 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000987 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000988
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000989 // Set the symbol's state to Allocated.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000990 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000991}
992
Anna Zaks87cb5be2012-02-22 19:24:52 +0000993ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
994 const CallExpr *CE,
Stephen Hines651f13c2014-04-23 16:59:28 -0700995 const OwnershipAttr *Att) const {
996 if (Att->getModule() != II_malloc)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700997 return nullptr;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000998
Anna Zaksb3d72752012-03-01 22:06:06 +0000999 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +00001000 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +00001001
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001002 for (const auto &Arg : Att->args()) {
1003 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaks55dd9562012-08-24 02:28:20 +00001004 Att->getOwnKind() == OwnershipAttr::Holds,
1005 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +00001006 if (StateI)
1007 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001008 }
Anna Zaksb3d72752012-03-01 22:06:06 +00001009 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001010}
1011
Ted Kremenek8bef8232012-01-26 21:29:00 +00001012ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +00001013 const CallExpr *CE,
1014 ProgramStateRef state,
1015 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +00001016 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +00001017 bool &ReleasedAllocated,
1018 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001019 if (CE->getNumArgs() < (Num + 1))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001020 return nullptr;
Anna Zaks259052d2012-04-10 23:41:11 +00001021
Anna Zaks4141e4d2012-11-13 03:18:01 +00001022 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
1023 ReleasedAllocated, ReturnsNullOnFailure);
1024}
1025
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001026/// Checks if the previous call to free on the given symbol failed - if free
1027/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +00001028static bool didPreviousFreeFail(ProgramStateRef State,
1029 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001030 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +00001031 if (Ret) {
1032 assert(*Ret && "We should not store the null return symbol");
1033 ConstraintManager &CMgr = State->getConstraintManager();
1034 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001035 RetStatusSymbol = *Ret;
1036 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +00001037 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001038 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +00001039}
1040
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001041AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartsev648cb712013-04-04 23:46:29 +00001042 const Stmt *S) const {
1043 if (!S)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001044 return AF_None;
1045
Anton Yartsev648cb712013-04-04 23:46:29 +00001046 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001047 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartsev648cb712013-04-04 23:46:29 +00001048
1049 if (!FD)
1050 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1051
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001052 ASTContext &Ctx = C.getASTContext();
1053
Stephen Hines176edba2014-12-01 14:53:08 -08001054 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001055 return AF_Malloc;
1056
1057 if (isStandardNewDelete(FD, Ctx)) {
1058 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartsev648cb712013-04-04 23:46:29 +00001059 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001060 return AF_CXXNew;
Anton Yartsev648cb712013-04-04 23:46:29 +00001061 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001062 return AF_CXXNewArray;
1063 }
1064
Stephen Hines176edba2014-12-01 14:53:08 -08001065 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1066 return AF_IfNameIndex;
1067
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001068 return AF_None;
1069 }
1070
Anton Yartsev648cb712013-04-04 23:46:29 +00001071 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1072 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1073
1074 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001075 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1076
Anton Yartsev648cb712013-04-04 23:46:29 +00001077 if (isa<ObjCMessageExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001078 return AF_Malloc;
1079
1080 return AF_None;
1081}
1082
1083bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1084 const Expr *E) const {
1085 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1086 // FIXME: This doesn't handle indirect calls.
1087 const FunctionDecl *FD = CE->getDirectCallee();
1088 if (!FD)
1089 return false;
1090
1091 os << *FD;
1092 if (!FD->isOverloadedOperator())
1093 os << "()";
1094 return true;
1095 }
1096
1097 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1098 if (Msg->isInstanceMessage())
1099 os << "-";
1100 else
1101 os << "+";
Stephen Hines651f13c2014-04-23 16:59:28 -07001102 Msg->getSelector().print(os);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001103 return true;
1104 }
1105
1106 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1107 os << "'"
1108 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1109 << "'";
1110 return true;
1111 }
1112
1113 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1114 os << "'"
1115 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1116 << "'";
1117 return true;
1118 }
1119
1120 return false;
1121}
1122
1123void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1124 const Expr *E) const {
1125 AllocationFamily Family = getAllocationFamily(C, E);
1126
1127 switch(Family) {
1128 case AF_Malloc: os << "malloc()"; return;
1129 case AF_CXXNew: os << "'new'"; return;
1130 case AF_CXXNewArray: os << "'new[]'"; return;
Stephen Hines176edba2014-12-01 14:53:08 -08001131 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001132 case AF_None: llvm_unreachable("not a deallocation expression");
1133 }
1134}
1135
1136void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1137 AllocationFamily Family) const {
1138 switch(Family) {
1139 case AF_Malloc: os << "free()"; return;
1140 case AF_CXXNew: os << "'delete'"; return;
1141 case AF_CXXNewArray: os << "'delete[]'"; return;
Stephen Hines176edba2014-12-01 14:53:08 -08001142 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001143 case AF_None: llvm_unreachable("suspicious AF_None argument");
1144 }
1145}
1146
Anna Zaks5b7aa342012-06-22 02:04:31 +00001147ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1148 const Expr *ArgExpr,
1149 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +00001150 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +00001151 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +00001152 bool &ReleasedAllocated,
1153 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +00001154
Anna Zaks4141e4d2012-11-13 03:18:01 +00001155 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +00001156 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001157 return nullptr;
David Blaikie5251abe2013-02-20 05:52:05 +00001158 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001159
1160 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +00001161 if (!location.getAs<Loc>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001162 return nullptr;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001163
Anna Zaksb276bd92012-02-14 00:26:13 +00001164 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +00001165 ProgramStateRef notNullState, nullState;
Stephen Hines651f13c2014-04-23 16:59:28 -07001166 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001167 if (nullState && !notNullState)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001168 return nullptr;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001169
Jordy Rose43859f62010-06-07 19:32:37 +00001170 // Unknown values could easily be okay
1171 // Undefined values are handled elsewhere
1172 if (ArgVal.isUnknownOrUndef())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001173 return nullptr;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001174
Jordy Rose43859f62010-06-07 19:32:37 +00001175 const MemRegion *R = ArgVal.getAsRegion();
1176
1177 // Nonlocs can't be freed, of course.
1178 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1179 if (!R) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001180 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001181 return nullptr;
Jordy Rose43859f62010-06-07 19:32:37 +00001182 }
1183
1184 R = R->StripCasts();
1185
1186 // Blocks might show up as heap data, but should not be free()d
1187 if (isa<BlockDataRegion>(R)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001188 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001189 return nullptr;
Jordy Rose43859f62010-06-07 19:32:37 +00001190 }
1191
1192 const MemSpaceRegion *MS = R->getMemorySpace();
1193
Anton Yartsevbb369952013-03-13 14:39:10 +00001194 // Parameters, locals, statics, globals, and memory returned by alloca()
1195 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +00001196 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1197 // FIXME: at the time this code was written, malloc() regions were
1198 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1199 // This means that there isn't actually anything from HeapSpaceRegion
1200 // that should be freed, even though we allow it here.
1201 // Of course, free() can work on memory allocated outside the current
1202 // function, so UnknownSpaceRegion is always a possibility.
1203 // False negatives are better than false positives.
1204
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001205 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001206 return nullptr;
Jordy Rose43859f62010-06-07 19:32:37 +00001207 }
Anna Zaks118aa752013-02-07 23:05:47 +00001208
1209 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +00001210 // Various cases could lead to non-symbol values here.
1211 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +00001212 if (!SrBase)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001213 return nullptr;
Jordy Rose43859f62010-06-07 19:32:37 +00001214
Anna Zaks118aa752013-02-07 23:05:47 +00001215 SymbolRef SymBase = SrBase->getSymbol();
1216 const RefState *RsBase = State->get<RegionState>(SymBase);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001217 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +00001218
Anton Yartsev648cb712013-04-04 23:46:29 +00001219 if (RsBase) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001220
Anna Zaks04130232013-04-09 00:30:28 +00001221 // Check for double free first.
1222 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartsev648cb712013-04-04 23:46:29 +00001223 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1224 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1225 SymBase, PreviousRetStatusSymbol);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001226 return nullptr;
Anton Yartsev648cb712013-04-04 23:46:29 +00001227
Anna Zaks04130232013-04-09 00:30:28 +00001228 // If the pointer is allocated or escaped, but we are now trying to free it,
1229 // check that the call to free is proper.
1230 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1231
1232 // Check if an expected deallocation function matches the real one.
1233 bool DeallocMatchesAlloc =
1234 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1235 if (!DeallocMatchesAlloc) {
1236 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsev30845182013-09-16 17:51:25 +00001237 ParentExpr, RsBase, SymBase, Hold);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001238 return nullptr;
Anna Zaks04130232013-04-09 00:30:28 +00001239 }
1240
1241 // Check if the memory location being freed is the actual location
1242 // allocated, or an offset.
1243 RegionOffset Offset = R->getAsOffset();
1244 if (Offset.isValid() &&
1245 !Offset.hasSymbolicOffset() &&
1246 Offset.getOffset() != 0) {
1247 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1248 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1249 AllocExpr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001250 return nullptr;
Anna Zaks04130232013-04-09 00:30:28 +00001251 }
Anton Yartsev648cb712013-04-04 23:46:29 +00001252 }
Anna Zaks118aa752013-02-07 23:05:47 +00001253 }
1254
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001255 ReleasedAllocated = (RsBase != nullptr) && RsBase->isAllocated();
Anna Zaks55dd9562012-08-24 02:28:20 +00001256
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001257 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +00001258 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001259
Anna Zaks4141e4d2012-11-13 03:18:01 +00001260 // Keep track of the return value. If it is NULL, we will know that free
1261 // failed.
1262 if (ReturnsNullOnFailure) {
1263 SVal RetVal = C.getSVal(ParentExpr);
1264 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1265 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +00001266 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1267 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +00001268 }
1269 }
1270
Anton Yartseva3989b82013-04-05 19:08:04 +00001271 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1272 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001273 // Normal free.
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001274 if (Hold)
Anna Zaks118aa752013-02-07 23:05:47 +00001275 return State->set<RegionState>(SymBase,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001276 RefState::getRelinquished(Family,
1277 ParentExpr));
1278
1279 return State->set<RegionState>(SymBase,
1280 RefState::getReleased(Family, ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001281}
1282
Stephen Hines651f13c2014-04-23 16:59:28 -07001283Optional<MallocChecker::CheckKind>
1284MallocChecker::getCheckIfTracked(AllocationFamily Family) const {
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001285 switch (Family) {
Stephen Hines176edba2014-12-01 14:53:08 -08001286 case AF_Malloc:
1287 case AF_IfNameIndex: {
Stephen Hines651f13c2014-04-23 16:59:28 -07001288 if (ChecksEnabled[CK_MallocOptimistic]) {
1289 return CK_MallocOptimistic;
1290 } else if (ChecksEnabled[CK_MallocPessimistic]) {
1291 return CK_MallocPessimistic;
1292 }
1293 return Optional<MallocChecker::CheckKind>();
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001294 }
1295 case AF_CXXNew:
1296 case AF_CXXNewArray: {
Stephen Hines651f13c2014-04-23 16:59:28 -07001297 if (ChecksEnabled[CK_NewDeleteChecker]) {
1298 return CK_NewDeleteChecker;
1299 }
1300 return Optional<MallocChecker::CheckKind>();
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001301 }
1302 case AF_None: {
Anton Yartseva3989b82013-04-05 19:08:04 +00001303 llvm_unreachable("no family");
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001304 }
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001305 }
Anton Yartsevc8454312013-04-05 02:12:04 +00001306 llvm_unreachable("unhandled family");
Anton Yartsev648cb712013-04-04 23:46:29 +00001307}
1308
Stephen Hines651f13c2014-04-23 16:59:28 -07001309Optional<MallocChecker::CheckKind>
1310MallocChecker::getCheckIfTracked(CheckerContext &C,
1311 const Stmt *AllocDeallocStmt) const {
1312 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt));
Anton Yartsev648cb712013-04-04 23:46:29 +00001313}
1314
Stephen Hines651f13c2014-04-23 16:59:28 -07001315Optional<MallocChecker::CheckKind>
1316MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const {
Anton Yartsev648cb712013-04-04 23:46:29 +00001317
Anton Yartseva3989b82013-04-05 19:08:04 +00001318 const RefState *RS = C.getState()->get<RegionState>(Sym);
1319 assert(RS);
Stephen Hines651f13c2014-04-23 16:59:28 -07001320 return getCheckIfTracked(RS->getAllocationFamily());
Anton Yartsev648cb712013-04-04 23:46:29 +00001321}
1322
Ted Kremenek9c378f72011-08-12 23:37:29 +00001323bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001324 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001325 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001326 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001327 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001328 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +00001329 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +00001330 else
1331 return false;
1332
1333 return true;
1334}
1335
Ted Kremenek9c378f72011-08-12 23:37:29 +00001336bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +00001337 const MemRegion *MR) {
1338 switch (MR->getKind()) {
1339 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +00001340 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +00001341 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001342 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +00001343 else
1344 os << "the address of a function";
1345 return true;
1346 }
1347 case MemRegion::BlockTextRegionKind:
1348 os << "block text";
1349 return true;
1350 case MemRegion::BlockDataRegionKind:
1351 // FIXME: where the block came from?
1352 os << "a block";
1353 return true;
1354 default: {
1355 const MemSpaceRegion *MS = MR->getMemorySpace();
1356
Anna Zakseb31a762012-01-04 23:54:01 +00001357 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001358 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1359 const VarDecl *VD;
1360 if (VR)
1361 VD = VR->getDecl();
1362 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001363 VD = nullptr;
1364
Jordy Rose43859f62010-06-07 19:32:37 +00001365 if (VD)
1366 os << "the address of the local variable '" << VD->getName() << "'";
1367 else
1368 os << "the address of a local stack variable";
1369 return true;
1370 }
Anna Zakseb31a762012-01-04 23:54:01 +00001371
1372 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001373 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1374 const VarDecl *VD;
1375 if (VR)
1376 VD = VR->getDecl();
1377 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001378 VD = nullptr;
1379
Jordy Rose43859f62010-06-07 19:32:37 +00001380 if (VD)
1381 os << "the address of the parameter '" << VD->getName() << "'";
1382 else
1383 os << "the address of a parameter";
1384 return true;
1385 }
Anna Zakseb31a762012-01-04 23:54:01 +00001386
1387 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001388 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1389 const VarDecl *VD;
1390 if (VR)
1391 VD = VR->getDecl();
1392 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001393 VD = nullptr;
1394
Jordy Rose43859f62010-06-07 19:32:37 +00001395 if (VD) {
1396 if (VD->isStaticLocal())
1397 os << "the address of the static variable '" << VD->getName() << "'";
1398 else
1399 os << "the address of the global variable '" << VD->getName() << "'";
1400 } else
1401 os << "the address of a global variable";
1402 return true;
1403 }
Anna Zakseb31a762012-01-04 23:54:01 +00001404
1405 return false;
Jordy Rose43859f62010-06-07 19:32:37 +00001406 }
1407 }
1408}
1409
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001410void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1411 SourceRange Range,
1412 const Expr *DeallocExpr) const {
1413
Stephen Hines651f13c2014-04-23 16:59:28 -07001414 if (!ChecksEnabled[CK_MallocOptimistic] &&
1415 !ChecksEnabled[CK_MallocPessimistic] &&
1416 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001417 return;
1418
Stephen Hines651f13c2014-04-23 16:59:28 -07001419 Optional<MallocChecker::CheckKind> CheckKind =
1420 getCheckIfTracked(C, DeallocExpr);
1421 if (!CheckKind.hasValue())
Anton Yartsev648cb712013-04-04 23:46:29 +00001422 return;
1423
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001424 if (ExplodedNode *N = C.generateSink()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001425 if (!BT_BadFree[*CheckKind])
1426 BT_BadFree[*CheckKind].reset(
1427 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1428
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001429 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +00001430 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001431
Jordy Rose43859f62010-06-07 19:32:37 +00001432 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001433 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1434 MR = ER->getSuperRegion();
1435
1436 if (MR && isa<AllocaRegion>(MR))
1437 os << "Memory allocated by alloca() should not be deallocated";
1438 else {
1439 os << "Argument to ";
1440 if (!printAllocDeallocName(os, C, DeallocExpr))
1441 os << "deallocator";
1442
1443 os << " is ";
1444 bool Summarized = MR ? SummarizeRegion(os, MR)
1445 : SummarizeValue(os, ArgVal);
1446 if (Summarized)
1447 os << ", which is not memory allocated by ";
Jordy Rose43859f62010-06-07 19:32:37 +00001448 else
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001449 os << "not memory allocated by ";
1450
1451 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose43859f62010-06-07 19:32:37 +00001452 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001453
Stephen Hines651f13c2014-04-23 16:59:28 -07001454 BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001455 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001456 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001457 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001458 }
1459}
1460
Anton Yartsev648cb712013-04-04 23:46:29 +00001461void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1462 SourceRange Range,
1463 const Expr *DeallocExpr,
Anton Yartseva3ae9372013-04-05 11:25:10 +00001464 const RefState *RS,
Anton Yartsev30845182013-09-16 17:51:25 +00001465 SymbolRef Sym,
1466 bool OwnershipTransferred) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001467
Stephen Hines651f13c2014-04-23 16:59:28 -07001468 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001469 return;
1470
1471 if (ExplodedNode *N = C.generateSink()) {
Anton Yartsev648cb712013-04-04 23:46:29 +00001472 if (!BT_MismatchedDealloc)
Stephen Hines651f13c2014-04-23 16:59:28 -07001473 BT_MismatchedDealloc.reset(
1474 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1475 "Bad deallocator", "Memory Error"));
1476
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001477 SmallString<100> buf;
1478 llvm::raw_svector_ostream os(buf);
1479
1480 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1481 SmallString<20> AllocBuf;
1482 llvm::raw_svector_ostream AllocOs(AllocBuf);
1483 SmallString<20> DeallocBuf;
1484 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1485
Anton Yartsev30845182013-09-16 17:51:25 +00001486 if (OwnershipTransferred) {
1487 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1488 os << DeallocOs.str() << " cannot";
1489 else
1490 os << "Cannot";
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001491
Anton Yartsev30845182013-09-16 17:51:25 +00001492 os << " take ownership of memory";
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001493
Anton Yartsev30845182013-09-16 17:51:25 +00001494 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1495 os << " allocated by " << AllocOs.str();
1496 } else {
1497 os << "Memory";
1498 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1499 os << " allocated by " << AllocOs.str();
1500
1501 os << " should be deallocated by ";
1502 printExpectedDeallocName(os, RS->getAllocationFamily());
1503
1504 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1505 os << ", not " << DeallocOs.str();
1506 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001507
Anton Yartsev648cb712013-04-04 23:46:29 +00001508 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001509 R->markInteresting(Sym);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001510 R->addRange(Range);
Stephen Hines176edba2014-12-01 14:53:08 -08001511 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001512 C.emitReport(R);
1513 }
1514}
1515
Anna Zaks118aa752013-02-07 23:05:47 +00001516void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001517 SourceRange Range, const Expr *DeallocExpr,
1518 const Expr *AllocExpr) const {
1519
Stephen Hines651f13c2014-04-23 16:59:28 -07001520 if (!ChecksEnabled[CK_MallocOptimistic] &&
1521 !ChecksEnabled[CK_MallocPessimistic] &&
1522 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001523 return;
1524
Stephen Hines651f13c2014-04-23 16:59:28 -07001525 Optional<MallocChecker::CheckKind> CheckKind =
1526 getCheckIfTracked(C, AllocExpr);
1527 if (!CheckKind.hasValue())
Anton Yartsev648cb712013-04-04 23:46:29 +00001528 return;
1529
Anna Zaks118aa752013-02-07 23:05:47 +00001530 ExplodedNode *N = C.generateSink();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001531 if (!N)
Anna Zaks118aa752013-02-07 23:05:47 +00001532 return;
1533
Stephen Hines651f13c2014-04-23 16:59:28 -07001534 if (!BT_OffsetFree[*CheckKind])
1535 BT_OffsetFree[*CheckKind].reset(
1536 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaks118aa752013-02-07 23:05:47 +00001537
1538 SmallString<100> buf;
1539 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001540 SmallString<20> AllocNameBuf;
1541 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaks118aa752013-02-07 23:05:47 +00001542
1543 const MemRegion *MR = ArgVal.getAsRegion();
1544 assert(MR && "Only MemRegion based symbols can have offset free errors");
1545
1546 RegionOffset Offset = MR->getAsOffset();
1547 assert((Offset.isValid() &&
1548 !Offset.hasSymbolicOffset() &&
1549 Offset.getOffset() != 0) &&
1550 "Only symbols with a valid offset can have offset free errors");
1551
1552 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1553
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001554 os << "Argument to ";
1555 if (!printAllocDeallocName(os, C, DeallocExpr))
1556 os << "deallocator";
1557 os << " is offset by "
Anna Zaks118aa752013-02-07 23:05:47 +00001558 << offsetBytes
1559 << " "
1560 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001561 << " from the start of ";
1562 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1563 os << "memory allocated by " << AllocNameOs.str();
1564 else
1565 os << "allocated memory";
Anna Zaks118aa752013-02-07 23:05:47 +00001566
Stephen Hines651f13c2014-04-23 16:59:28 -07001567 BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaks118aa752013-02-07 23:05:47 +00001568 R->markInteresting(MR->getBaseRegion());
1569 R->addRange(Range);
1570 C.emitReport(R);
1571}
1572
Anton Yartsevbb369952013-03-13 14:39:10 +00001573void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1574 SymbolRef Sym) const {
1575
Stephen Hines651f13c2014-04-23 16:59:28 -07001576 if (!ChecksEnabled[CK_MallocOptimistic] &&
1577 !ChecksEnabled[CK_MallocPessimistic] &&
1578 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001579 return;
1580
Stephen Hines651f13c2014-04-23 16:59:28 -07001581 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1582 if (!CheckKind.hasValue())
Anton Yartsev648cb712013-04-04 23:46:29 +00001583 return;
1584
Anton Yartsevbb369952013-03-13 14:39:10 +00001585 if (ExplodedNode *N = C.generateSink()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001586 if (!BT_UseFree[*CheckKind])
1587 BT_UseFree[*CheckKind].reset(new BugType(
1588 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsevbb369952013-03-13 14:39:10 +00001589
Stephen Hines651f13c2014-04-23 16:59:28 -07001590 BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
Anton Yartsevbb369952013-03-13 14:39:10 +00001591 "Use of memory after it is freed", N);
1592
1593 R->markInteresting(Sym);
1594 R->addRange(Range);
Stephen Hines176edba2014-12-01 14:53:08 -08001595 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsevbb369952013-03-13 14:39:10 +00001596 C.emitReport(R);
1597 }
1598}
1599
1600void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1601 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001602 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001603
Stephen Hines651f13c2014-04-23 16:59:28 -07001604 if (!ChecksEnabled[CK_MallocOptimistic] &&
1605 !ChecksEnabled[CK_MallocPessimistic] &&
1606 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001607 return;
1608
Stephen Hines651f13c2014-04-23 16:59:28 -07001609 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1610 if (!CheckKind.hasValue())
Anton Yartsev648cb712013-04-04 23:46:29 +00001611 return;
1612
Anton Yartsevbb369952013-03-13 14:39:10 +00001613 if (ExplodedNode *N = C.generateSink()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001614 if (!BT_DoubleFree[*CheckKind])
1615 BT_DoubleFree[*CheckKind].reset(
1616 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsevbb369952013-03-13 14:39:10 +00001617
Stephen Hines651f13c2014-04-23 16:59:28 -07001618 BugReport *R =
1619 new BugReport(*BT_DoubleFree[*CheckKind],
1620 (Released ? "Attempt to free released memory"
1621 : "Attempt to free non-owned memory"),
1622 N);
Anton Yartsevbb369952013-03-13 14:39:10 +00001623 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001624 R->markInteresting(Sym);
1625 if (PrevSym)
1626 R->markInteresting(PrevSym);
Stephen Hines176edba2014-12-01 14:53:08 -08001627 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsevbb369952013-03-13 14:39:10 +00001628 C.emitReport(R);
1629 }
1630}
1631
Stephen Hines651f13c2014-04-23 16:59:28 -07001632void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1633
1634 if (!ChecksEnabled[CK_NewDeleteChecker])
1635 return;
1636
1637 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1638 if (!CheckKind.hasValue())
1639 return;
1640 assert(*CheckKind == CK_NewDeleteChecker && "invalid check kind");
1641
1642 if (ExplodedNode *N = C.generateSink()) {
1643 if (!BT_DoubleDelete)
1644 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1645 "Double delete", "Memory Error"));
1646
1647 BugReport *R = new BugReport(*BT_DoubleDelete,
1648 "Attempt to delete released memory", N);
1649
1650 R->markInteresting(Sym);
Stephen Hines176edba2014-12-01 14:53:08 -08001651 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Stephen Hines651f13c2014-04-23 16:59:28 -07001652 C.emitReport(R);
1653 }
1654}
1655
Anna Zaks87cb5be2012-02-22 19:24:52 +00001656ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1657 const CallExpr *CE,
1658 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001659 if (CE->getNumArgs() < 2)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001660 return nullptr;
Anna Zaks259052d2012-04-10 23:41:11 +00001661
Ted Kremenek8bef8232012-01-26 21:29:00 +00001662 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001663 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001664 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001665 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001666 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001667 return nullptr;
David Blaikie5251abe2013-02-20 05:52:05 +00001668 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001669
Ted Kremenek846eabd2010-12-01 21:28:31 +00001670 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001671
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001672 DefinedOrUnknownSVal PtrEQ =
1673 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001674
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001675 // Get the size argument. If there is no size arg then give up.
1676 const Expr *Arg1 = CE->getArg(1);
1677 if (!Arg1)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001678 return nullptr;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001679
1680 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001681 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001682 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001683 return nullptr;
David Blaikie5251abe2013-02-20 05:52:05 +00001684 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001685
1686 // Compare the size argument to 0.
1687 DefinedOrUnknownSVal SizeZero =
1688 svalBuilder.evalEQ(state, Arg1Val,
1689 svalBuilder.makeIntValWithPtrWidth(0, false));
1690
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001691 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Stephen Hines651f13c2014-04-23 16:59:28 -07001692 std::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001693 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Stephen Hines651f13c2014-04-23 16:59:28 -07001694 std::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001695 // We only assume exceptional states if they are definitely true; if the
1696 // state is under-constrained, assume regular realloc behavior.
1697 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1698 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1699
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001700 // If the ptr is NULL and the size is not 0, the call is equivalent to
1701 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001702 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001703 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001704 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001705 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001706 }
1707
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001708 if (PrtIsNull && SizeIsZero)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001709 return nullptr;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001710
Anna Zaks30838b92012-02-13 20:57:07 +00001711 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001712 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001713 SymbolRef FromPtr = arg0Val.getAsSymbol();
1714 SVal RetVal = state->getSVal(CE, LCtx);
1715 SymbolRef ToPtr = RetVal.getAsSymbol();
1716 if (!FromPtr || !ToPtr)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001717 return nullptr;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001718
Anna Zaks55dd9562012-08-24 02:28:20 +00001719 bool ReleasedAllocated = false;
1720
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001721 // If the size is 0, free the memory.
1722 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001723 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1724 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001725 // The semantics of the return value are:
1726 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001727 // to free() is returned. We just free the input pointer and do not add
1728 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001729 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001730 }
1731
1732 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001733 if (ProgramStateRef stateFree =
1734 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1735
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001736 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1737 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001738 if (!stateRealloc)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001739 return nullptr;
Anna Zaks55dd9562012-08-24 02:28:20 +00001740
Anna Zaks9dc298b2012-09-12 22:57:34 +00001741 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1742 if (FreesOnFail)
1743 Kind = RPIsFreeOnFailure;
1744 else if (!ReleasedAllocated)
1745 Kind = RPDoNotTrackAfterFailure;
1746
Anna Zaks55dd9562012-08-24 02:28:20 +00001747 // Record the info about the reallocated symbol so that we could properly
1748 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001749 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001750 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001751 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001752 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001753 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001754 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001755 return nullptr;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001756}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001757
Anna Zaks87cb5be2012-02-22 19:24:52 +00001758ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001759 if (CE->getNumArgs() < 2)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001760 return nullptr;
Anna Zaks259052d2012-04-10 23:41:11 +00001761
Ted Kremenek8bef8232012-01-26 21:29:00 +00001762 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001763 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001764 const LocationContext *LCtx = C.getLocationContext();
1765 SVal count = state->getSVal(CE->getArg(0), LCtx);
1766 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001767 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1768 svalBuilder.getContext().getSizeType());
1769 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001770
Anna Zaks87cb5be2012-02-22 19:24:52 +00001771 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001772}
1773
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001774LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001775MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1776 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001777 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001778 // Walk the ExplodedGraph backwards and find the first node that referred to
1779 // the tracked symbol.
1780 const ExplodedNode *AllocNode = N;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001781 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001782
1783 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001784 ProgramStateRef State = N->getState();
1785 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001786 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001787
1788 // Find the most recent expression bound to the symbol in the current
1789 // context.
Anna Zaks27d99dd2013-04-10 21:42:02 +00001790 if (!ReferenceRegion) {
1791 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1792 SVal Val = State->getSVal(MR);
1793 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks8cf91f72013-04-10 22:56:33 +00001794 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00001795 // Do not show local variables belonging to a function other than
1796 // where the error is reported.
1797 if (!VR ||
1798 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1799 ReferenceRegion = MR;
1800 }
1801 }
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001802 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001803
Anna Zaks7752d292012-02-27 23:40:55 +00001804 // Allocation node, is the last node in the current context in which the
1805 // symbol was tracked.
1806 if (N->getLocationContext() == LeakContext)
1807 AllocNode = N;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001808 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001809 }
1810
Anna Zaks97bfb552013-01-08 00:25:29 +00001811 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001812}
1813
Anna Zaksda046772012-02-11 21:02:40 +00001814void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1815 CheckerContext &C) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001816
Stephen Hines651f13c2014-04-23 16:59:28 -07001817 if (!ChecksEnabled[CK_MallocOptimistic] &&
1818 !ChecksEnabled[CK_MallocPessimistic] &&
1819 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001820 return;
1821
Jordan Rosee85deb32013-04-05 17:55:00 +00001822 const RefState *RS = C.getState()->get<RegionState>(Sym);
1823 assert(RS && "cannot leak an untracked symbol");
1824 AllocationFamily Family = RS->getAllocationFamily();
Stephen Hines651f13c2014-04-23 16:59:28 -07001825 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
1826 if (!CheckKind.hasValue())
Anton Yartsev418780f2013-04-05 02:25:02 +00001827 return;
1828
Jordan Rosee85deb32013-04-05 17:55:00 +00001829 // Special case for new and new[]; these are controlled by a separate checker
1830 // flag so that they can be selectively disabled.
1831 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
Stephen Hines651f13c2014-04-23 16:59:28 -07001832 if (!ChecksEnabled[CK_NewDeleteLeaksChecker])
Jordan Rosee85deb32013-04-05 17:55:00 +00001833 return;
1834
Anna Zaksda046772012-02-11 21:02:40 +00001835 assert(N);
Stephen Hines651f13c2014-04-23 16:59:28 -07001836 if (!BT_Leak[*CheckKind]) {
1837 BT_Leak[*CheckKind].reset(
1838 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001839 // Leaks should not be reported if they are post-dominated by a sink:
1840 // (1) Sinks are higher importance bugs.
1841 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1842 // with __noreturn functions such as assert() or exit(). We choose not
1843 // to report leaks on such paths.
Stephen Hines651f13c2014-04-23 16:59:28 -07001844 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksda046772012-02-11 21:02:40 +00001845 }
1846
Anna Zaksca8e36e2012-02-23 21:38:21 +00001847 // Most bug reports are cached at the location where they occurred.
1848 // With leaks, we want to unique them by the location where they were
1849 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001850 PathDiagnosticLocation LocUsedForUniqueing;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001851 const ExplodedNode *AllocNode = nullptr;
1852 const MemRegion *Region = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001853 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Anna Zaks97bfb552013-01-08 00:25:29 +00001854
1855 ProgramPoint P = AllocNode->getLocation();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001856 const Stmt *AllocationStmt = nullptr;
David Blaikie7a95de62013-02-21 22:23:56 +00001857 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001858 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001859 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001860 AllocationStmt = SP->getStmt();
Anton Yartsev418780f2013-04-05 02:25:02 +00001861 if (AllocationStmt)
Anna Zaks97bfb552013-01-08 00:25:29 +00001862 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1863 C.getSourceManager(),
1864 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001865
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001866 SmallString<200> buf;
1867 llvm::raw_svector_ostream os(buf);
Jordan Rose919e8a12012-08-08 18:23:36 +00001868 if (Region && Region->canPrintPretty()) {
Anna Zaks9e2f5972013-04-12 18:40:21 +00001869 os << "Potential leak of memory pointed to by ";
Jordan Rose919e8a12012-08-08 18:23:36 +00001870 Region->printPretty(os);
Anna Zaks68eb4c22013-04-06 00:41:36 +00001871 } else {
1872 os << "Potential memory leak";
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001873 }
1874
Stephen Hines651f13c2014-04-23 16:59:28 -07001875 BugReport *R =
1876 new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1877 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001878 R->markInteresting(Sym);
Stephen Hines176edba2014-12-01 14:53:08 -08001879 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001880 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001881}
1882
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001883void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1884 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001885{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001886 if (!SymReaper.hasDeadSymbols())
1887 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001888
Ted Kremenek8bef8232012-01-26 21:29:00 +00001889 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001890 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001891 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001892
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001893 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001894 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1895 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001896 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001897 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001898 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001899 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001900
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001901 }
1902 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001903
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001904 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001905 ReallocPairsTy RP = state->get<ReallocPairs>();
1906 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001907 if (SymReaper.isDead(I->first) ||
1908 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001909 state = state->remove<ReallocPairs>(I->first);
1910 }
1911 }
1912
Anna Zaks4141e4d2012-11-13 03:18:01 +00001913 // Cleanup the FreeReturnValue Map.
1914 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1915 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1916 if (SymReaper.isDead(I->first) ||
1917 SymReaper.isDead(I->second)) {
1918 state = state->remove<FreeReturnValue>(I->first);
1919 }
1920 }
1921
Anna Zaksca8e36e2012-02-23 21:38:21 +00001922 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001923 ExplodedNode *N = C.getPredecessor();
1924 if (!Errors.empty()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001925 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Anna Zaks54458702012-10-29 22:51:54 +00001926 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper09d19ef2013-07-04 03:08:24 +00001927 for (SmallVectorImpl<SymbolRef>::iterator
1928 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001929 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001930 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001931 }
Anna Zaks54458702012-10-29 22:51:54 +00001932
Anna Zaksca8e36e2012-02-23 21:38:21 +00001933 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001934}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001935
Anton Yartsev55e57a52013-04-10 22:21:41 +00001936void MallocChecker::checkPreCall(const CallEvent &Call,
1937 CheckerContext &C) const {
1938
Stephen Hines651f13c2014-04-23 16:59:28 -07001939 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
1940 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
1941 if (!Sym || checkDoubleDelete(Sym, C))
1942 return;
1943 }
1944
Anna Zaks14345182012-05-18 01:16:10 +00001945 // We will check for double free in the post visit.
Anton Yartsev55e57a52013-04-10 22:21:41 +00001946 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
1947 const FunctionDecl *FD = FC->getDecl();
1948 if (!FD)
1949 return;
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001950
Stephen Hines176edba2014-12-01 14:53:08 -08001951 ASTContext &Ctx = C.getASTContext();
Stephen Hines651f13c2014-04-23 16:59:28 -07001952 if ((ChecksEnabled[CK_MallocOptimistic] ||
1953 ChecksEnabled[CK_MallocPessimistic]) &&
Stephen Hines176edba2014-12-01 14:53:08 -08001954 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
1955 isCMemFunction(FD, Ctx, AF_IfNameIndex,
1956 MemoryOperationKind::MOK_Free)))
Anton Yartsev55e57a52013-04-10 22:21:41 +00001957 return;
Anna Zaks66c40402012-02-14 21:55:24 +00001958
Stephen Hines651f13c2014-04-23 16:59:28 -07001959 if (ChecksEnabled[CK_NewDeleteChecker] &&
Stephen Hines176edba2014-12-01 14:53:08 -08001960 isStandardNewDelete(FD, Ctx))
Anton Yartsev55e57a52013-04-10 22:21:41 +00001961 return;
1962 }
1963
1964 // Check if the callee of a method is deleted.
1965 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
1966 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
1967 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
1968 return;
1969 }
1970
1971 // Check arguments for being used after free.
1972 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
1973 SVal ArgSVal = Call.getArgSVal(I);
1974 if (ArgSVal.getAs<Loc>()) {
1975 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001976 if (!Sym)
1977 continue;
Anton Yartsev55e57a52013-04-10 22:21:41 +00001978 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks66c40402012-02-14 21:55:24 +00001979 return;
1980 }
1981 }
1982}
1983
Anna Zaks91c2a112012-02-08 23:16:56 +00001984void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1985 const Expr *E = S->getRetValue();
1986 if (!E)
1987 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001988
1989 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001990 ProgramStateRef State = C.getState();
1991 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001992 SymbolRef Sym = RetVal.getAsSymbol();
1993 if (!Sym)
1994 // If we are returning a field of the allocated struct or an array element,
1995 // the callee could still free the memory.
1996 // TODO: This logic should be a part of generic symbol escape callback.
1997 if (const MemRegion *MR = RetVal.getAsRegion())
1998 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1999 if (const SymbolicRegion *BMR =
2000 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2001 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00002002
Anna Zaks0860cd02012-02-11 21:44:39 +00002003 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00002004 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00002005 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00002006}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00002007
Anna Zaksf5aa3f52012-03-22 00:57:20 +00002008// TODO: Blocks should be either inlined or should call invalidate regions
2009// upon invocation. After that's in place, special casing here will not be
2010// needed.
2011void MallocChecker::checkPostStmt(const BlockExpr *BE,
2012 CheckerContext &C) const {
2013
2014 // Scan the BlockDecRefExprs for any object the retain count checker
2015 // may be tracking.
2016 if (!BE->getBlockDecl()->hasCaptures())
2017 return;
2018
2019 ProgramStateRef state = C.getState();
2020 const BlockDataRegion *R =
2021 cast<BlockDataRegion>(state->getSVal(BE,
2022 C.getLocationContext()).getAsRegion());
2023
2024 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2025 E = R->referenced_vars_end();
2026
2027 if (I == E)
2028 return;
2029
2030 SmallVector<const MemRegion*, 10> Regions;
2031 const LocationContext *LC = C.getLocationContext();
2032 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2033
2034 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00002035 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00002036 if (VR->getSuperRegion() == R) {
2037 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2038 }
2039 Regions.push_back(VR);
2040 }
2041
2042 state =
2043 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2044 Regions.data() + Regions.size()).getState();
2045 C.addTransition(state);
2046}
2047
Anna Zaks14345182012-05-18 01:16:10 +00002048bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00002049 assert(Sym);
2050 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00002051 return (RS && RS->isReleased());
2052}
2053
2054bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2055 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00002056
Stephen Hines651f13c2014-04-23 16:59:28 -07002057 if (isReleased(Sym, C)) {
Anton Yartsevbb369952013-03-13 14:39:10 +00002058 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2059 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00002060 }
Anton Yartsevbb369952013-03-13 14:39:10 +00002061
Anna Zaks91c2a112012-02-08 23:16:56 +00002062 return false;
2063}
2064
Stephen Hines651f13c2014-04-23 16:59:28 -07002065bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2066
2067 if (isReleased(Sym, C)) {
2068 ReportDoubleDelete(C, Sym);
2069 return true;
2070 }
2071 return false;
2072}
2073
Zhongxing Xuc8023782010-03-10 04:58:55 +00002074// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00002075void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2076 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00002077 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00002078 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00002079 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00002080}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00002081
Anna Zaks4fb54872012-02-11 21:02:35 +00002082// If a symbolic region is assumed to NULL (or another constant), stop tracking
2083// it - assuming that allocation failed on this path.
2084ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2085 SVal Cond,
2086 bool Assumption) const {
2087 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00002088 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00002089 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00002090 ConstraintManager &CMgr = state->getConstraintManager();
2091 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2092 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00002093 state = state->remove<RegionState>(I.getKey());
2094 }
2095
Anna Zaksc8bb3be2012-02-13 18:05:39 +00002096 // Realloc returns 0 when reallocation fails, which means that we should
2097 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00002098 ReallocPairsTy RP = state->get<ReallocPairs>();
2099 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00002100 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00002101 ConstraintManager &CMgr = state->getConstraintManager();
2102 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00002103 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00002104 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00002105
Anna Zaks9dc298b2012-09-12 22:57:34 +00002106 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2107 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2108 if (RS->isReleased()) {
2109 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00002110 state = state->set<RegionState>(ReallocSym,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002111 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks9dc298b2012-09-12 22:57:34 +00002112 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2113 state = state->remove<RegionState>(ReallocSym);
2114 else
2115 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00002116 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00002117 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00002118 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00002119 }
2120
Anna Zaks4fb54872012-02-11 21:02:35 +00002121 return state;
2122}
2123
Anna Zaks33708592013-06-08 00:29:29 +00002124bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zakse7a5c822013-05-31 23:47:32 +00002125 const CallEvent *Call,
2126 ProgramStateRef State,
2127 SymbolRef &EscapingSymbol) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00002128 assert(Call);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002129 EscapingSymbol = nullptr;
2130
Stephen Hines651f13c2014-04-23 16:59:28 -07002131 // For now, assume that any C++ or block call can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00002132 // TODO: If we want to be more optimistic here, we'll need to make sure that
2133 // regions escape to C++ containers. They seem to do that even now, but for
2134 // mysterious reasons.
Stephen Hines651f13c2014-04-23 16:59:28 -07002135 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zakse7a5c822013-05-31 23:47:32 +00002136 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00002137
Jordan Rose740d4902012-07-02 19:27:35 +00002138 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00002139 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00002140 // If it's not a framework call, or if it takes a callback, assume it
2141 // can free memory.
2142 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zakse7a5c822013-05-31 23:47:32 +00002143 return true;
Anna Zaks07d39a42012-02-28 01:54:22 +00002144
Jordan Rose9fe09f32013-03-09 00:59:10 +00002145 // If it's a method we know about, handle it explicitly post-call.
2146 // This should happen before the "freeWhenDone" check below.
2147 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zakse7a5c822013-05-31 23:47:32 +00002148 return false;
Anna Zaks52a04812012-06-20 23:35:57 +00002149
Jordan Rose9fe09f32013-03-09 00:59:10 +00002150 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2151 // about, we can't be sure that the object will use free() to deallocate the
2152 // memory, so we can't model it explicitly. The best we can do is use it to
2153 // decide whether the pointer escapes.
2154 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zakse7a5c822013-05-31 23:47:32 +00002155 return *FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00002156
Jordan Rose9fe09f32013-03-09 00:59:10 +00002157 // If the first selector piece ends with "NoCopy", and there is no
2158 // "freeWhenDone" parameter set to zero, we know ownership is being
2159 // transferred. Again, though, we can't be sure that the object will use
2160 // free() to deallocate the memory, so we can't model it explicitly.
2161 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00002162 if (FirstSlot.endswith("NoCopy"))
Anna Zakse7a5c822013-05-31 23:47:32 +00002163 return true;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00002164
Anna Zaks5f757682012-06-19 05:10:32 +00002165 // If the first selector starts with addPointer, insertPointer,
2166 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2167 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00002168 // that the pointers get freed by following the container itself.
2169 if (FirstSlot.startswith("addPointer") ||
2170 FirstSlot.startswith("insertPointer") ||
Stephen Hines651f13c2014-04-23 16:59:28 -07002171 FirstSlot.startswith("replacePointer") ||
2172 FirstSlot.equals("valueWithPointer")) {
Anna Zakse7a5c822013-05-31 23:47:32 +00002173 return true;
Anna Zaks5f757682012-06-19 05:10:32 +00002174 }
2175
Anna Zakse7a5c822013-05-31 23:47:32 +00002176 // We should escape receiver on call to 'init'. This is especially relevant
2177 // to the receiver, as the corresponding symbol is usually not referenced
2178 // after the call.
2179 if (Msg->getMethodFamily() == OMF_init) {
2180 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2181 return true;
2182 }
Anna Zaksee1af232013-05-31 22:39:13 +00002183
Jordan Rose740d4902012-07-02 19:27:35 +00002184 // Otherwise, assume that the method does not free memory.
2185 // Most framework methods do not free memory.
Anna Zakse7a5c822013-05-31 23:47:32 +00002186 return false;
Anna Zaks66c40402012-02-14 21:55:24 +00002187 }
2188
Jordan Rose740d4902012-07-02 19:27:35 +00002189 // At this point the only thing left to handle is straight function calls.
Stephen Hines651f13c2014-04-23 16:59:28 -07002190 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose740d4902012-07-02 19:27:35 +00002191 if (!FD)
Anna Zakse7a5c822013-05-31 23:47:32 +00002192 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00002193
Jordan Rose740d4902012-07-02 19:27:35 +00002194 ASTContext &ASTC = State->getStateManager().getContext();
2195
2196 // If it's one of the allocation functions we can reason about, we model
2197 // its behavior explicitly.
2198 if (isMemFunction(FD, ASTC))
Anna Zakse7a5c822013-05-31 23:47:32 +00002199 return false;
Jordan Rose740d4902012-07-02 19:27:35 +00002200
2201 // If it's not a system call, assume it frees memory.
2202 if (!Call->isInSystemHeader())
Anna Zakse7a5c822013-05-31 23:47:32 +00002203 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002204
2205 // White list the system functions whose arguments escape.
2206 const IdentifierInfo *II = FD->getIdentifier();
2207 if (!II)
Anna Zakse7a5c822013-05-31 23:47:32 +00002208 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002209 StringRef FName = II->getName();
2210
Jordan Rose740d4902012-07-02 19:27:35 +00002211 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00002212 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00002213 if (FName.endswith("NoCopy")) {
2214 // Look for the deallocator argument. We know that the memory ownership
2215 // is not transferred only if the deallocator argument is
2216 // 'kCFAllocatorNull'.
2217 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2218 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2219 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2220 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2221 if (DeallocatorName == "kCFAllocatorNull")
Anna Zakse7a5c822013-05-31 23:47:32 +00002222 return false;
Jordan Rose740d4902012-07-02 19:27:35 +00002223 }
2224 }
Anna Zakse7a5c822013-05-31 23:47:32 +00002225 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002226 }
2227
Jordan Rose740d4902012-07-02 19:27:35 +00002228 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00002229 // 'closefn' is specified (and if that function does free memory),
2230 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00002231 // Currently, we do not inspect the 'closefn' function (PR12101).
2232 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00002233 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zakse7a5c822013-05-31 23:47:32 +00002234 return false;
Jordan Rose740d4902012-07-02 19:27:35 +00002235
2236 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2237 // these leaks might be intentional when setting the buffer for stdio.
2238 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2239 if (FName == "setbuf" || FName =="setbuffer" ||
2240 FName == "setlinebuf" || FName == "setvbuf") {
2241 if (Call->getNumArgs() >= 1) {
2242 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2243 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2244 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2245 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zakse7a5c822013-05-31 23:47:32 +00002246 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002247 }
2248 }
2249
2250 // A bunch of other functions which either take ownership of a pointer or
2251 // wrap the result up in a struct or object, meaning it can be freed later.
2252 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2253 // but the Malloc checker cannot differentiate between them. The right way
2254 // of doing this would be to implement a pointer escapes callback.
2255 if (FName == "CGBitmapContextCreate" ||
2256 FName == "CGBitmapContextCreateWithData" ||
2257 FName == "CVPixelBufferCreateWithBytes" ||
2258 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2259 FName == "OSAtomicEnqueue") {
Anna Zakse7a5c822013-05-31 23:47:32 +00002260 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002261 }
2262
Jordan Rose85d7e012012-07-02 19:27:51 +00002263 // Handle cases where we know a buffer's /address/ can escape.
2264 // Note that the above checks handle some special cases where we know that
2265 // even though the address escapes, it's still our responsibility to free the
2266 // buffer.
2267 if (Call->argumentsMayEscape())
Anna Zakse7a5c822013-05-31 23:47:32 +00002268 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002269
2270 // Otherwise, assume that the function does not free memory.
2271 // Most system calls do not free the memory.
Anna Zakse7a5c822013-05-31 23:47:32 +00002272 return false;
Anna Zaks66c40402012-02-14 21:55:24 +00002273}
2274
Anna Zaks41988f32013-03-28 23:15:29 +00002275static bool retTrue(const RefState *RS) {
2276 return true;
2277}
2278
2279static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2280 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2281 RS->getAllocationFamily() == AF_CXXNew);
2282}
2283
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002284ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2285 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00002286 const CallEvent *Call,
2287 PointerEscapeKind Kind) const {
Anna Zaks41988f32013-03-28 23:15:29 +00002288 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2289}
2290
2291ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2292 const InvalidatedSymbols &Escaped,
2293 const CallEvent *Call,
2294 PointerEscapeKind Kind) const {
2295 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2296 &checkIfNewOrNewArrayFamily);
2297}
2298
2299ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2300 const InvalidatedSymbols &Escaped,
2301 const CallEvent *Call,
2302 PointerEscapeKind Kind,
2303 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00002304 // If we know that the call does not free memory, or we want to process the
2305 // call later, keep tracking the top level arguments.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002306 SymbolRef EscapingSymbol = nullptr;
Jordan Rose374ae322013-05-10 17:07:16 +00002307 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks33708592013-06-08 00:29:29 +00002308 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2309 EscapingSymbol) &&
Anna Zakse7a5c822013-05-31 23:47:32 +00002310 !EscapingSymbol) {
Anna Zaks66c40402012-02-14 21:55:24 +00002311 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00002312 }
Anna Zaks66c40402012-02-14 21:55:24 +00002313
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002314 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks41988f32013-03-28 23:15:29 +00002315 E = Escaped.end();
2316 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00002317 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002318
Anna Zakse7a5c822013-05-31 23:47:32 +00002319 if (EscapingSymbol && EscapingSymbol != sym)
2320 continue;
2321
Anna Zaks5b7aa342012-06-22 02:04:31 +00002322 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks04130232013-04-09 00:30:28 +00002323 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks431e35c2012-08-09 00:42:24 +00002324 State = State->remove<RegionState>(sym);
Anna Zaks04130232013-04-09 00:30:28 +00002325 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2326 }
Anna Zaks5b7aa342012-06-22 02:04:31 +00002327 }
Anna Zaks4fb54872012-02-11 21:02:35 +00002328 }
Anna Zaks66c40402012-02-14 21:55:24 +00002329 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00002330}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002331
Jordy Rose393f98b2012-03-18 07:43:35 +00002332static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2333 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00002334 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2335 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00002336
Jordan Rose166d5022012-11-02 01:54:06 +00002337 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00002338 I != E; ++I) {
2339 SymbolRef sym = I.getKey();
2340 if (!currMap.lookup(sym))
2341 return sym;
2342 }
2343
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002344 return nullptr;
Jordy Rose393f98b2012-03-18 07:43:35 +00002345}
2346
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002347PathDiagnosticPiece *
2348MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2349 const ExplodedNode *PrevN,
2350 BugReporterContext &BRC,
2351 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00002352 ProgramStateRef state = N->getState();
2353 ProgramStateRef statePrev = PrevN->getState();
2354
2355 const RefState *RS = state->get<RegionState>(Sym);
2356 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00002357 if (!RS)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002358 return nullptr;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002359
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002360 const Stmt *S = nullptr;
2361 const char *Msg = nullptr;
2362 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaksfe571602012-02-16 22:26:07 +00002363
2364 // Retrieve the associated statement.
2365 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002366 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002367 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00002368 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002369 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00002370 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00002371 // If an assumption was made on a branch, it should be caught
2372 // here by looking at the state transition.
2373 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00002374 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00002375
Anna Zaksfe571602012-02-16 22:26:07 +00002376 if (!S)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002377 return nullptr;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002378
Jordan Rose28038f32012-07-10 22:07:42 +00002379 // FIXME: We will eventually need to handle non-statement-based events
2380 // (__attribute__((cleanup))).
2381
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002382 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00002383 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00002384 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002385 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00002386 StackHint = new StackHintGeneratorForSymbol(Sym,
2387 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00002388 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002389 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00002390 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zaks148d9222013-04-16 00:22:55 +00002391 "Returning; memory was released");
Anna Zaks5b7aa342012-06-22 02:04:31 +00002392 } else if (isRelinquished(RS, RSPrev, S)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002393 Msg = "Memory ownership is transferred";
Anna Zaks5b7aa342012-06-22 02:04:31 +00002394 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00002395 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002396 Mode = ReallocationFailed;
2397 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00002398 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00002399 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00002400
Jordy Roseb000fb52012-03-24 03:15:09 +00002401 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2402 // Is it possible to fail two reallocs WITHOUT testing in between?
2403 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2404 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00002405 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00002406 FailedReallocSymbol = sym;
2407 }
Anna Zaksfe571602012-02-16 22:26:07 +00002408 }
2409
2410 // We are in a special mode if a reallocation failed later in the path.
2411 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002412 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00002413
Jordy Roseb000fb52012-03-24 03:15:09 +00002414 // Is this is the first appearance of the reallocated symbol?
2415 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002416 // We're at the reallocation point.
2417 Msg = "Attempt to reallocate memory";
2418 StackHint = new StackHintGeneratorForSymbol(Sym,
2419 "Returned reallocated memory");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002420 FailedReallocSymbol = nullptr;
Jordy Roseb000fb52012-03-24 03:15:09 +00002421 Mode = Normal;
2422 }
Anna Zaksfe571602012-02-16 22:26:07 +00002423 }
2424
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002425 if (!Msg)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002426 return nullptr;
Anna Zaks56a938f2012-03-16 23:24:20 +00002427 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002428
2429 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00002430 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002431 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00002432 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002433}
2434
Anna Zaks93c5a242012-05-02 00:05:20 +00002435void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2436 const char *NL, const char *Sep) const {
2437
2438 RegionStateTy RS = State->get<RegionState>();
2439
Ted Kremenekc37fad62013-01-03 01:30:12 +00002440 if (!RS.isEmpty()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002441 Out << Sep << "MallocChecker :" << NL;
Ted Kremenekc37fad62013-01-03 01:30:12 +00002442 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002443 const RefState *RefS = State->get<RegionState>(I.getKey());
2444 AllocationFamily Family = RefS->getAllocationFamily();
2445 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2446
Ted Kremenekc37fad62013-01-03 01:30:12 +00002447 I.getKey()->dumpToStream(Out);
2448 Out << " : ";
2449 I.getData().dump(Out);
Stephen Hines651f13c2014-04-23 16:59:28 -07002450 if (CheckKind.hasValue())
2451 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenekc37fad62013-01-03 01:30:12 +00002452 Out << NL;
2453 }
2454 }
Anna Zaks93c5a242012-05-02 00:05:20 +00002455}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002456
Anna Zaks148d9222013-04-16 00:22:55 +00002457void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2458 registerCStringCheckerBasic(mgr);
Stephen Hines651f13c2014-04-23 16:59:28 -07002459 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2460 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2461 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2462 mgr.getCurrentCheckName();
Anna Zaks148d9222013-04-16 00:22:55 +00002463 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2464 // checker.
Stephen Hines651f13c2014-04-23 16:59:28 -07002465 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
2466 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zaks148d9222013-04-16 00:22:55 +00002467}
Anton Yartsev9df151c2013-04-12 23:25:40 +00002468
Stephen Hines651f13c2014-04-23 16:59:28 -07002469#define REGISTER_CHECKER(name) \
2470 void ento::register##name(CheckerManager &mgr) { \
2471 registerCStringCheckerBasic(mgr); \
2472 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2473 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2474 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2475 }
Anna Zaks231361a2012-02-08 23:16:52 +00002476
2477REGISTER_CHECKER(MallocPessimistic)
2478REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00002479REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002480REGISTER_CHECKER(MismatchedDeallocatorChecker)