blob: 498465d514390929aceb4f57e1d62e07e5af77ee [file] [log] [blame]
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines malloc/free checker, which checks for potential memory
11// leaks, double free, and use-after-free problems.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zakse56167e2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +000018#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Basic/SourceManager.h"
Jordan Rose6b33c6f2014-03-26 17:05:46 +000020#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000022#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000023#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000028#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000029#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000030#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000032#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000033#include <climits>
34
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000035using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000036using namespace ento;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000037
38namespace {
39
Anton Yartsev05789592013-03-28 17:05:19 +000040// Used to check correspondence between allocators and deallocators.
41enum AllocationFamily {
42 AF_None,
43 AF_Malloc,
44 AF_CXXNew,
Anna Zaksd79b8402014-10-03 21:48:59 +000045 AF_CXXNewArray,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +000046 AF_IfNameIndex,
47 AF_Alloca
Anton Yartsev05789592013-03-28 17:05:19 +000048};
49
Zhongxing Xu1239de12009-12-11 00:55:44 +000050class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000051 enum Kind { // Reference to allocated memory.
52 Allocated,
53 // Reference to released/freed memory.
54 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000055 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000056 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000057 Relinquished,
58 // We are no longer guaranteed to have observed all manipulations
59 // of this pointer/memory. For example, it could have been
60 // passed as a parameter to an opaque function.
61 Escaped
62 };
Anton Yartsev05789592013-03-28 17:05:19 +000063
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000064 const Stmt *S;
Anton Yartsev05789592013-03-28 17:05:19 +000065 unsigned K : 2; // Kind enum, but stored as a bitfield.
66 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
67 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000068
Anton Yartsev05789592013-03-28 17:05:19 +000069 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000070 : S(s), K(k), Family(family) {
71 assert(family != AF_None);
72 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000073public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000074 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000075 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000076 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000077 bool isEscaped() const { return K == Escaped; }
78 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000079 return (AllocationFamily)Family;
80 }
Anna Zaksd56c8792012-02-13 18:05:39 +000081 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000082
83 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000084 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000085 }
86
Anton Yartsev05789592013-03-28 17:05:19 +000087 static RefState getAllocated(unsigned family, const Stmt *s) {
88 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000089 }
Anton Yartsev05789592013-03-28 17:05:19 +000090 static RefState getReleased(unsigned family, const Stmt *s) {
91 return RefState(Released, s, family);
92 }
93 static RefState getRelinquished(unsigned family, const Stmt *s) {
94 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +000095 }
Anna Zaks93a21a82013-04-09 00:30:28 +000096 static RefState getEscaped(const RefState *RS) {
97 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
98 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000099
100 void Profile(llvm::FoldingSetNodeID &ID) const {
101 ID.AddInteger(K);
102 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +0000103 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000104 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000105
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000106 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000107 switch (static_cast<Kind>(K)) {
108#define CASE(ID) case ID: OS << #ID; break;
109 CASE(Allocated)
110 CASE(Released)
111 CASE(Relinquished)
112 CASE(Escaped)
113 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000114 }
115
Alp Tokeref6b0072014-01-04 13:47:14 +0000116 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000117};
118
Anna Zaks75cfbb62012-09-12 22:57:34 +0000119enum ReallocPairKind {
120 RPToBeFreedAfterFailure,
121 // The symbol has been freed when reallocation failed.
122 RPIsFreeOnFailure,
123 // The symbol does not need to be freed after reallocation fails.
124 RPDoNotTrackAfterFailure
125};
126
Anna Zaksfe6eb672012-08-24 02:28:20 +0000127/// \class ReallocPair
128/// \brief Stores information about the symbol being reallocated by a call to
129/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000130struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000131 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000132 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000133 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000134
Anna Zaks75cfbb62012-09-12 22:57:34 +0000135 ReallocPair(SymbolRef S, ReallocPairKind K) :
136 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000137 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000138 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000139 ID.AddPointer(ReallocatedSym);
140 }
141 bool operator==(const ReallocPair &X) const {
142 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000143 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000144 }
145};
146
Anna Zaksa043d0c2013-01-08 00:25:29 +0000147typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000148
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000149class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000150 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000151 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000152 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000153 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000154 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000155 check::PostStmt<CXXNewExpr>,
156 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000157 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000158 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000159 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000160 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000161{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000162public:
Craig Topper0dbb7832014-05-27 02:45:47 +0000163 MallocChecker()
Anton Yartsevc38d7952015-03-03 22:58:46 +0000164 : II_alloca(nullptr), II_malloc(nullptr), II_free(nullptr),
165 II_realloc(nullptr), II_calloc(nullptr), II_valloc(nullptr),
166 II_reallocf(nullptr), II_strndup(nullptr), II_strdup(nullptr),
167 II_kmalloc(nullptr), II_if_nameindex(nullptr),
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000168 II_if_freenameindex(nullptr) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000169
170 /// In pessimistic mode, the checker assumes that it does not know which
171 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000172 enum CheckKind {
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000173 CK_MallocChecker,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000174 CK_NewDeleteChecker,
175 CK_NewDeleteLeaksChecker,
176 CK_MismatchedDeallocatorChecker,
177 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000178 };
179
Anna Zaksd79b8402014-10-03 21:48:59 +0000180 enum class MemoryOperationKind {
181 MOK_Allocate,
182 MOK_Free,
183 MOK_Any
184 };
185
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000186 DefaultBool IsOptimistic;
187
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000188 DefaultBool ChecksEnabled[CK_NumCheckKinds];
189 CheckName CheckNames[CK_NumCheckKinds];
Anton Yartseve5c0c142015-02-18 00:39:06 +0000190 typedef llvm::SmallVector<CheckKind, CK_NumCheckKinds> CKVecTy;
Anna Zakscd37bf42012-02-08 23:16:52 +0000191
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000192 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000193 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000194 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
195 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000196 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000197 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000198 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000199 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000200 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000201 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000202 void checkLocation(SVal l, bool isLoad, const Stmt *S,
203 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000204
205 ProgramStateRef checkPointerEscape(ProgramStateRef State,
206 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000207 const CallEvent *Call,
208 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000209 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
210 const InvalidatedSymbols &Escaped,
211 const CallEvent *Call,
212 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000213
Anna Zaks263b7e02012-05-02 00:05:20 +0000214 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000215 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000216
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000217private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000218 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
219 mutable std::unique_ptr<BugType> BT_DoubleDelete;
220 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
221 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
222 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000223 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000224 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
225 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevc38d7952015-03-03 22:58:46 +0000226 mutable IdentifierInfo *II_alloca, *II_malloc, *II_free, *II_realloc,
227 *II_calloc, *II_valloc, *II_reallocf, *II_strndup,
228 *II_strdup, *II_kmalloc, *II_if_nameindex,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000229 *II_if_freenameindex;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000230 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000231
Anna Zaks3d348342012-02-14 21:55:24 +0000232 void initIdentifierInfo(ASTContext &C) const;
233
Anton Yartsev05789592013-03-28 17:05:19 +0000234 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000235 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000236
237 /// \brief Print names of allocators and deallocators.
238 ///
239 /// \returns true on success.
240 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
241 const Expr *E) const;
242
243 /// \brief Print expected name of an allocator based on the deallocator's
244 /// family derived from the DeallocExpr.
245 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
246 const Expr *DeallocExpr) const;
247 /// \brief Print expected name of a deallocator based on the allocator's
248 /// family.
249 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
250
Jordan Rose613f3c02013-03-09 00:59:10 +0000251 ///@{
Anna Zaks3d348342012-02-14 21:55:24 +0000252 /// Check if this is one of the functions which can allocate/reallocate memory
253 /// pointed to by one of its arguments.
254 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000255 bool isCMemFunction(const FunctionDecl *FD,
256 ASTContext &C,
257 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000258 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000259 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000260 ///@}
Richard Smith852e9ce2013-11-27 01:46:48 +0000261 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
262 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000263 const OwnershipAttr* Att,
264 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000265 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000266 const Expr *SizeEx, SVal Init,
267 ProgramStateRef State,
268 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000269 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000270 SVal SizeEx, SVal Init,
271 ProgramStateRef State,
272 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000273
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000274 // Check if this malloc() for special flags. At present that means M_ZERO or
275 // __GFP_ZERO (in which case, treat it like calloc).
276 llvm::Optional<ProgramStateRef>
277 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
278 const ProgramStateRef &State) const;
279
Anna Zaks40a7eb32012-02-22 19:24:52 +0000280 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev05789592013-03-28 17:05:19 +0000281 static ProgramStateRef
282 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
283 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000284
285 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000286 const OwnershipAttr* Att,
287 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000288 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000289 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000290 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000291 bool &ReleasedAllocated,
292 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000293 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
294 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000295 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000296 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000297 bool &ReleasedAllocated,
298 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000299
Anna Zaks40a7eb32012-02-22 19:24:52 +0000300 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000301 bool FreesMemOnFailure,
302 ProgramStateRef State) const;
303 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
304 ProgramStateRef State);
Jordy Rose3597b212010-06-07 19:32:37 +0000305
Anna Zaks46d01602012-05-18 01:16:10 +0000306 ///\brief Check if the memory associated with this symbol was released.
307 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
308
Anton Yartsev13df0362013-03-25 01:35:45 +0000309 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000310
Jordan Rose656fdd52014-01-08 18:46:55 +0000311 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
312
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000313 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000314 /// "interesting" and should be modeled explicitly.
315 ///
Anna Zaks8ebeb642013-06-08 00:29:29 +0000316 /// \param [out] EscapingSymbol A function might not free memory in general,
317 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000318 /// returned and the single escaping symbol is returned through the out
319 /// parameter.
320 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000321 /// We assume that pointers do not escape through calls to system functions
322 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000323 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000324 ProgramStateRef State,
325 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000326
Anna Zaks333481b2013-03-28 23:15:29 +0000327 // Implementation of the checkPointerEscape callabcks.
328 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
329 const InvalidatedSymbols &Escaped,
330 const CallEvent *Call,
331 PointerEscapeKind Kind,
332 bool(*CheckRefState)(const RefState*)) const;
333
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000334 ///@{
335 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000336 /// Sets CheckKind to the kind of the checker responsible for this
337 /// family/call/symbol.
338 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family) const;
339 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000340 const Stmt *AllocDeallocStmt) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000341 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000342 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000343 static bool SummarizeValue(raw_ostream &os, SVal V);
344 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev05789592013-03-28 17:05:19 +0000345 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
346 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000347 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
348 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000349 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000350 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000351 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000352 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
353 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000354 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000355 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
356 SymbolRef Sym) const;
357 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000358 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000359
Jordan Rose656fdd52014-01-08 18:46:55 +0000360 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
361
Anna Zaksdf901a42012-02-23 21:38:21 +0000362 /// Find the location of the allocation for Sym on the path leading to the
363 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000364 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
365 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000366
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000367 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
368
Anna Zaks2b5bb972012-02-09 06:25:51 +0000369 /// The bug visitor which allows us to print extra diagnostics along the
370 /// BugReport path. For example, showing the allocation site of the leaked
371 /// region.
Jordy Rosef78877e2012-03-24 02:45:35 +0000372 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000373 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000374 enum NotificationMode {
375 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000376 ReallocationFailed
377 };
378
Anna Zaks2b5bb972012-02-09 06:25:51 +0000379 // The allocated region symbol tracked by the main analysis.
380 SymbolRef Sym;
381
Anna Zaks62cce9e2012-05-10 01:37:40 +0000382 // The mode we are in, i.e. what kind of diagnostics will be emitted.
383 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000384
Anna Zaks62cce9e2012-05-10 01:37:40 +0000385 // A symbol from when the primary region should have been reallocated.
386 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000387
Anna Zaks62cce9e2012-05-10 01:37:40 +0000388 bool IsLeak;
389
390 public:
391 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000392 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000393
Anna Zaks2b5bb972012-02-09 06:25:51 +0000394 virtual ~MallocBugVisitor() {}
395
Craig Topperfb6b25b2014-03-15 04:29:04 +0000396 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000397 static int X = 0;
398 ID.AddPointer(&X);
399 ID.AddPointer(Sym);
400 }
401
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000402 inline bool isAllocated(const RefState *S, const RefState *SPrev,
403 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000404 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000405 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000406 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000407 }
408
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000409 inline bool isReleased(const RefState *S, const RefState *SPrev,
410 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000411 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000412 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000413 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
414 }
415
Anna Zaks0d6989b2012-06-22 02:04:31 +0000416 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
417 const Stmt *Stmt) {
418 // Did not track -> relinquished. Other state (allocated) -> relinquished.
419 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
420 isa<ObjCPropertyRefExpr>(Stmt)) &&
421 (S && S->isRelinquished()) &&
422 (!SPrev || !SPrev->isRelinquished()));
423 }
424
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000425 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
426 const Stmt *Stmt) {
427 // If the expression is not a call, and the state change is
428 // released -> allocated, it must be the realloc return value
429 // check. If we have to handle more cases here, it might be cleaner just
430 // to track this extra bit in the state itself.
431 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
432 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000433 }
434
435 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
436 const ExplodedNode *PrevN,
437 BugReporterContext &BRC,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000438 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000439
David Blaikied15481c2014-08-29 18:18:43 +0000440 std::unique_ptr<PathDiagnosticPiece>
441 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
442 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000443 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000444 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000445
446 PathDiagnosticLocation L =
447 PathDiagnosticLocation::createEndOfPath(EndPathNode,
448 BRC.getSourceManager());
449 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000450 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
451 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000452 }
453
Anna Zakscba4f292012-03-16 23:24:20 +0000454 private:
455 class StackHintGeneratorForReallocationFailed
456 : public StackHintGeneratorForSymbol {
457 public:
458 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
459 : StackHintGeneratorForSymbol(S, M) {}
460
Craig Topperfb6b25b2014-03-15 04:29:04 +0000461 std::string getMessageForArg(const Expr *ArgE,
462 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000463 // Printed parameters start at 1, not 0.
464 ++ArgIndex;
465
Anna Zakscba4f292012-03-16 23:24:20 +0000466 SmallString<200> buf;
467 llvm::raw_svector_ostream os(buf);
468
Jordan Rosec102b352012-09-22 01:24:42 +0000469 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
470 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000471
472 return os.str();
473 }
474
Craig Topperfb6b25b2014-03-15 04:29:04 +0000475 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000476 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000477 }
478 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000479 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000480};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000481} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000482
Jordan Rose0c153cb2012-11-02 01:54:06 +0000483REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
484REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000485
Anna Zaks67291b92012-11-13 03:18:01 +0000486// A map from the freed symbol to the symbol representing the return value of
487// the free function.
488REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
489
Anna Zaksbb1ef902012-02-11 21:02:35 +0000490namespace {
491class StopTrackingCallback : public SymbolVisitor {
492 ProgramStateRef state;
493public:
494 StopTrackingCallback(ProgramStateRef st) : state(st) {}
495 ProgramStateRef getState() const { return state; }
496
Craig Topperfb6b25b2014-03-15 04:29:04 +0000497 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000498 state = state->remove<RegionState>(sym);
499 return true;
500 }
501};
502} // end anonymous namespace
503
Anna Zaks3d348342012-02-14 21:55:24 +0000504void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000505 if (II_malloc)
506 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000507 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000508 II_malloc = &Ctx.Idents.get("malloc");
509 II_free = &Ctx.Idents.get("free");
510 II_realloc = &Ctx.Idents.get("realloc");
511 II_reallocf = &Ctx.Idents.get("reallocf");
512 II_calloc = &Ctx.Idents.get("calloc");
513 II_valloc = &Ctx.Idents.get("valloc");
514 II_strdup = &Ctx.Idents.get("strdup");
515 II_strndup = &Ctx.Idents.get("strndup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000516 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000517 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
518 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000519}
520
Anna Zaks3d348342012-02-14 21:55:24 +0000521bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000522 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000523 return true;
524
Anna Zaksd79b8402014-10-03 21:48:59 +0000525 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000526 return true;
527
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000528 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
529 return true;
530
Anton Yartsev13df0362013-03-25 01:35:45 +0000531 if (isStandardNewDelete(FD, C))
532 return true;
533
Anna Zaks46d01602012-05-18 01:16:10 +0000534 return false;
535}
536
Anna Zaksd79b8402014-10-03 21:48:59 +0000537bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
538 ASTContext &C,
539 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000540 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000541 if (!FD)
542 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000543
Anna Zaksd79b8402014-10-03 21:48:59 +0000544 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
545 MemKind == MemoryOperationKind::MOK_Free);
546 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
547 MemKind == MemoryOperationKind::MOK_Allocate);
548
Jordan Rose6cd16c52012-07-10 23:13:01 +0000549 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000550 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000551 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000552
Anna Zaksd79b8402014-10-03 21:48:59 +0000553 if (Family == AF_Malloc && CheckFree) {
554 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
555 return true;
556 }
557
558 if (Family == AF_Malloc && CheckAlloc) {
559 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
560 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
561 FunI == II_strndup || FunI == II_kmalloc)
562 return true;
563 }
564
565 if (Family == AF_IfNameIndex && CheckFree) {
566 if (FunI == II_if_freenameindex)
567 return true;
568 }
569
570 if (Family == AF_IfNameIndex && CheckAlloc) {
571 if (FunI == II_if_nameindex)
572 return true;
573 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000574
575 if (Family == AF_Alloca && CheckAlloc) {
Anton Yartsevc38d7952015-03-03 22:58:46 +0000576 if (FunI == II_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000577 return true;
578 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000579 }
Anna Zaks3d348342012-02-14 21:55:24 +0000580
Anna Zaksd79b8402014-10-03 21:48:59 +0000581 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000582 return false;
583
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000584 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000585 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
586 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
587 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
588 if (CheckFree)
589 return true;
590 } else if (OwnKind == OwnershipAttr::Returns) {
591 if (CheckAlloc)
592 return true;
593 }
594 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000595 }
Anna Zaks3d348342012-02-14 21:55:24 +0000596
Anna Zaks3d348342012-02-14 21:55:24 +0000597 return false;
598}
599
Anton Yartsev8b662702013-03-28 16:10:38 +0000600// Tells if the callee is one of the following:
601// 1) A global non-placement new/delete operator function.
602// 2) A global placement operator function with the single placement argument
603// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000604bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
605 ASTContext &C) const {
606 if (!FD)
607 return false;
608
609 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
610 if (Kind != OO_New && Kind != OO_Array_New &&
611 Kind != OO_Delete && Kind != OO_Array_Delete)
612 return false;
613
Anton Yartsev8b662702013-03-28 16:10:38 +0000614 // Skip all operator new/delete methods.
615 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000616 return false;
617
618 // Return true if tested operator is a standard placement nothrow operator.
619 if (FD->getNumParams() == 2) {
620 QualType T = FD->getParamDecl(1)->getType();
621 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
622 return II->getName().equals("nothrow_t");
623 }
624
625 // Skip placement operators.
626 if (FD->getNumParams() != 1 || FD->isVariadic())
627 return false;
628
629 // One of the standard new/new[]/delete/delete[] non-placement operators.
630 return true;
631}
632
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000633llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
634 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
635 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
636 //
637 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
638 //
639 // One of the possible flags is M_ZERO, which means 'give me back an
640 // allocation which is already zeroed', like calloc.
641
642 // 2-argument kmalloc(), as used in the Linux kernel:
643 //
644 // void *kmalloc(size_t size, gfp_t flags);
645 //
646 // Has the similar flag value __GFP_ZERO.
647
648 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
649 // code could be shared.
650
651 ASTContext &Ctx = C.getASTContext();
652 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
653
654 if (!KernelZeroFlagVal.hasValue()) {
655 if (OS == llvm::Triple::FreeBSD)
656 KernelZeroFlagVal = 0x0100;
657 else if (OS == llvm::Triple::NetBSD)
658 KernelZeroFlagVal = 0x0002;
659 else if (OS == llvm::Triple::OpenBSD)
660 KernelZeroFlagVal = 0x0008;
661 else if (OS == llvm::Triple::Linux)
662 // __GFP_ZERO
663 KernelZeroFlagVal = 0x8000;
664 else
665 // FIXME: We need a more general way of getting the M_ZERO value.
666 // See also: O_CREAT in UnixAPIChecker.cpp.
667
668 // Fall back to normal malloc behavior on platforms where we don't
669 // know M_ZERO.
670 return None;
671 }
672
673 // We treat the last argument as the flags argument, and callers fall-back to
674 // normal malloc on a None return. This works for the FreeBSD kernel malloc
675 // as well as Linux kmalloc.
676 if (CE->getNumArgs() < 2)
677 return None;
678
679 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
680 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
681 if (!V.getAs<NonLoc>()) {
682 // The case where 'V' can be a location can only be due to a bad header,
683 // so in this case bail out.
684 return None;
685 }
686
687 NonLoc Flags = V.castAs<NonLoc>();
688 NonLoc ZeroFlag = C.getSValBuilder()
689 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
690 .castAs<NonLoc>();
691 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
692 Flags, ZeroFlag,
693 FlagsEx->getType());
694 if (MaskedFlagsUC.isUnknownOrUndef())
695 return None;
696 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
697
698 // Check if maskedFlags is non-zero.
699 ProgramStateRef TrueState, FalseState;
700 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
701
702 // If M_ZERO is set, treat this like calloc (initialized).
703 if (TrueState && !FalseState) {
704 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
705 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
706 }
707
708 return None;
709}
710
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000711void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000712 if (C.wasInlined)
713 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000714
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000715 const FunctionDecl *FD = C.getCalleeDecl(CE);
716 if (!FD)
717 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000718
Anna Zaks40a7eb32012-02-22 19:24:52 +0000719 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000720 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000721
722 if (FD->getKind() == Decl::Function) {
723 initIdentifierInfo(C.getASTContext());
724 IdentifierInfo *FunI = FD->getIdentifier();
725
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000726 if (FunI == II_malloc) {
727 if (CE->getNumArgs() < 1)
728 return;
729 if (CE->getNumArgs() < 3) {
730 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
731 } else if (CE->getNumArgs() == 3) {
732 llvm::Optional<ProgramStateRef> MaybeState =
733 performKernelMalloc(CE, C, State);
734 if (MaybeState.hasValue())
735 State = MaybeState.getValue();
736 else
737 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
738 }
739 } else if (FunI == II_kmalloc) {
740 llvm::Optional<ProgramStateRef> MaybeState =
741 performKernelMalloc(CE, C, State);
742 if (MaybeState.hasValue())
743 State = MaybeState.getValue();
744 else
745 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
746 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000747 if (CE->getNumArgs() < 1)
748 return;
749 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
750 } else if (FunI == II_realloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000751 State = ReallocMem(C, CE, false, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000752 } else if (FunI == II_reallocf) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000753 State = ReallocMem(C, CE, true, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000754 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000755 State = CallocMem(C, CE, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000756 } else if (FunI == II_free) {
757 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
758 } else if (FunI == II_strdup) {
759 State = MallocUpdateRefState(C, CE, State);
760 } else if (FunI == II_strndup) {
761 State = MallocUpdateRefState(C, CE, State);
Anton Yartsevc38d7952015-03-03 22:58:46 +0000762 } else if (FunI == II_alloca) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000763 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
764 AF_Alloca);
765 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000766 // Process direct calls to operator new/new[]/delete/delete[] functions
767 // as distinct from new/new[]/delete/delete[] expressions that are
768 // processed by the checkPostStmt callbacks for CXXNewExpr and
769 // CXXDeleteExpr.
770 OverloadedOperatorKind K = FD->getOverloadedOperator();
771 if (K == OO_New)
772 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
773 AF_CXXNew);
774 else if (K == OO_Array_New)
775 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
776 AF_CXXNewArray);
777 else if (K == OO_Delete || K == OO_Array_Delete)
778 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
779 else
780 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000781 } else if (FunI == II_if_nameindex) {
782 // Should we model this differently? We can allocate a fixed number of
783 // elements with zeros in the last one.
784 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
785 AF_IfNameIndex);
786 } else if (FunI == II_if_freenameindex) {
787 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000788 }
789 }
790
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000791 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000792 // Check all the attributes, if there are any.
793 // There can be multiple of these attributes.
794 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000795 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
796 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000797 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000798 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000799 break;
800 case OwnershipAttr::Takes:
801 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000802 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000803 break;
804 }
805 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000806 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000807 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000808}
809
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000810static QualType getDeepPointeeType(QualType T) {
811 QualType Result = T, PointeeType = T->getPointeeType();
812 while (!PointeeType.isNull()) {
813 Result = PointeeType;
814 PointeeType = PointeeType->getPointeeType();
815 }
816 return Result;
817}
818
819static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
820
821 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
822 if (!ConstructE)
823 return false;
824
825 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
826 return false;
827
828 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
829
830 // Iterate over the constructor parameters.
831 for (const auto *CtorParam : CtorD->params()) {
832
833 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
834 if (CtorParamPointeeT.isNull())
835 continue;
836
837 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
838
839 if (CtorParamPointeeT->getAsCXXRecordDecl())
840 return true;
841 }
842
843 return false;
844}
845
Anton Yartsev13df0362013-03-25 01:35:45 +0000846void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
847 CheckerContext &C) const {
848
849 if (NE->getNumPlacementArgs())
850 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
851 E = NE->placement_arg_end(); I != E; ++I)
852 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
853 checkUseAfterFree(Sym, C, *I);
854
Anton Yartsev13df0362013-03-25 01:35:45 +0000855 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
856 return;
857
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000858 ParentMap &PM = C.getLocationContext()->getParentMap();
859 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
860 return;
861
Anton Yartsev13df0362013-03-25 01:35:45 +0000862 ProgramStateRef State = C.getState();
863 // The return value from operator new is bound to a specified initialization
864 // value (if any) and we don't want to loose this value. So we call
865 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
866 // existing binding.
Anton Yartsev05789592013-03-28 17:05:19 +0000867 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
868 : AF_CXXNew);
Anton Yartsev13df0362013-03-25 01:35:45 +0000869 C.addTransition(State);
870}
871
872void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
873 CheckerContext &C) const {
874
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000875 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +0000876 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
877 checkUseAfterFree(Sym, C, DE->getArgument());
878
Anton Yartsev13df0362013-03-25 01:35:45 +0000879 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
880 return;
881
882 ProgramStateRef State = C.getState();
883 bool ReleasedAllocated;
884 State = FreeMemAux(C, DE->getArgument(), DE, State,
885 /*Hold*/false, ReleasedAllocated);
886
887 C.addTransition(State);
888}
889
Jordan Rose613f3c02013-03-09 00:59:10 +0000890static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
891 // If the first selector piece is one of the names below, assume that the
892 // object takes ownership of the memory, promising to eventually deallocate it
893 // with free().
894 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
895 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
896 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
897 if (FirstSlot == "dataWithBytesNoCopy" ||
898 FirstSlot == "initWithBytesNoCopy" ||
899 FirstSlot == "initWithCharactersNoCopy")
900 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000901
902 return false;
903}
904
Jordan Rose613f3c02013-03-09 00:59:10 +0000905static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
906 Selector S = Call.getSelector();
907
908 // FIXME: We should not rely on fully-constrained symbols being folded.
909 for (unsigned i = 1; i < S.getNumArgs(); ++i)
910 if (S.getNameForSlot(i).equals("freeWhenDone"))
911 return !Call.getArgSVal(i).isZeroConstant();
912
913 return None;
914}
915
Anna Zaks67291b92012-11-13 03:18:01 +0000916void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
917 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +0000918 if (C.wasInlined)
919 return;
920
Jordan Rose613f3c02013-03-09 00:59:10 +0000921 if (!isKnownDeallocObjCMethodName(Call))
922 return;
Anna Zaks67291b92012-11-13 03:18:01 +0000923
Jordan Rose613f3c02013-03-09 00:59:10 +0000924 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
925 if (!*FreeWhenDone)
926 return;
927
928 bool ReleasedAllocatedMemory;
929 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
930 Call.getOriginExpr(), C.getState(),
931 /*Hold=*/true, ReleasedAllocatedMemory,
932 /*RetNullOnFailure=*/true);
933
934 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +0000935}
936
Richard Smith852e9ce2013-11-27 01:46:48 +0000937ProgramStateRef
938MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000939 const OwnershipAttr *Att,
940 ProgramStateRef State) const {
941 if (!State)
942 return nullptr;
943
Richard Smith852e9ce2013-11-27 01:46:48 +0000944 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +0000945 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000946
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000947 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000948 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000949 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000950 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000951 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
952}
953
954ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
955 const CallExpr *CE,
956 const Expr *SizeEx, SVal Init,
957 ProgramStateRef State,
958 AllocationFamily Family) {
959 if (!State)
960 return nullptr;
961
962 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
963 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000964}
965
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000966ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000967 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000968 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000969 ProgramStateRef State,
970 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000971 if (!State)
972 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +0000973
Jordan Rosef69e65f2014-09-05 16:33:51 +0000974 // We expect the malloc functions to return a pointer.
975 if (!Loc::isLocType(CE->getType()))
976 return nullptr;
977
Anna Zaks3563fde2012-06-07 03:57:32 +0000978 // Bind the return value to the symbolic value from the heap region.
979 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
980 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +0000981 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +0000982 SValBuilder &svalBuilder = C.getSValBuilder();
983 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000984 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
985 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +0000986 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000987
Jordy Rose674bd552010-07-04 00:00:41 +0000988 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +0000989 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000990
Jordy Rose674bd552010-07-04 00:00:41 +0000991 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +0000992 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +0000993 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +0000994 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +0000995 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +0000996 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000997 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000998 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +0000999 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001000 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001001 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001002
Anton Yartsev05789592013-03-28 17:05:19 +00001003 State = State->assume(extentMatchesSize, true);
1004 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001005 }
Ted Kremenek90af9092010-12-02 07:49:45 +00001006
Anton Yartsev05789592013-03-28 17:05:19 +00001007 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001008}
1009
1010ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001011 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001012 ProgramStateRef State,
1013 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001014 if (!State)
1015 return nullptr;
1016
Anna Zaks40a7eb32012-02-22 19:24:52 +00001017 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001018 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001019
1020 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001021 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001022 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001023
Ted Kremenek90af9092010-12-02 07:49:45 +00001024 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001025 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001026
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001027 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001028 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001029}
1030
Anna Zaks40a7eb32012-02-22 19:24:52 +00001031ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1032 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001033 const OwnershipAttr *Att,
1034 ProgramStateRef State) const {
1035 if (!State)
1036 return nullptr;
1037
Richard Smith852e9ce2013-11-27 01:46:48 +00001038 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001039 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001040
Anna Zaksfe6eb672012-08-24 02:28:20 +00001041 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001042
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001043 for (const auto &Arg : Att->args()) {
1044 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001045 Att->getOwnKind() == OwnershipAttr::Holds,
1046 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001047 if (StateI)
1048 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001049 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001050 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001051}
1052
Ted Kremenek49b1e382012-01-26 21:29:00 +00001053ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001054 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001055 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001056 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001057 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001058 bool &ReleasedAllocated,
1059 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001060 if (!State)
1061 return nullptr;
1062
Anna Zaksb508d292012-04-10 23:41:11 +00001063 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001064 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001065
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001066 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001067 ReleasedAllocated, ReturnsNullOnFailure);
1068}
1069
Anna Zaksa14c1d02012-11-13 19:47:40 +00001070/// Checks if the previous call to free on the given symbol failed - if free
1071/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001072static bool didPreviousFreeFail(ProgramStateRef State,
1073 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001074 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001075 if (Ret) {
1076 assert(*Ret && "We should not store the null return symbol");
1077 ConstraintManager &CMgr = State->getConstraintManager();
1078 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001079 RetStatusSymbol = *Ret;
1080 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001081 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001082 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001083}
1084
Anton Yartsev05789592013-03-28 17:05:19 +00001085AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001086 const Stmt *S) const {
1087 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001088 return AF_None;
1089
Anton Yartseve3377fb2013-04-04 23:46:29 +00001090 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001091 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001092
1093 if (!FD)
1094 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1095
Anton Yartsev05789592013-03-28 17:05:19 +00001096 ASTContext &Ctx = C.getASTContext();
1097
Anna Zaksd79b8402014-10-03 21:48:59 +00001098 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001099 return AF_Malloc;
1100
1101 if (isStandardNewDelete(FD, Ctx)) {
1102 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001103 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001104 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001105 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001106 return AF_CXXNewArray;
1107 }
1108
Anna Zaksd79b8402014-10-03 21:48:59 +00001109 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1110 return AF_IfNameIndex;
1111
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001112 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1113 return AF_Alloca;
1114
Anton Yartsev05789592013-03-28 17:05:19 +00001115 return AF_None;
1116 }
1117
Anton Yartseve3377fb2013-04-04 23:46:29 +00001118 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1119 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1120
1121 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001122 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1123
Anton Yartseve3377fb2013-04-04 23:46:29 +00001124 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001125 return AF_Malloc;
1126
1127 return AF_None;
1128}
1129
1130bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1131 const Expr *E) const {
1132 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1133 // FIXME: This doesn't handle indirect calls.
1134 const FunctionDecl *FD = CE->getDirectCallee();
1135 if (!FD)
1136 return false;
1137
1138 os << *FD;
1139 if (!FD->isOverloadedOperator())
1140 os << "()";
1141 return true;
1142 }
1143
1144 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1145 if (Msg->isInstanceMessage())
1146 os << "-";
1147 else
1148 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001149 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001150 return true;
1151 }
1152
1153 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1154 os << "'"
1155 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1156 << "'";
1157 return true;
1158 }
1159
1160 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1161 os << "'"
1162 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1163 << "'";
1164 return true;
1165 }
1166
1167 return false;
1168}
1169
1170void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1171 const Expr *E) const {
1172 AllocationFamily Family = getAllocationFamily(C, E);
1173
1174 switch(Family) {
1175 case AF_Malloc: os << "malloc()"; return;
1176 case AF_CXXNew: os << "'new'"; return;
1177 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001178 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001179 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001180 case AF_None: llvm_unreachable("not a deallocation expression");
1181 }
1182}
1183
1184void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1185 AllocationFamily Family) const {
1186 switch(Family) {
1187 case AF_Malloc: os << "free()"; return;
1188 case AF_CXXNew: os << "'delete'"; return;
1189 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001190 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001191 case AF_Alloca:
1192 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001193 }
1194}
1195
Anna Zaks0d6989b2012-06-22 02:04:31 +00001196ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1197 const Expr *ArgExpr,
1198 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001199 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001200 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001201 bool &ReleasedAllocated,
1202 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001203
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001204 if (!State)
1205 return nullptr;
1206
Anna Zaks67291b92012-11-13 03:18:01 +00001207 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001208 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001209 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001210 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001211
1212 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001213 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001214 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001215
Anna Zaksad01ef52012-02-14 00:26:13 +00001216 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001217 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001218 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001219 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001220 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001221
Jordy Rose3597b212010-06-07 19:32:37 +00001222 // Unknown values could easily be okay
1223 // Undefined values are handled elsewhere
1224 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001225 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001226
Jordy Rose3597b212010-06-07 19:32:37 +00001227 const MemRegion *R = ArgVal.getAsRegion();
1228
1229 // Nonlocs can't be freed, of course.
1230 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1231 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001232 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001233 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001234 }
1235
1236 R = R->StripCasts();
1237
1238 // Blocks might show up as heap data, but should not be free()d
1239 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001240 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001241 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001242 }
1243
1244 const MemSpaceRegion *MS = R->getMemorySpace();
1245
Anton Yartsevc38d7952015-03-03 22:58:46 +00001246 // Parameters, locals, statics, globals, and memory returned by
1247 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001248 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1249 // FIXME: at the time this code was written, malloc() regions were
1250 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1251 // This means that there isn't actually anything from HeapSpaceRegion
1252 // that should be freed, even though we allow it here.
1253 // Of course, free() can work on memory allocated outside the current
1254 // function, so UnknownSpaceRegion is always a possibility.
1255 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001256
1257 if (isa<AllocaRegion>(R))
1258 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1259 else
1260 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1261
Craig Topper0dbb7832014-05-27 02:45:47 +00001262 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001263 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001264
1265 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001266 // Various cases could lead to non-symbol values here.
1267 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001268 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001269 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001270
Anna Zaksc89ad072013-02-07 23:05:47 +00001271 SymbolRef SymBase = SrBase->getSymbol();
1272 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001273 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001274
Anton Yartseve3377fb2013-04-04 23:46:29 +00001275 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001276
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001277 // Memory returned by alloca() shouldn't be freed.
1278 if (RsBase->getAllocationFamily() == AF_Alloca) {
1279 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1280 return nullptr;
1281 }
1282
Anna Zaks93a21a82013-04-09 00:30:28 +00001283 // Check for double free first.
1284 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001285 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1286 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1287 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001288 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001289
Anna Zaks93a21a82013-04-09 00:30:28 +00001290 // If the pointer is allocated or escaped, but we are now trying to free it,
1291 // check that the call to free is proper.
1292 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1293
1294 // Check if an expected deallocation function matches the real one.
1295 bool DeallocMatchesAlloc =
1296 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1297 if (!DeallocMatchesAlloc) {
1298 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001299 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001300 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001301 }
1302
1303 // Check if the memory location being freed is the actual location
1304 // allocated, or an offset.
1305 RegionOffset Offset = R->getAsOffset();
1306 if (Offset.isValid() &&
1307 !Offset.hasSymbolicOffset() &&
1308 Offset.getOffset() != 0) {
1309 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1310 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1311 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001312 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001313 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001314 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001315 }
1316
Craig Topper0dbb7832014-05-27 02:45:47 +00001317 ReleasedAllocated = (RsBase != nullptr) && RsBase->isAllocated();
Anna Zaksfe6eb672012-08-24 02:28:20 +00001318
Anna Zaksa14c1d02012-11-13 19:47:40 +00001319 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001320 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001321
Anna Zaks67291b92012-11-13 03:18:01 +00001322 // Keep track of the return value. If it is NULL, we will know that free
1323 // failed.
1324 if (ReturnsNullOnFailure) {
1325 SVal RetVal = C.getSVal(ParentExpr);
1326 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1327 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001328 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1329 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001330 }
1331 }
1332
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001333 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1334 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001335 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001336 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001337 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001338 RefState::getRelinquished(Family,
1339 ParentExpr));
1340
1341 return State->set<RegionState>(SymBase,
1342 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001343}
1344
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001345Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001346MallocChecker::getCheckIfTracked(AllocationFamily Family) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001347 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001348 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001349 case AF_Alloca:
1350 case AF_IfNameIndex: {
1351 if (ChecksEnabled[CK_MallocChecker])
1352 return CK_MallocChecker;
1353
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001354 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001355 }
1356 case AF_CXXNew:
1357 case AF_CXXNewArray: {
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001358 if (ChecksEnabled[CK_NewDeleteChecker]) {
1359 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001360 }
1361 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001362 }
1363 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001364 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001365 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001366 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001367 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001368}
1369
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001370Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001371MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartseve5c0c142015-02-18 00:39:06 +00001372 const Stmt *AllocDeallocStmt) const {
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001373 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt));
Anton Yartseve5c0c142015-02-18 00:39:06 +00001374}
1375
1376Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001377MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const {
1378
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001379 const RefState *RS = C.getState()->get<RegionState>(Sym);
1380 assert(RS);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001381 return getCheckIfTracked(RS->getAllocationFamily());
Anton Yartseve3377fb2013-04-04 23:46:29 +00001382}
1383
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001384bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001385 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001386 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001387 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001388 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001389 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001390 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001391 else
1392 return false;
1393
1394 return true;
1395}
1396
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001397bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001398 const MemRegion *MR) {
1399 switch (MR->getKind()) {
1400 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001401 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001402 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001403 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001404 else
1405 os << "the address of a function";
1406 return true;
1407 }
1408 case MemRegion::BlockTextRegionKind:
1409 os << "block text";
1410 return true;
1411 case MemRegion::BlockDataRegionKind:
1412 // FIXME: where the block came from?
1413 os << "a block";
1414 return true;
1415 default: {
1416 const MemSpaceRegion *MS = MR->getMemorySpace();
1417
Anna Zaks8158ef02012-01-04 23:54:01 +00001418 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001419 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1420 const VarDecl *VD;
1421 if (VR)
1422 VD = VR->getDecl();
1423 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001424 VD = nullptr;
1425
Jordy Rose3597b212010-06-07 19:32:37 +00001426 if (VD)
1427 os << "the address of the local variable '" << VD->getName() << "'";
1428 else
1429 os << "the address of a local stack variable";
1430 return true;
1431 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001432
1433 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001434 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1435 const VarDecl *VD;
1436 if (VR)
1437 VD = VR->getDecl();
1438 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001439 VD = nullptr;
1440
Jordy Rose3597b212010-06-07 19:32:37 +00001441 if (VD)
1442 os << "the address of the parameter '" << VD->getName() << "'";
1443 else
1444 os << "the address of a parameter";
1445 return true;
1446 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001447
1448 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001449 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1450 const VarDecl *VD;
1451 if (VR)
1452 VD = VR->getDecl();
1453 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001454 VD = nullptr;
1455
Jordy Rose3597b212010-06-07 19:32:37 +00001456 if (VD) {
1457 if (VD->isStaticLocal())
1458 os << "the address of the static variable '" << VD->getName() << "'";
1459 else
1460 os << "the address of the global variable '" << VD->getName() << "'";
1461 } else
1462 os << "the address of a global variable";
1463 return true;
1464 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001465
1466 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001467 }
1468 }
1469}
1470
Anton Yartsev05789592013-03-28 17:05:19 +00001471void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1472 SourceRange Range,
1473 const Expr *DeallocExpr) const {
1474
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001475 if (!ChecksEnabled[CK_MallocChecker] &&
1476 !ChecksEnabled[CK_NewDeleteChecker])
1477 return;
1478
1479 Optional<MallocChecker::CheckKind> CheckKind =
1480 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001481 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001482 return;
1483
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001484 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001485 if (!BT_BadFree[*CheckKind])
1486 BT_BadFree[*CheckKind].reset(
1487 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1488
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001489 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001490 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001491
Jordy Rose3597b212010-06-07 19:32:37 +00001492 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001493 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1494 MR = ER->getSuperRegion();
1495
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001496 os << "Argument to ";
1497 if (!printAllocDeallocName(os, C, DeallocExpr))
1498 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001499
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001500 os << " is ";
1501 bool Summarized = MR ? SummarizeRegion(os, MR)
1502 : SummarizeValue(os, ArgVal);
1503 if (Summarized)
1504 os << ", which is not memory allocated by ";
1505 else
1506 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001507
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001508 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001509
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001510 BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001511 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001512 R->addRange(Range);
Jordan Rosee10d5a72012-11-02 01:53:40 +00001513 C.emitReport(R);
Jordy Rose3597b212010-06-07 19:32:37 +00001514 }
1515}
1516
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001517void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1518 SourceRange Range) const {
1519
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001520 Optional<MallocChecker::CheckKind> CheckKind;
1521
1522 if (ChecksEnabled[CK_MallocChecker])
1523 CheckKind = CK_MallocChecker;
1524 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1525 CheckKind = CK_MismatchedDeallocatorChecker;
1526 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001527 return;
1528
1529 if (ExplodedNode *N = C.generateSink()) {
1530 if (!BT_FreeAlloca[*CheckKind])
1531 BT_FreeAlloca[*CheckKind].reset(
1532 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1533
1534 BugReport *R = new BugReport(*BT_FreeAlloca[*CheckKind],
1535 "Memory allocated by alloca() should not be deallocated", N);
1536 R->markInteresting(ArgVal.getAsRegion());
1537 R->addRange(Range);
1538 C.emitReport(R);
1539 }
1540}
1541
Anton Yartseve3377fb2013-04-04 23:46:29 +00001542void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1543 SourceRange Range,
1544 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001545 const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001546 SymbolRef Sym,
1547 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001548
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001549 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001550 return;
1551
1552 if (ExplodedNode *N = C.generateSink()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001553 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001554 BT_MismatchedDealloc.reset(
1555 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1556 "Bad deallocator", "Memory Error"));
1557
Anton Yartsev05789592013-03-28 17:05:19 +00001558 SmallString<100> buf;
1559 llvm::raw_svector_ostream os(buf);
1560
1561 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1562 SmallString<20> AllocBuf;
1563 llvm::raw_svector_ostream AllocOs(AllocBuf);
1564 SmallString<20> DeallocBuf;
1565 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1566
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001567 if (OwnershipTransferred) {
1568 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1569 os << DeallocOs.str() << " cannot";
1570 else
1571 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001572
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001573 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001574
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001575 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1576 os << " allocated by " << AllocOs.str();
1577 } else {
1578 os << "Memory";
1579 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1580 os << " allocated by " << AllocOs.str();
1581
1582 os << " should be deallocated by ";
1583 printExpectedDeallocName(os, RS->getAllocationFamily());
1584
1585 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1586 os << ", not " << DeallocOs.str();
1587 }
Anton Yartsev05789592013-03-28 17:05:19 +00001588
Anton Yartseve3377fb2013-04-04 23:46:29 +00001589 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001590 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001591 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001592 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev05789592013-03-28 17:05:19 +00001593 C.emitReport(R);
1594 }
1595}
1596
Anna Zaksc89ad072013-02-07 23:05:47 +00001597void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001598 SourceRange Range, const Expr *DeallocExpr,
1599 const Expr *AllocExpr) const {
1600
Anton Yartsev05789592013-03-28 17:05:19 +00001601
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001602 if (!ChecksEnabled[CK_MallocChecker] &&
1603 !ChecksEnabled[CK_NewDeleteChecker])
1604 return;
1605
1606 Optional<MallocChecker::CheckKind> CheckKind =
1607 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001608 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001609 return;
1610
Anna Zaksc89ad072013-02-07 23:05:47 +00001611 ExplodedNode *N = C.generateSink();
Craig Topper0dbb7832014-05-27 02:45:47 +00001612 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001613 return;
1614
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001615 if (!BT_OffsetFree[*CheckKind])
1616 BT_OffsetFree[*CheckKind].reset(
1617 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001618
1619 SmallString<100> buf;
1620 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001621 SmallString<20> AllocNameBuf;
1622 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001623
1624 const MemRegion *MR = ArgVal.getAsRegion();
1625 assert(MR && "Only MemRegion based symbols can have offset free errors");
1626
1627 RegionOffset Offset = MR->getAsOffset();
1628 assert((Offset.isValid() &&
1629 !Offset.hasSymbolicOffset() &&
1630 Offset.getOffset() != 0) &&
1631 "Only symbols with a valid offset can have offset free errors");
1632
1633 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1634
Anton Yartsev05789592013-03-28 17:05:19 +00001635 os << "Argument to ";
1636 if (!printAllocDeallocName(os, C, DeallocExpr))
1637 os << "deallocator";
1638 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001639 << offsetBytes
1640 << " "
1641 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001642 << " from the start of ";
1643 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1644 os << "memory allocated by " << AllocNameOs.str();
1645 else
1646 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001647
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001648 BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001649 R->markInteresting(MR->getBaseRegion());
1650 R->addRange(Range);
1651 C.emitReport(R);
1652}
1653
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001654void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1655 SymbolRef Sym) const {
1656
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001657 if (!ChecksEnabled[CK_MallocChecker] &&
1658 !ChecksEnabled[CK_NewDeleteChecker])
1659 return;
1660
1661 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001662 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001663 return;
1664
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001665 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001666 if (!BT_UseFree[*CheckKind])
1667 BT_UseFree[*CheckKind].reset(new BugType(
1668 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001669
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001670 BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001671 "Use of memory after it is freed", N);
1672
1673 R->markInteresting(Sym);
1674 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001675 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001676 C.emitReport(R);
1677 }
1678}
1679
1680void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1681 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001682 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001683
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001684 if (!ChecksEnabled[CK_MallocChecker] &&
1685 !ChecksEnabled[CK_NewDeleteChecker])
1686 return;
1687
1688 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001689 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001690 return;
1691
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001692 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001693 if (!BT_DoubleFree[*CheckKind])
1694 BT_DoubleFree[*CheckKind].reset(
1695 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001696
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001697 BugReport *R =
1698 new BugReport(*BT_DoubleFree[*CheckKind],
1699 (Released ? "Attempt to free released memory"
1700 : "Attempt to free non-owned memory"),
1701 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001702 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001703 R->markInteresting(Sym);
1704 if (PrevSym)
1705 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001706 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001707 C.emitReport(R);
1708 }
1709}
1710
Jordan Rose656fdd52014-01-08 18:46:55 +00001711void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1712
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001713 if (!ChecksEnabled[CK_NewDeleteChecker])
1714 return;
1715
1716 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001717 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001718 return;
1719
1720 if (ExplodedNode *N = C.generateSink()) {
1721 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001722 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1723 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001724
1725 BugReport *R = new BugReport(*BT_DoubleDelete,
1726 "Attempt to delete released memory", N);
1727
1728 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001729 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Jordan Rose656fdd52014-01-08 18:46:55 +00001730 C.emitReport(R);
1731 }
1732}
1733
Anna Zaks40a7eb32012-02-22 19:24:52 +00001734ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1735 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001736 bool FreesOnFail,
1737 ProgramStateRef State) const {
1738 if (!State)
1739 return nullptr;
1740
Anna Zaksb508d292012-04-10 23:41:11 +00001741 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001742 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001743
Ted Kremenek90af9092010-12-02 07:49:45 +00001744 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001745 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001746 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001747 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001748 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001749 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001750
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001751 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001752
Ted Kremenek90af9092010-12-02 07:49:45 +00001753 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001754 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001755
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001756 // Get the size argument. If there is no size arg then give up.
1757 const Expr *Arg1 = CE->getArg(1);
1758 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00001759 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001760
1761 // Get the value of the size argument.
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001762 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001763 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001764 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001765 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001766
1767 // Compare the size argument to 0.
1768 DefinedOrUnknownSVal SizeZero =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001769 svalBuilder.evalEQ(State, Arg1Val,
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001770 svalBuilder.makeIntValWithPtrWidth(0, false));
1771
Anna Zaksd56c8792012-02-13 18:05:39 +00001772 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001773 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001774 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001775 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001776 // We only assume exceptional states if they are definitely true; if the
1777 // state is under-constrained, assume regular realloc behavior.
1778 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1779 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1780
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001781 // If the ptr is NULL and the size is not 0, the call is equivalent to
1782 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001783 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001784 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001785 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001786 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001787 }
1788
Anna Zaksd56c8792012-02-13 18:05:39 +00001789 if (PrtIsNull && SizeIsZero)
Craig Topper0dbb7832014-05-27 02:45:47 +00001790 return nullptr;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001791
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001792 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001793 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001794 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001795 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001796 SymbolRef ToPtr = RetVal.getAsSymbol();
1797 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00001798 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00001799
Anna Zaksfe6eb672012-08-24 02:28:20 +00001800 bool ReleasedAllocated = false;
1801
Anna Zaksd56c8792012-02-13 18:05:39 +00001802 // If the size is 0, free the memory.
1803 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001804 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1805 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001806 // The semantics of the return value are:
1807 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001808 // to free() is returned. We just free the input pointer and do not add
1809 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001810 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001811 }
1812
1813 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001814 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001815 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00001816
Anna Zaksd56c8792012-02-13 18:05:39 +00001817 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1818 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001819 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001820 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001821
Anna Zaks75cfbb62012-09-12 22:57:34 +00001822 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1823 if (FreesOnFail)
1824 Kind = RPIsFreeOnFailure;
1825 else if (!ReleasedAllocated)
1826 Kind = RPDoNotTrackAfterFailure;
1827
Anna Zaksfe6eb672012-08-24 02:28:20 +00001828 // Record the info about the reallocated symbol so that we could properly
1829 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001830 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001831 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001832 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001833 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001834 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001835 }
Craig Topper0dbb7832014-05-27 02:45:47 +00001836 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001837}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001838
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001839ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
1840 ProgramStateRef State) {
1841 if (!State)
1842 return nullptr;
1843
Anna Zaksb508d292012-04-10 23:41:11 +00001844 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001845 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001846
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001847 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001848 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001849 SVal count = State->getSVal(CE->getArg(0), LCtx);
1850 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1851 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
Ted Kremenek90af9092010-12-02 07:49:45 +00001852 svalBuilder.getContext().getSizeType());
1853 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001854
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001855 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001856}
1857
Anna Zaksfc2e1532012-03-21 19:45:08 +00001858LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00001859MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1860 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00001861 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00001862 // Walk the ExplodedGraph backwards and find the first node that referred to
1863 // the tracked symbol.
1864 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001865 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00001866
1867 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00001868 ProgramStateRef State = N->getState();
1869 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00001870 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001871
1872 // Find the most recent expression bound to the symbol in the current
1873 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00001874 if (!ReferenceRegion) {
1875 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1876 SVal Val = State->getSVal(MR);
1877 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00001878 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00001879 // Do not show local variables belonging to a function other than
1880 // where the error is reported.
1881 if (!VR ||
1882 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1883 ReferenceRegion = MR;
1884 }
1885 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00001886 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00001887
Anna Zaks486a0ff2015-02-05 01:02:53 +00001888 // Allocation node, is the last node in the current or parent context in
1889 // which the symbol was tracked.
1890 const LocationContext *NContext = N->getLocationContext();
1891 if (NContext == LeakContext ||
1892 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00001893 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001894 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00001895 }
1896
Anna Zaksa043d0c2013-01-08 00:25:29 +00001897 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00001898}
1899
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001900void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1901 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001902
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001903 if (!ChecksEnabled[CK_MallocChecker] &&
1904 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00001905 return;
1906
Anton Yartsev9907fc92015-03-04 23:18:21 +00001907 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001908 assert(RS && "cannot leak an untracked symbol");
1909 AllocationFamily Family = RS->getAllocationFamily();
1910 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
1911 if (!CheckKind.hasValue())
1912 return;
1913
1914 // Special case for new and new[]; these are controlled by a separate checker
1915 // flag so that they can be selectively disabled.
1916 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
1917 if (!ChecksEnabled[CK_NewDeleteLeaksChecker])
1918 return;
1919
Anton Yartsev9907fc92015-03-04 23:18:21 +00001920 if (RS->getAllocationFamily() == AF_Alloca)
1921 return;
1922
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001923 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001924 if (!BT_Leak[*CheckKind]) {
1925 BT_Leak[*CheckKind].reset(
1926 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001927 // Leaks should not be reported if they are post-dominated by a sink:
1928 // (1) Sinks are higher importance bugs.
1929 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1930 // with __noreturn functions such as assert() or exit(). We choose not
1931 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001932 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001933 }
1934
Anna Zaksdf901a42012-02-23 21:38:21 +00001935 // Most bug reports are cached at the location where they occurred.
1936 // With leaks, we want to unique them by the location where they were
1937 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00001938 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00001939 const ExplodedNode *AllocNode = nullptr;
1940 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001941 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Anna Zaksa043d0c2013-01-08 00:25:29 +00001942
1943 ProgramPoint P = AllocNode->getLocation();
Craig Topper0dbb7832014-05-27 02:45:47 +00001944 const Stmt *AllocationStmt = nullptr;
David Blaikie87396b92013-02-21 22:23:56 +00001945 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001946 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00001947 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001948 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00001949 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00001950 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1951 C.getSourceManager(),
1952 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00001953
Anna Zaksfc2e1532012-03-21 19:45:08 +00001954 SmallString<200> buf;
1955 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001956 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00001957 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001958 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00001959 } else {
1960 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00001961 }
1962
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001963 BugReport *R =
1964 new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1965 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00001966 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001967 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Jordan Rosee10d5a72012-11-02 01:53:40 +00001968 C.emitReport(R);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001969}
1970
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00001971void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1972 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00001973{
Zhongxing Xubce831f2010-08-15 08:19:57 +00001974 if (!SymReaper.hasDeadSymbols())
1975 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00001976
Ted Kremenek49b1e382012-01-26 21:29:00 +00001977 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001978 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00001979 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001980
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001981 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00001982 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1983 if (SymReaper.isDead(I->first)) {
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001984 if (I->second.isAllocated())
Anna Zaks78edc2f2012-02-09 06:48:19 +00001985 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00001986 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001987 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00001988
Zhongxing Xuc7460962009-11-13 07:48:11 +00001989 }
1990 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001991
Anna Zaksd56c8792012-02-13 18:05:39 +00001992 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00001993 ReallocPairsTy RP = state->get<ReallocPairs>();
1994 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00001995 if (SymReaper.isDead(I->first) ||
1996 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00001997 state = state->remove<ReallocPairs>(I->first);
1998 }
1999 }
2000
Anna Zaks67291b92012-11-13 03:18:01 +00002001 // Cleanup the FreeReturnValue Map.
2002 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2003 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2004 if (SymReaper.isDead(I->first) ||
2005 SymReaper.isDead(I->second)) {
2006 state = state->remove<FreeReturnValue>(I->first);
2007 }
2008 }
2009
Anna Zaksdf901a42012-02-23 21:38:21 +00002010 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002011 ExplodedNode *N = C.getPredecessor();
2012 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002013 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002014 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper2341c0d2013-07-04 03:08:24 +00002015 for (SmallVectorImpl<SymbolRef>::iterator
2016 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002017 reportLeak(*I, N, C);
Anna Zaks78edc2f2012-02-09 06:48:19 +00002018 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002019 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002020
Anna Zaksdf901a42012-02-23 21:38:21 +00002021 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002022}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002023
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002024void MallocChecker::checkPreCall(const CallEvent &Call,
2025 CheckerContext &C) const {
2026
Jordan Rose656fdd52014-01-08 18:46:55 +00002027 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2028 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2029 if (!Sym || checkDoubleDelete(Sym, C))
2030 return;
2031 }
2032
Anna Zaks46d01602012-05-18 01:16:10 +00002033 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002034 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2035 const FunctionDecl *FD = FC->getDecl();
2036 if (!FD)
2037 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002038
Anna Zaksd79b8402014-10-03 21:48:59 +00002039 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002040 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002041 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2042 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2043 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002044 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002045
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002046 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002047 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002048 return;
2049 }
2050
2051 // Check if the callee of a method is deleted.
2052 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2053 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2054 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2055 return;
2056 }
2057
2058 // Check arguments for being used after free.
2059 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2060 SVal ArgSVal = Call.getArgSVal(I);
2061 if (ArgSVal.getAs<Loc>()) {
2062 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002063 if (!Sym)
2064 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002065 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002066 return;
2067 }
2068 }
2069}
2070
Anna Zaksa1b227b2012-02-08 23:16:56 +00002071void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2072 const Expr *E = S->getRetValue();
2073 if (!E)
2074 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002075
2076 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002077 ProgramStateRef State = C.getState();
2078 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002079 SymbolRef Sym = RetVal.getAsSymbol();
2080 if (!Sym)
2081 // If we are returning a field of the allocated struct or an array element,
2082 // the callee could still free the memory.
2083 // TODO: This logic should be a part of generic symbol escape callback.
2084 if (const MemRegion *MR = RetVal.getAsRegion())
2085 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2086 if (const SymbolicRegion *BMR =
2087 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2088 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002089
Anna Zaks3aa52252012-02-11 21:44:39 +00002090 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002091 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002092 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002093}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002094
Anna Zaks9fe80982012-03-22 00:57:20 +00002095// TODO: Blocks should be either inlined or should call invalidate regions
2096// upon invocation. After that's in place, special casing here will not be
2097// needed.
2098void MallocChecker::checkPostStmt(const BlockExpr *BE,
2099 CheckerContext &C) const {
2100
2101 // Scan the BlockDecRefExprs for any object the retain count checker
2102 // may be tracking.
2103 if (!BE->getBlockDecl()->hasCaptures())
2104 return;
2105
2106 ProgramStateRef state = C.getState();
2107 const BlockDataRegion *R =
2108 cast<BlockDataRegion>(state->getSVal(BE,
2109 C.getLocationContext()).getAsRegion());
2110
2111 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2112 E = R->referenced_vars_end();
2113
2114 if (I == E)
2115 return;
2116
2117 SmallVector<const MemRegion*, 10> Regions;
2118 const LocationContext *LC = C.getLocationContext();
2119 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2120
2121 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002122 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002123 if (VR->getSuperRegion() == R) {
2124 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2125 }
2126 Regions.push_back(VR);
2127 }
2128
2129 state =
2130 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2131 Regions.data() + Regions.size()).getState();
2132 C.addTransition(state);
2133}
2134
Anna Zaks46d01602012-05-18 01:16:10 +00002135bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002136 assert(Sym);
2137 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002138 return (RS && RS->isReleased());
2139}
2140
2141bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2142 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002143
Jordan Rose656fdd52014-01-08 18:46:55 +00002144 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002145 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2146 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002147 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002148
Anna Zaksa1b227b2012-02-08 23:16:56 +00002149 return false;
2150}
2151
Jordan Rose656fdd52014-01-08 18:46:55 +00002152bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2153
2154 if (isReleased(Sym, C)) {
2155 ReportDoubleDelete(C, Sym);
2156 return true;
2157 }
2158 return false;
2159}
2160
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002161// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002162void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2163 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002164 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaksa1b227b2012-02-08 23:16:56 +00002165 if (Sym)
Anna Zaks46d01602012-05-18 01:16:10 +00002166 checkUseAfterFree(Sym, C, S);
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002167}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002168
Anna Zaksbb1ef902012-02-11 21:02:35 +00002169// If a symbolic region is assumed to NULL (or another constant), stop tracking
2170// it - assuming that allocation failed on this path.
2171ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2172 SVal Cond,
2173 bool Assumption) const {
2174 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002175 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002176 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002177 ConstraintManager &CMgr = state->getConstraintManager();
2178 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2179 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002180 state = state->remove<RegionState>(I.getKey());
2181 }
2182
Anna Zaksd56c8792012-02-13 18:05:39 +00002183 // Realloc returns 0 when reallocation fails, which means that we should
2184 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002185 ReallocPairsTy RP = state->get<ReallocPairs>();
2186 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002187 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002188 ConstraintManager &CMgr = state->getConstraintManager();
2189 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002190 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002191 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002192
Anna Zaks75cfbb62012-09-12 22:57:34 +00002193 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2194 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2195 if (RS->isReleased()) {
2196 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002197 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002198 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002199 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2200 state = state->remove<RegionState>(ReallocSym);
2201 else
2202 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002203 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002204 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002205 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002206 }
2207
Anna Zaksbb1ef902012-02-11 21:02:35 +00002208 return state;
2209}
2210
Anna Zaks8ebeb642013-06-08 00:29:29 +00002211bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002212 const CallEvent *Call,
2213 ProgramStateRef State,
2214 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002215 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002216 EscapingSymbol = nullptr;
2217
Jordan Rose2a833ca2014-01-15 17:25:15 +00002218 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002219 // TODO: If we want to be more optimistic here, we'll need to make sure that
2220 // regions escape to C++ containers. They seem to do that even now, but for
2221 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002222 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002223 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002224
Jordan Rose742920c2012-07-02 19:27:35 +00002225 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002226 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002227 // If it's not a framework call, or if it takes a callback, assume it
2228 // can free memory.
2229 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002230 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002231
Jordan Rose613f3c02013-03-09 00:59:10 +00002232 // If it's a method we know about, handle it explicitly post-call.
2233 // This should happen before the "freeWhenDone" check below.
2234 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002235 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002236
Jordan Rose613f3c02013-03-09 00:59:10 +00002237 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2238 // about, we can't be sure that the object will use free() to deallocate the
2239 // memory, so we can't model it explicitly. The best we can do is use it to
2240 // decide whether the pointer escapes.
2241 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002242 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002243
Jordan Rose613f3c02013-03-09 00:59:10 +00002244 // If the first selector piece ends with "NoCopy", and there is no
2245 // "freeWhenDone" parameter set to zero, we know ownership is being
2246 // transferred. Again, though, we can't be sure that the object will use
2247 // free() to deallocate the memory, so we can't model it explicitly.
2248 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002249 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002250 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002251
Anna Zaks42908c72012-06-19 05:10:32 +00002252 // If the first selector starts with addPointer, insertPointer,
2253 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2254 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002255 // that the pointers get freed by following the container itself.
2256 if (FirstSlot.startswith("addPointer") ||
2257 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002258 FirstSlot.startswith("replacePointer") ||
2259 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002260 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002261 }
2262
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002263 // We should escape receiver on call to 'init'. This is especially relevant
2264 // to the receiver, as the corresponding symbol is usually not referenced
2265 // after the call.
2266 if (Msg->getMethodFamily() == OMF_init) {
2267 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2268 return true;
2269 }
Anna Zaks737926b2013-05-31 22:39:13 +00002270
Jordan Rose742920c2012-07-02 19:27:35 +00002271 // Otherwise, assume that the method does not free memory.
2272 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002273 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002274 }
2275
Jordan Rose742920c2012-07-02 19:27:35 +00002276 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002277 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002278 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002279 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002280
Jordan Rose742920c2012-07-02 19:27:35 +00002281 ASTContext &ASTC = State->getStateManager().getContext();
2282
2283 // If it's one of the allocation functions we can reason about, we model
2284 // its behavior explicitly.
2285 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002286 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002287
2288 // If it's not a system call, assume it frees memory.
2289 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002290 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002291
2292 // White list the system functions whose arguments escape.
2293 const IdentifierInfo *II = FD->getIdentifier();
2294 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002295 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002296 StringRef FName = II->getName();
2297
Jordan Rose742920c2012-07-02 19:27:35 +00002298 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose7ab01822012-07-02 19:27:51 +00002299 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002300 if (FName.endswith("NoCopy")) {
2301 // Look for the deallocator argument. We know that the memory ownership
2302 // is not transferred only if the deallocator argument is
2303 // 'kCFAllocatorNull'.
2304 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2305 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2306 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2307 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2308 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002309 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002310 }
2311 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002312 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002313 }
2314
Jordan Rose742920c2012-07-02 19:27:35 +00002315 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002316 // 'closefn' is specified (and if that function does free memory),
2317 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002318 // Currently, we do not inspect the 'closefn' function (PR12101).
2319 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002320 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002321 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002322
2323 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2324 // these leaks might be intentional when setting the buffer for stdio.
2325 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2326 if (FName == "setbuf" || FName =="setbuffer" ||
2327 FName == "setlinebuf" || FName == "setvbuf") {
2328 if (Call->getNumArgs() >= 1) {
2329 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2330 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2331 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2332 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002333 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002334 }
2335 }
2336
2337 // A bunch of other functions which either take ownership of a pointer or
2338 // wrap the result up in a struct or object, meaning it can be freed later.
2339 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2340 // but the Malloc checker cannot differentiate between them. The right way
2341 // of doing this would be to implement a pointer escapes callback.
2342 if (FName == "CGBitmapContextCreate" ||
2343 FName == "CGBitmapContextCreateWithData" ||
2344 FName == "CVPixelBufferCreateWithBytes" ||
2345 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2346 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002347 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002348 }
2349
Jordan Rose7ab01822012-07-02 19:27:51 +00002350 // Handle cases where we know a buffer's /address/ can escape.
2351 // Note that the above checks handle some special cases where we know that
2352 // even though the address escapes, it's still our responsibility to free the
2353 // buffer.
2354 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002355 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002356
2357 // Otherwise, assume that the function does not free memory.
2358 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002359 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002360}
2361
Anna Zaks333481b2013-03-28 23:15:29 +00002362static bool retTrue(const RefState *RS) {
2363 return true;
2364}
2365
2366static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2367 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2368 RS->getAllocationFamily() == AF_CXXNew);
2369}
2370
Anna Zaksdc154152012-12-20 00:38:25 +00002371ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2372 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002373 const CallEvent *Call,
2374 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002375 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2376}
2377
2378ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2379 const InvalidatedSymbols &Escaped,
2380 const CallEvent *Call,
2381 PointerEscapeKind Kind) const {
2382 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2383 &checkIfNewOrNewArrayFamily);
2384}
2385
2386ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2387 const InvalidatedSymbols &Escaped,
2388 const CallEvent *Call,
2389 PointerEscapeKind Kind,
2390 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002391 // If we know that the call does not free memory, or we want to process the
2392 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002393 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002394 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002395 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2396 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002397 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002398 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002399 }
Anna Zaks3d348342012-02-14 21:55:24 +00002400
Anna Zaksdc154152012-12-20 00:38:25 +00002401 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002402 E = Escaped.end();
2403 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002404 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002405
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002406 if (EscapingSymbol && EscapingSymbol != sym)
2407 continue;
2408
Anna Zaks0d6989b2012-06-22 02:04:31 +00002409 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks93a21a82013-04-09 00:30:28 +00002410 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002411 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002412 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2413 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002414 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002415 }
Anna Zaks3d348342012-02-14 21:55:24 +00002416 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002417}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002418
Jordy Rosebf38f202012-03-18 07:43:35 +00002419static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2420 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002421 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2422 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002423
Jordan Rose0c153cb2012-11-02 01:54:06 +00002424 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002425 I != E; ++I) {
2426 SymbolRef sym = I.getKey();
2427 if (!currMap.lookup(sym))
2428 return sym;
2429 }
2430
Craig Topper0dbb7832014-05-27 02:45:47 +00002431 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002432}
2433
Anna Zaks2b5bb972012-02-09 06:25:51 +00002434PathDiagnosticPiece *
2435MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2436 const ExplodedNode *PrevN,
2437 BugReporterContext &BRC,
2438 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002439 ProgramStateRef state = N->getState();
2440 ProgramStateRef statePrev = PrevN->getState();
2441
2442 const RefState *RS = state->get<RegionState>(Sym);
2443 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002444 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002445 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002446
Craig Topper0dbb7832014-05-27 02:45:47 +00002447 const Stmt *S = nullptr;
2448 const char *Msg = nullptr;
2449 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002450
2451 // Retrieve the associated statement.
2452 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002453 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002454 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002455 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002456 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002457 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002458 // If an assumption was made on a branch, it should be caught
2459 // here by looking at the state transition.
2460 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002461 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002462
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002463 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002464 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002465
Jordan Rose681cce92012-07-10 22:07:42 +00002466 // FIXME: We will eventually need to handle non-statement-based events
2467 // (__attribute__((cleanup))).
2468
Anna Zaks2b5bb972012-02-09 06:25:51 +00002469 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002470 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002471 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002472 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002473 StackHint = new StackHintGeneratorForSymbol(Sym,
2474 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002475 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002476 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002477 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002478 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002479 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002480 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002481 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002482 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002483 Mode = ReallocationFailed;
2484 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002485 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002486 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002487
Jordy Rose21ff76e2012-03-24 03:15:09 +00002488 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2489 // Is it possible to fail two reallocs WITHOUT testing in between?
2490 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2491 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002492 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002493 FailedReallocSymbol = sym;
2494 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002495 }
2496
2497 // We are in a special mode if a reallocation failed later in the path.
2498 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002499 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002500
Jordy Rose21ff76e2012-03-24 03:15:09 +00002501 // Is this is the first appearance of the reallocated symbol?
2502 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002503 // We're at the reallocation point.
2504 Msg = "Attempt to reallocate memory";
2505 StackHint = new StackHintGeneratorForSymbol(Sym,
2506 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002507 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002508 Mode = Normal;
2509 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002510 }
2511
Anna Zaks2b5bb972012-02-09 06:25:51 +00002512 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002513 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002514 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002515
2516 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002517 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002518 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002519 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002520}
2521
Anna Zaks263b7e02012-05-02 00:05:20 +00002522void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2523 const char *NL, const char *Sep) const {
2524
2525 RegionStateTy RS = State->get<RegionState>();
2526
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002527 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002528 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002529 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002530 const RefState *RefS = State->get<RegionState>(I.getKey());
2531 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002532 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2533
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002534 I.getKey()->dumpToStream(Out);
2535 Out << " : ";
2536 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002537 if (CheckKind.hasValue())
2538 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002539 Out << NL;
2540 }
2541 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002542}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002543
Anna Zakse4cfcd42013-04-16 00:22:55 +00002544void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2545 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002546 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002547 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2548 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002549 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2550 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2551 mgr.getCurrentCheckName();
Anna Zakse4cfcd42013-04-16 00:22:55 +00002552 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2553 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002554 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002555 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002556}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002557
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002558#define REGISTER_CHECKER(name) \
2559 void ento::register##name(CheckerManager &mgr) { \
2560 registerCStringCheckerBasic(mgr); \
2561 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002562 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2563 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002564 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2565 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2566 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002567
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002568REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002569REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002570REGISTER_CHECKER(MismatchedDeallocatorChecker)