blob: 70e17684bd3172e7c334a48261635b0a984de9d5 [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];
Anna Zakscd37bf42012-02-08 23:16:52 +0000190
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000191 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000192 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000193 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
194 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000195 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000196 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000197 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000198 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000199 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000200 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000201 void checkLocation(SVal l, bool isLoad, const Stmt *S,
202 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000203
204 ProgramStateRef checkPointerEscape(ProgramStateRef State,
205 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000206 const CallEvent *Call,
207 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000208 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
209 const InvalidatedSymbols &Escaped,
210 const CallEvent *Call,
211 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000212
Anna Zaks263b7e02012-05-02 00:05:20 +0000213 void printState(raw_ostream &Out, ProgramStateRef State,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000214 const char *NL, const char *Sep) const override;
Anna Zaks263b7e02012-05-02 00:05:20 +0000215
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000216private:
Ahmed Charlesb8984322014-03-07 20:03:18 +0000217 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
218 mutable std::unique_ptr<BugType> BT_DoubleDelete;
219 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
220 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
221 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000222 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
Ahmed Charlesb8984322014-03-07 20:03:18 +0000223 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
224 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
Anton Yartsevc38d7952015-03-03 22:58:46 +0000225 mutable IdentifierInfo *II_alloca, *II_malloc, *II_free, *II_realloc,
226 *II_calloc, *II_valloc, *II_reallocf, *II_strndup,
227 *II_strdup, *II_kmalloc, *II_if_nameindex,
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000228 *II_if_freenameindex;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000229 mutable Optional<uint64_t> KernelZeroFlagVal;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000230
Anna Zaks3d348342012-02-14 21:55:24 +0000231 void initIdentifierInfo(ASTContext &C) const;
232
Anton Yartsev05789592013-03-28 17:05:19 +0000233 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000234 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000235
236 /// \brief Print names of allocators and deallocators.
237 ///
238 /// \returns true on success.
239 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
240 const Expr *E) const;
241
242 /// \brief Print expected name of an allocator based on the deallocator's
243 /// family derived from the DeallocExpr.
244 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
245 const Expr *DeallocExpr) const;
246 /// \brief Print expected name of a deallocator based on the allocator's
247 /// family.
248 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
249
Jordan Rose613f3c02013-03-09 00:59:10 +0000250 ///@{
Anna Zaks3d348342012-02-14 21:55:24 +0000251 /// Check if this is one of the functions which can allocate/reallocate memory
252 /// pointed to by one of its arguments.
253 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaksd79b8402014-10-03 21:48:59 +0000254 bool isCMemFunction(const FunctionDecl *FD,
255 ASTContext &C,
256 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000257 MemoryOperationKind MemKind) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000258 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000259 ///@}
Richard Smith852e9ce2013-11-27 01:46:48 +0000260 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
261 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000262 const OwnershipAttr* Att,
263 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000264 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000265 const Expr *SizeEx, SVal Init,
266 ProgramStateRef State,
267 AllocationFamily Family = AF_Malloc);
Ted Kremenek49b1e382012-01-26 21:29:00 +0000268 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000269 SVal SizeEx, SVal Init,
270 ProgramStateRef State,
271 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000272
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000273 // Check if this malloc() for special flags. At present that means M_ZERO or
274 // __GFP_ZERO (in which case, treat it like calloc).
275 llvm::Optional<ProgramStateRef>
276 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
277 const ProgramStateRef &State) const;
278
Anna Zaks40a7eb32012-02-22 19:24:52 +0000279 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev05789592013-03-28 17:05:19 +0000280 static ProgramStateRef
281 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
282 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000283
284 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000285 const OwnershipAttr* Att,
286 ProgramStateRef State) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000287 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000288 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000289 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000290 bool &ReleasedAllocated,
291 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000292 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
293 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000294 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000295 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000296 bool &ReleasedAllocated,
297 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000298
Anna Zaks40a7eb32012-02-22 19:24:52 +0000299 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000300 bool FreesMemOnFailure,
301 ProgramStateRef State) const;
302 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
303 ProgramStateRef State);
Jordy Rose3597b212010-06-07 19:32:37 +0000304
Anna Zaks46d01602012-05-18 01:16:10 +0000305 ///\brief Check if the memory associated with this symbol was released.
306 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
307
Anton Yartsev13df0362013-03-25 01:35:45 +0000308 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000309
Jordan Rose656fdd52014-01-08 18:46:55 +0000310 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
311
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000312 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000313 /// "interesting" and should be modeled explicitly.
314 ///
Anna Zaks8ebeb642013-06-08 00:29:29 +0000315 /// \param [out] EscapingSymbol A function might not free memory in general,
316 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000317 /// returned and the single escaping symbol is returned through the out
318 /// parameter.
319 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000320 /// We assume that pointers do not escape through calls to system functions
321 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000322 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000323 ProgramStateRef State,
324 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000325
Anna Zaks333481b2013-03-28 23:15:29 +0000326 // Implementation of the checkPointerEscape callabcks.
327 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
328 const InvalidatedSymbols &Escaped,
329 const CallEvent *Call,
330 PointerEscapeKind Kind,
331 bool(*CheckRefState)(const RefState*)) const;
332
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000333 ///@{
334 /// Tells if a given family/call/symbol is tracked by the current checker.
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000335 /// Sets CheckKind to the kind of the checker responsible for this
336 /// family/call/symbol.
Anton Yartsev2487dd62015-03-10 22:24:21 +0000337 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
338 bool IsALeakCheck = false) const;
Anton Yartsev4eb394d2015-03-07 00:31:53 +0000339 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +0000340 const Stmt *AllocDeallocStmt,
341 bool IsALeakCheck = false) const;
342 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
343 bool IsALeakCheck = false) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000344 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000345 static bool SummarizeValue(raw_ostream &os, SVal V);
346 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev05789592013-03-28 17:05:19 +0000347 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
348 const Expr *DeallocExpr) const;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000349 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
350 SourceRange Range) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000351 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000352 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000353 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000354 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
355 const Expr *DeallocExpr,
Craig Topper0dbb7832014-05-27 02:45:47 +0000356 const Expr *AllocExpr = nullptr) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000357 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
358 SymbolRef Sym) const;
359 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000360 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000361
Jordan Rose656fdd52014-01-08 18:46:55 +0000362 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
363
Anna Zaksdf901a42012-02-23 21:38:21 +0000364 /// Find the location of the allocation for Sym on the path leading to the
365 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000366 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
367 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000368
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000369 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
370
Anna Zaks2b5bb972012-02-09 06:25:51 +0000371 /// The bug visitor which allows us to print extra diagnostics along the
372 /// BugReport path. For example, showing the allocation site of the leaked
373 /// region.
Jordy Rosef78877e2012-03-24 02:45:35 +0000374 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000375 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000376 enum NotificationMode {
377 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000378 ReallocationFailed
379 };
380
Anna Zaks2b5bb972012-02-09 06:25:51 +0000381 // The allocated region symbol tracked by the main analysis.
382 SymbolRef Sym;
383
Anna Zaks62cce9e2012-05-10 01:37:40 +0000384 // The mode we are in, i.e. what kind of diagnostics will be emitted.
385 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000386
Anna Zaks62cce9e2012-05-10 01:37:40 +0000387 // A symbol from when the primary region should have been reallocated.
388 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000389
Anna Zaks62cce9e2012-05-10 01:37:40 +0000390 bool IsLeak;
391
392 public:
393 MallocBugVisitor(SymbolRef S, bool isLeak = false)
Craig Topper0dbb7832014-05-27 02:45:47 +0000394 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000395
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000396 ~MallocBugVisitor() override {}
Anna Zaks2b5bb972012-02-09 06:25:51 +0000397
Craig Topperfb6b25b2014-03-15 04:29:04 +0000398 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000399 static int X = 0;
400 ID.AddPointer(&X);
401 ID.AddPointer(Sym);
402 }
403
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000404 inline bool isAllocated(const RefState *S, const RefState *SPrev,
405 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000406 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000407 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000408 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000409 }
410
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000411 inline bool isReleased(const RefState *S, const RefState *SPrev,
412 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000413 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000414 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000415 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
416 }
417
Anna Zaks0d6989b2012-06-22 02:04:31 +0000418 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
419 const Stmt *Stmt) {
420 // Did not track -> relinquished. Other state (allocated) -> relinquished.
421 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
422 isa<ObjCPropertyRefExpr>(Stmt)) &&
423 (S && S->isRelinquished()) &&
424 (!SPrev || !SPrev->isRelinquished()));
425 }
426
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000427 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
428 const Stmt *Stmt) {
429 // If the expression is not a call, and the state change is
430 // released -> allocated, it must be the realloc return value
431 // check. If we have to handle more cases here, it might be cleaner just
432 // to track this extra bit in the state itself.
433 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
434 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000435 }
436
437 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
438 const ExplodedNode *PrevN,
439 BugReporterContext &BRC,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000440 BugReport &BR) override;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000441
David Blaikied15481c2014-08-29 18:18:43 +0000442 std::unique_ptr<PathDiagnosticPiece>
443 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
444 BugReport &BR) override {
Anna Zaks62cce9e2012-05-10 01:37:40 +0000445 if (!IsLeak)
Craig Topper0dbb7832014-05-27 02:45:47 +0000446 return nullptr;
Anna Zaks62cce9e2012-05-10 01:37:40 +0000447
448 PathDiagnosticLocation L =
449 PathDiagnosticLocation::createEndOfPath(EndPathNode,
450 BRC.getSourceManager());
451 // Do not add the statement itself as a range in case of leak.
David Blaikied15481c2014-08-29 18:18:43 +0000452 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
453 false);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000454 }
455
Anna Zakscba4f292012-03-16 23:24:20 +0000456 private:
457 class StackHintGeneratorForReallocationFailed
458 : public StackHintGeneratorForSymbol {
459 public:
460 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
461 : StackHintGeneratorForSymbol(S, M) {}
462
Craig Topperfb6b25b2014-03-15 04:29:04 +0000463 std::string getMessageForArg(const Expr *ArgE,
464 unsigned ArgIndex) override {
Jordan Rosec102b352012-09-22 01:24:42 +0000465 // Printed parameters start at 1, not 0.
466 ++ArgIndex;
467
Anna Zakscba4f292012-03-16 23:24:20 +0000468 SmallString<200> buf;
469 llvm::raw_svector_ostream os(buf);
470
Jordan Rosec102b352012-09-22 01:24:42 +0000471 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
472 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000473
474 return os.str();
475 }
476
Craig Topperfb6b25b2014-03-15 04:29:04 +0000477 std::string getMessageForReturn(const CallExpr *CallExpr) override {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000478 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000479 }
480 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000481 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000482};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000483} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000484
Jordan Rose0c153cb2012-11-02 01:54:06 +0000485REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
486REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000487
Anna Zaks67291b92012-11-13 03:18:01 +0000488// A map from the freed symbol to the symbol representing the return value of
489// the free function.
490REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
491
Anna Zaksbb1ef902012-02-11 21:02:35 +0000492namespace {
493class StopTrackingCallback : public SymbolVisitor {
494 ProgramStateRef state;
495public:
496 StopTrackingCallback(ProgramStateRef st) : state(st) {}
497 ProgramStateRef getState() const { return state; }
498
Craig Topperfb6b25b2014-03-15 04:29:04 +0000499 bool VisitSymbol(SymbolRef sym) override {
Anna Zaksbb1ef902012-02-11 21:02:35 +0000500 state = state->remove<RegionState>(sym);
501 return true;
502 }
503};
504} // end anonymous namespace
505
Anna Zaks3d348342012-02-14 21:55:24 +0000506void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000507 if (II_malloc)
508 return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000509 II_alloca = &Ctx.Idents.get("alloca");
Anna Zaksb3436602012-05-18 22:47:40 +0000510 II_malloc = &Ctx.Idents.get("malloc");
511 II_free = &Ctx.Idents.get("free");
512 II_realloc = &Ctx.Idents.get("realloc");
513 II_reallocf = &Ctx.Idents.get("reallocf");
514 II_calloc = &Ctx.Idents.get("calloc");
515 II_valloc = &Ctx.Idents.get("valloc");
516 II_strdup = &Ctx.Idents.get("strdup");
517 II_strndup = &Ctx.Idents.get("strndup");
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000518 II_kmalloc = &Ctx.Idents.get("kmalloc");
Anna Zaksd79b8402014-10-03 21:48:59 +0000519 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
520 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000521}
522
Anna Zaks3d348342012-02-14 21:55:24 +0000523bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaksd79b8402014-10-03 21:48:59 +0000524 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000525 return true;
526
Anna Zaksd79b8402014-10-03 21:48:59 +0000527 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
Anna Zaks46d01602012-05-18 01:16:10 +0000528 return true;
529
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000530 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
531 return true;
532
Anton Yartsev13df0362013-03-25 01:35:45 +0000533 if (isStandardNewDelete(FD, C))
534 return true;
535
Anna Zaks46d01602012-05-18 01:16:10 +0000536 return false;
537}
538
Anna Zaksd79b8402014-10-03 21:48:59 +0000539bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
540 ASTContext &C,
541 AllocationFamily Family,
Benjamin Kramer719772c2014-10-03 22:20:30 +0000542 MemoryOperationKind MemKind) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000543 if (!FD)
544 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000545
Anna Zaksd79b8402014-10-03 21:48:59 +0000546 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
547 MemKind == MemoryOperationKind::MOK_Free);
548 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
549 MemKind == MemoryOperationKind::MOK_Allocate);
550
Jordan Rose6cd16c52012-07-10 23:13:01 +0000551 if (FD->getKind() == Decl::Function) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000552 const IdentifierInfo *FunI = FD->getIdentifier();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000553 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000554
Anna Zaksd79b8402014-10-03 21:48:59 +0000555 if (Family == AF_Malloc && CheckFree) {
556 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
557 return true;
558 }
559
560 if (Family == AF_Malloc && CheckAlloc) {
561 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
562 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
563 FunI == II_strndup || FunI == II_kmalloc)
564 return true;
565 }
566
567 if (Family == AF_IfNameIndex && CheckFree) {
568 if (FunI == II_if_freenameindex)
569 return true;
570 }
571
572 if (Family == AF_IfNameIndex && CheckAlloc) {
573 if (FunI == II_if_nameindex)
574 return true;
575 }
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000576
577 if (Family == AF_Alloca && CheckAlloc) {
Anton Yartsevc38d7952015-03-03 22:58:46 +0000578 if (FunI == II_alloca)
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000579 return true;
580 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000581 }
Anna Zaks3d348342012-02-14 21:55:24 +0000582
Anna Zaksd79b8402014-10-03 21:48:59 +0000583 if (Family != AF_Malloc)
Anna Zaks46d01602012-05-18 01:16:10 +0000584 return false;
585
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000586 if (IsOptimistic && FD->hasAttrs()) {
Anna Zaksd79b8402014-10-03 21:48:59 +0000587 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
588 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
589 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
590 if (CheckFree)
591 return true;
592 } else if (OwnKind == OwnershipAttr::Returns) {
593 if (CheckAlloc)
594 return true;
595 }
596 }
Jordan Rose6cd16c52012-07-10 23:13:01 +0000597 }
Anna Zaks3d348342012-02-14 21:55:24 +0000598
Anna Zaks3d348342012-02-14 21:55:24 +0000599 return false;
600}
601
Anton Yartsev8b662702013-03-28 16:10:38 +0000602// Tells if the callee is one of the following:
603// 1) A global non-placement new/delete operator function.
604// 2) A global placement operator function with the single placement argument
605// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000606bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
607 ASTContext &C) const {
608 if (!FD)
609 return false;
610
611 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
612 if (Kind != OO_New && Kind != OO_Array_New &&
613 Kind != OO_Delete && Kind != OO_Array_Delete)
614 return false;
615
Anton Yartsev8b662702013-03-28 16:10:38 +0000616 // Skip all operator new/delete methods.
617 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000618 return false;
619
620 // Return true if tested operator is a standard placement nothrow operator.
621 if (FD->getNumParams() == 2) {
622 QualType T = FD->getParamDecl(1)->getType();
623 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
624 return II->getName().equals("nothrow_t");
625 }
626
627 // Skip placement operators.
628 if (FD->getNumParams() != 1 || FD->isVariadic())
629 return false;
630
631 // One of the standard new/new[]/delete/delete[] non-placement operators.
632 return true;
633}
634
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000635llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
636 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
637 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
638 //
639 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
640 //
641 // One of the possible flags is M_ZERO, which means 'give me back an
642 // allocation which is already zeroed', like calloc.
643
644 // 2-argument kmalloc(), as used in the Linux kernel:
645 //
646 // void *kmalloc(size_t size, gfp_t flags);
647 //
648 // Has the similar flag value __GFP_ZERO.
649
650 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
651 // code could be shared.
652
653 ASTContext &Ctx = C.getASTContext();
654 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
655
656 if (!KernelZeroFlagVal.hasValue()) {
657 if (OS == llvm::Triple::FreeBSD)
658 KernelZeroFlagVal = 0x0100;
659 else if (OS == llvm::Triple::NetBSD)
660 KernelZeroFlagVal = 0x0002;
661 else if (OS == llvm::Triple::OpenBSD)
662 KernelZeroFlagVal = 0x0008;
663 else if (OS == llvm::Triple::Linux)
664 // __GFP_ZERO
665 KernelZeroFlagVal = 0x8000;
666 else
667 // FIXME: We need a more general way of getting the M_ZERO value.
668 // See also: O_CREAT in UnixAPIChecker.cpp.
669
670 // Fall back to normal malloc behavior on platforms where we don't
671 // know M_ZERO.
672 return None;
673 }
674
675 // We treat the last argument as the flags argument, and callers fall-back to
676 // normal malloc on a None return. This works for the FreeBSD kernel malloc
677 // as well as Linux kmalloc.
678 if (CE->getNumArgs() < 2)
679 return None;
680
681 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
682 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
683 if (!V.getAs<NonLoc>()) {
684 // The case where 'V' can be a location can only be due to a bad header,
685 // so in this case bail out.
686 return None;
687 }
688
689 NonLoc Flags = V.castAs<NonLoc>();
690 NonLoc ZeroFlag = C.getSValBuilder()
691 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
692 .castAs<NonLoc>();
693 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
694 Flags, ZeroFlag,
695 FlagsEx->getType());
696 if (MaskedFlagsUC.isUnknownOrUndef())
697 return None;
698 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
699
700 // Check if maskedFlags is non-zero.
701 ProgramStateRef TrueState, FalseState;
702 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
703
704 // If M_ZERO is set, treat this like calloc (initialized).
705 if (TrueState && !FalseState) {
706 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
707 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
708 }
709
710 return None;
711}
712
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000713void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000714 if (C.wasInlined)
715 return;
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000716
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000717 const FunctionDecl *FD = C.getCalleeDecl(CE);
718 if (!FD)
719 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000720
Anna Zaks40a7eb32012-02-22 19:24:52 +0000721 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000722 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000723
724 if (FD->getKind() == Decl::Function) {
725 initIdentifierInfo(C.getASTContext());
726 IdentifierInfo *FunI = FD->getIdentifier();
727
Jordan Rose6b33c6f2014-03-26 17:05:46 +0000728 if (FunI == II_malloc) {
729 if (CE->getNumArgs() < 1)
730 return;
731 if (CE->getNumArgs() < 3) {
732 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
733 } else if (CE->getNumArgs() == 3) {
734 llvm::Optional<ProgramStateRef> MaybeState =
735 performKernelMalloc(CE, C, State);
736 if (MaybeState.hasValue())
737 State = MaybeState.getValue();
738 else
739 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
740 }
741 } else if (FunI == II_kmalloc) {
742 llvm::Optional<ProgramStateRef> MaybeState =
743 performKernelMalloc(CE, C, State);
744 if (MaybeState.hasValue())
745 State = MaybeState.getValue();
746 else
747 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
748 } else if (FunI == II_valloc) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000749 if (CE->getNumArgs() < 1)
750 return;
751 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
752 } else if (FunI == II_realloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000753 State = ReallocMem(C, CE, false, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000754 } else if (FunI == II_reallocf) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000755 State = ReallocMem(C, CE, true, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000756 } else if (FunI == II_calloc) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000757 State = CallocMem(C, CE, State);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000758 } else if (FunI == II_free) {
759 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
760 } else if (FunI == II_strdup) {
761 State = MallocUpdateRefState(C, CE, State);
762 } else if (FunI == II_strndup) {
763 State = MallocUpdateRefState(C, CE, State);
Anton Yartsevc38d7952015-03-03 22:58:46 +0000764 } else if (FunI == II_alloca) {
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +0000765 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
766 AF_Alloca);
767 } else if (isStandardNewDelete(FD, C.getASTContext())) {
Anton Yartseve3377fb2013-04-04 23:46:29 +0000768 // Process direct calls to operator new/new[]/delete/delete[] functions
769 // as distinct from new/new[]/delete/delete[] expressions that are
770 // processed by the checkPostStmt callbacks for CXXNewExpr and
771 // CXXDeleteExpr.
772 OverloadedOperatorKind K = FD->getOverloadedOperator();
773 if (K == OO_New)
774 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
775 AF_CXXNew);
776 else if (K == OO_Array_New)
777 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
778 AF_CXXNewArray);
779 else if (K == OO_Delete || K == OO_Array_Delete)
780 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
781 else
782 llvm_unreachable("not a new/delete operator");
Anna Zaksd79b8402014-10-03 21:48:59 +0000783 } else if (FunI == II_if_nameindex) {
784 // Should we model this differently? We can allocate a fixed number of
785 // elements with zeros in the last one.
786 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
787 AF_IfNameIndex);
788 } else if (FunI == II_if_freenameindex) {
789 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose6cd16c52012-07-10 23:13:01 +0000790 }
791 }
792
Gabor Horvathe40c71c2015-03-04 17:59:34 +0000793 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000794 // Check all the attributes, if there are any.
795 // There can be multiple of these attributes.
796 if (FD->hasAttrs())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000797 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
798 switch (I->getOwnKind()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000799 case OwnershipAttr::Returns:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000800 State = MallocMemReturnsAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000801 break;
802 case OwnershipAttr::Takes:
803 case OwnershipAttr::Holds:
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000804 State = FreeMemAttr(C, CE, I, State);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000805 break;
806 }
807 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000808 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000809 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000810}
811
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000812static QualType getDeepPointeeType(QualType T) {
813 QualType Result = T, PointeeType = T->getPointeeType();
814 while (!PointeeType.isNull()) {
815 Result = PointeeType;
816 PointeeType = PointeeType->getPointeeType();
817 }
818 return Result;
819}
820
821static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
822
823 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
824 if (!ConstructE)
825 return false;
826
827 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
828 return false;
829
830 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
831
832 // Iterate over the constructor parameters.
833 for (const auto *CtorParam : CtorD->params()) {
834
835 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
836 if (CtorParamPointeeT.isNull())
837 continue;
838
839 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
840
841 if (CtorParamPointeeT->getAsCXXRecordDecl())
842 return true;
843 }
844
845 return false;
846}
847
Anton Yartsev13df0362013-03-25 01:35:45 +0000848void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
849 CheckerContext &C) const {
850
851 if (NE->getNumPlacementArgs())
852 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
853 E = NE->placement_arg_end(); I != E; ++I)
854 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
855 checkUseAfterFree(Sym, C, *I);
856
Anton Yartsev13df0362013-03-25 01:35:45 +0000857 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
858 return;
859
Anton Yartsev4e4cb6b2014-08-05 18:26:05 +0000860 ParentMap &PM = C.getLocationContext()->getParentMap();
861 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
862 return;
863
Anton Yartsev13df0362013-03-25 01:35:45 +0000864 ProgramStateRef State = C.getState();
865 // The return value from operator new is bound to a specified initialization
866 // value (if any) and we don't want to loose this value. So we call
867 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
868 // existing binding.
Anton Yartsev05789592013-03-28 17:05:19 +0000869 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
870 : AF_CXXNew);
Anton Yartsev13df0362013-03-25 01:35:45 +0000871 C.addTransition(State);
872}
873
874void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
875 CheckerContext &C) const {
876
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000877 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +0000878 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
879 checkUseAfterFree(Sym, C, DE->getArgument());
880
Anton Yartsev13df0362013-03-25 01:35:45 +0000881 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
882 return;
883
884 ProgramStateRef State = C.getState();
885 bool ReleasedAllocated;
886 State = FreeMemAux(C, DE->getArgument(), DE, State,
887 /*Hold*/false, ReleasedAllocated);
888
889 C.addTransition(State);
890}
891
Jordan Rose613f3c02013-03-09 00:59:10 +0000892static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
893 // If the first selector piece is one of the names below, assume that the
894 // object takes ownership of the memory, promising to eventually deallocate it
895 // with free().
896 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
897 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
898 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
899 if (FirstSlot == "dataWithBytesNoCopy" ||
900 FirstSlot == "initWithBytesNoCopy" ||
901 FirstSlot == "initWithCharactersNoCopy")
902 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000903
904 return false;
905}
906
Jordan Rose613f3c02013-03-09 00:59:10 +0000907static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
908 Selector S = Call.getSelector();
909
910 // FIXME: We should not rely on fully-constrained symbols being folded.
911 for (unsigned i = 1; i < S.getNumArgs(); ++i)
912 if (S.getNameForSlot(i).equals("freeWhenDone"))
913 return !Call.getArgSVal(i).isZeroConstant();
914
915 return None;
916}
917
Anna Zaks67291b92012-11-13 03:18:01 +0000918void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
919 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +0000920 if (C.wasInlined)
921 return;
922
Jordan Rose613f3c02013-03-09 00:59:10 +0000923 if (!isKnownDeallocObjCMethodName(Call))
924 return;
Anna Zaks67291b92012-11-13 03:18:01 +0000925
Jordan Rose613f3c02013-03-09 00:59:10 +0000926 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
927 if (!*FreeWhenDone)
928 return;
929
930 bool ReleasedAllocatedMemory;
931 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
932 Call.getOriginExpr(), C.getState(),
933 /*Hold=*/true, ReleasedAllocatedMemory,
934 /*RetNullOnFailure=*/true);
935
936 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +0000937}
938
Richard Smith852e9ce2013-11-27 01:46:48 +0000939ProgramStateRef
940MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000941 const OwnershipAttr *Att,
942 ProgramStateRef State) const {
943 if (!State)
944 return nullptr;
945
Richard Smith852e9ce2013-11-27 01:46:48 +0000946 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +0000947 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000948
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000949 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000950 if (I != E) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000951 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000952 }
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000953 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
954}
955
956ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
957 const CallExpr *CE,
958 const Expr *SizeEx, SVal Init,
959 ProgramStateRef State,
960 AllocationFamily Family) {
961 if (!State)
962 return nullptr;
963
964 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
965 Init, State, Family);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000966}
967
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000968ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000969 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000970 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000971 ProgramStateRef State,
972 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +0000973 if (!State)
974 return nullptr;
Anna Zaks3563fde2012-06-07 03:57:32 +0000975
Jordan Rosef69e65f2014-09-05 16:33:51 +0000976 // We expect the malloc functions to return a pointer.
977 if (!Loc::isLocType(CE->getType()))
978 return nullptr;
979
Anna Zaks3563fde2012-06-07 03:57:32 +0000980 // Bind the return value to the symbolic value from the heap region.
981 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
982 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +0000983 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +0000984 SValBuilder &svalBuilder = C.getSValBuilder();
985 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000986 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
987 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +0000988 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000989
Jordy Rose674bd552010-07-04 00:00:41 +0000990 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +0000991 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000992
Jordy Rose674bd552010-07-04 00:00:41 +0000993 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +0000994 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +0000995 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +0000996 if (!R)
Craig Topper0dbb7832014-05-27 02:45:47 +0000997 return nullptr;
David Blaikie05785d12013-02-20 22:23:23 +0000998 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000999 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001000 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +00001001 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +00001002 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +00001003 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +00001004
Anton Yartsev05789592013-03-28 17:05:19 +00001005 State = State->assume(extentMatchesSize, true);
1006 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +00001007 }
Ted Kremenek90af9092010-12-02 07:49:45 +00001008
Anton Yartsev05789592013-03-28 17:05:19 +00001009 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001010}
1011
1012ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +00001013 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +00001014 ProgramStateRef State,
1015 AllocationFamily Family) {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001016 if (!State)
1017 return nullptr;
1018
Anna Zaks40a7eb32012-02-22 19:24:52 +00001019 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +00001020 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +00001021
1022 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001023 if (!retVal.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001024 return nullptr;
Anna Zaks40a7eb32012-02-22 19:24:52 +00001025
Ted Kremenek90af9092010-12-02 07:49:45 +00001026 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001027 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +00001028
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001029 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +00001030 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001031}
1032
Anna Zaks40a7eb32012-02-22 19:24:52 +00001033ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1034 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001035 const OwnershipAttr *Att,
1036 ProgramStateRef State) const {
1037 if (!State)
1038 return nullptr;
1039
Richard Smith852e9ce2013-11-27 01:46:48 +00001040 if (Att->getModule() != II_malloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001041 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001042
Anna Zaksfe6eb672012-08-24 02:28:20 +00001043 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +00001044
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001045 for (const auto &Arg : Att->args()) {
1046 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001047 Att->getOwnKind() == OwnershipAttr::Holds,
1048 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +00001049 if (StateI)
1050 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001051 }
Anna Zaks8dc53af2012-03-01 22:06:06 +00001052 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001053}
1054
Ted Kremenek49b1e382012-01-26 21:29:00 +00001055ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +00001056 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001057 ProgramStateRef State,
Anna Zaks31886862012-02-10 01:11:00 +00001058 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001059 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001060 bool &ReleasedAllocated,
1061 bool ReturnsNullOnFailure) const {
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001062 if (!State)
1063 return nullptr;
1064
Anna Zaksb508d292012-04-10 23:41:11 +00001065 if (CE->getNumArgs() < (Num + 1))
Craig Topper0dbb7832014-05-27 02:45:47 +00001066 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001067
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001068 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001069 ReleasedAllocated, ReturnsNullOnFailure);
1070}
1071
Anna Zaksa14c1d02012-11-13 19:47:40 +00001072/// Checks if the previous call to free on the given symbol failed - if free
1073/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +00001074static bool didPreviousFreeFail(ProgramStateRef State,
1075 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +00001076 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +00001077 if (Ret) {
1078 assert(*Ret && "We should not store the null return symbol");
1079 ConstraintManager &CMgr = State->getConstraintManager();
1080 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001081 RetStatusSymbol = *Ret;
1082 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +00001083 }
Anna Zaksa14c1d02012-11-13 19:47:40 +00001084 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +00001085}
1086
Anton Yartsev05789592013-03-28 17:05:19 +00001087AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +00001088 const Stmt *S) const {
1089 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +00001090 return AF_None;
1091
Anton Yartseve3377fb2013-04-04 23:46:29 +00001092 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001093 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001094
1095 if (!FD)
1096 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1097
Anton Yartsev05789592013-03-28 17:05:19 +00001098 ASTContext &Ctx = C.getASTContext();
1099
Anna Zaksd79b8402014-10-03 21:48:59 +00001100 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
Anton Yartsev05789592013-03-28 17:05:19 +00001101 return AF_Malloc;
1102
1103 if (isStandardNewDelete(FD, Ctx)) {
1104 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +00001105 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001106 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001107 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +00001108 return AF_CXXNewArray;
1109 }
1110
Anna Zaksd79b8402014-10-03 21:48:59 +00001111 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1112 return AF_IfNameIndex;
1113
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001114 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1115 return AF_Alloca;
1116
Anton Yartsev05789592013-03-28 17:05:19 +00001117 return AF_None;
1118 }
1119
Anton Yartseve3377fb2013-04-04 23:46:29 +00001120 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1121 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1122
1123 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001124 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1125
Anton Yartseve3377fb2013-04-04 23:46:29 +00001126 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +00001127 return AF_Malloc;
1128
1129 return AF_None;
1130}
1131
1132bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1133 const Expr *E) const {
1134 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1135 // FIXME: This doesn't handle indirect calls.
1136 const FunctionDecl *FD = CE->getDirectCallee();
1137 if (!FD)
1138 return false;
1139
1140 os << *FD;
1141 if (!FD->isOverloadedOperator())
1142 os << "()";
1143 return true;
1144 }
1145
1146 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1147 if (Msg->isInstanceMessage())
1148 os << "-";
1149 else
1150 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +00001151 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +00001152 return true;
1153 }
1154
1155 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1156 os << "'"
1157 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1158 << "'";
1159 return true;
1160 }
1161
1162 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1163 os << "'"
1164 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1165 << "'";
1166 return true;
1167 }
1168
1169 return false;
1170}
1171
1172void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1173 const Expr *E) const {
1174 AllocationFamily Family = getAllocationFamily(C, E);
1175
1176 switch(Family) {
1177 case AF_Malloc: os << "malloc()"; return;
1178 case AF_CXXNew: os << "'new'"; return;
1179 case AF_CXXNewArray: os << "'new[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001180 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001181 case AF_Alloca:
Anton Yartsev05789592013-03-28 17:05:19 +00001182 case AF_None: llvm_unreachable("not a deallocation expression");
1183 }
1184}
1185
1186void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1187 AllocationFamily Family) const {
1188 switch(Family) {
1189 case AF_Malloc: os << "free()"; return;
1190 case AF_CXXNew: os << "'delete'"; return;
1191 case AF_CXXNewArray: os << "'delete[]'"; return;
Anna Zaksd79b8402014-10-03 21:48:59 +00001192 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001193 case AF_Alloca:
1194 case AF_None: llvm_unreachable("suspicious argument");
Anton Yartsev05789592013-03-28 17:05:19 +00001195 }
1196}
1197
Anna Zaks0d6989b2012-06-22 02:04:31 +00001198ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1199 const Expr *ArgExpr,
1200 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +00001201 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +00001202 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +00001203 bool &ReleasedAllocated,
1204 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +00001205
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001206 if (!State)
1207 return nullptr;
1208
Anna Zaks67291b92012-11-13 03:18:01 +00001209 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +00001210 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001211 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001212 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +00001213
1214 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +00001215 if (!location.getAs<Loc>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001216 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001217
Anna Zaksad01ef52012-02-14 00:26:13 +00001218 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +00001219 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001220 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001221 if (nullState && !notNullState)
Craig Topper0dbb7832014-05-27 02:45:47 +00001222 return nullptr;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001223
Jordy Rose3597b212010-06-07 19:32:37 +00001224 // Unknown values could easily be okay
1225 // Undefined values are handled elsewhere
1226 if (ArgVal.isUnknownOrUndef())
Craig Topper0dbb7832014-05-27 02:45:47 +00001227 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001228
Jordy Rose3597b212010-06-07 19:32:37 +00001229 const MemRegion *R = ArgVal.getAsRegion();
1230
1231 // Nonlocs can't be freed, of course.
1232 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1233 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +00001234 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001235 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001236 }
1237
1238 R = R->StripCasts();
1239
1240 // Blocks might show up as heap data, but should not be free()d
1241 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001242 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001243 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001244 }
1245
1246 const MemSpaceRegion *MS = R->getMemorySpace();
1247
Anton Yartsevc38d7952015-03-03 22:58:46 +00001248 // Parameters, locals, statics, globals, and memory returned by
1249 // __builtin_alloca() shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001250 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1251 // FIXME: at the time this code was written, malloc() regions were
1252 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1253 // This means that there isn't actually anything from HeapSpaceRegion
1254 // that should be freed, even though we allow it here.
1255 // Of course, free() can work on memory allocated outside the current
1256 // function, so UnknownSpaceRegion is always a possibility.
1257 // False negatives are better than false positives.
Anton Yartsevc38d7952015-03-03 22:58:46 +00001258
1259 if (isa<AllocaRegion>(R))
1260 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1261 else
1262 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1263
Craig Topper0dbb7832014-05-27 02:45:47 +00001264 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001265 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001266
1267 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001268 // Various cases could lead to non-symbol values here.
1269 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001270 if (!SrBase)
Craig Topper0dbb7832014-05-27 02:45:47 +00001271 return nullptr;
Jordy Rose3597b212010-06-07 19:32:37 +00001272
Anna Zaksc89ad072013-02-07 23:05:47 +00001273 SymbolRef SymBase = SrBase->getSymbol();
1274 const RefState *RsBase = State->get<RegionState>(SymBase);
Craig Topper0dbb7832014-05-27 02:45:47 +00001275 SymbolRef PreviousRetStatusSymbol = nullptr;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001276
Anton Yartseve3377fb2013-04-04 23:46:29 +00001277 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001278
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001279 // Memory returned by alloca() shouldn't be freed.
1280 if (RsBase->getAllocationFamily() == AF_Alloca) {
1281 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1282 return nullptr;
1283 }
1284
Anna Zaks93a21a82013-04-09 00:30:28 +00001285 // Check for double free first.
1286 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001287 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1288 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1289 SymBase, PreviousRetStatusSymbol);
Craig Topper0dbb7832014-05-27 02:45:47 +00001290 return nullptr;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001291
Anna Zaks93a21a82013-04-09 00:30:28 +00001292 // If the pointer is allocated or escaped, but we are now trying to free it,
1293 // check that the call to free is proper.
1294 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1295
1296 // Check if an expected deallocation function matches the real one.
1297 bool DeallocMatchesAlloc =
1298 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1299 if (!DeallocMatchesAlloc) {
1300 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001301 ParentExpr, RsBase, SymBase, Hold);
Craig Topper0dbb7832014-05-27 02:45:47 +00001302 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001303 }
1304
1305 // Check if the memory location being freed is the actual location
1306 // allocated, or an offset.
1307 RegionOffset Offset = R->getAsOffset();
1308 if (Offset.isValid() &&
1309 !Offset.hasSymbolicOffset() &&
1310 Offset.getOffset() != 0) {
1311 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1312 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1313 AllocExpr);
Craig Topper0dbb7832014-05-27 02:45:47 +00001314 return nullptr;
Anna Zaks93a21a82013-04-09 00:30:28 +00001315 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001316 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001317 }
1318
Craig Topper0dbb7832014-05-27 02:45:47 +00001319 ReleasedAllocated = (RsBase != nullptr) && RsBase->isAllocated();
Anna Zaksfe6eb672012-08-24 02:28:20 +00001320
Anna Zaksa14c1d02012-11-13 19:47:40 +00001321 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001322 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001323
Anna Zaks67291b92012-11-13 03:18:01 +00001324 // Keep track of the return value. If it is NULL, we will know that free
1325 // failed.
1326 if (ReturnsNullOnFailure) {
1327 SVal RetVal = C.getSVal(ParentExpr);
1328 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1329 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001330 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1331 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001332 }
1333 }
1334
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001335 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1336 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001337 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001338 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001339 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001340 RefState::getRelinquished(Family,
1341 ParentExpr));
1342
1343 return State->set<RegionState>(SymBase,
1344 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001345}
1346
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001347Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001348MallocChecker::getCheckIfTracked(AllocationFamily Family,
1349 bool IsALeakCheck) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001350 switch (Family) {
Anna Zaksd79b8402014-10-03 21:48:59 +00001351 case AF_Malloc:
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001352 case AF_Alloca:
1353 case AF_IfNameIndex: {
1354 if (ChecksEnabled[CK_MallocChecker])
1355 return CK_MallocChecker;
1356
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001357 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001358 }
1359 case AF_CXXNew:
1360 case AF_CXXNewArray: {
Anton Yartsev2487dd62015-03-10 22:24:21 +00001361 if (IsALeakCheck) {
1362 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1363 return CK_NewDeleteLeaksChecker;
1364 }
1365 else {
1366 if (ChecksEnabled[CK_NewDeleteChecker])
1367 return CK_NewDeleteChecker;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001368 }
1369 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001370 }
1371 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001372 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001373 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001374 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001375 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001376}
1377
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001378Optional<MallocChecker::CheckKind>
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001379MallocChecker::getCheckIfTracked(CheckerContext &C,
Anton Yartsev2487dd62015-03-10 22:24:21 +00001380 const Stmt *AllocDeallocStmt,
1381 bool IsALeakCheck) const {
1382 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1383 IsALeakCheck);
Anton Yartseve5c0c142015-02-18 00:39:06 +00001384}
1385
1386Optional<MallocChecker::CheckKind>
Anton Yartsev2487dd62015-03-10 22:24:21 +00001387MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1388 bool IsALeakCheck) const {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001389 const RefState *RS = C.getState()->get<RegionState>(Sym);
1390 assert(RS);
Anton Yartsev2487dd62015-03-10 22:24:21 +00001391 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
Anton Yartseve3377fb2013-04-04 23:46:29 +00001392}
1393
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001394bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001395 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001396 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001397 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001398 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001399 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001400 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001401 else
1402 return false;
1403
1404 return true;
1405}
1406
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001407bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001408 const MemRegion *MR) {
1409 switch (MR->getKind()) {
1410 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001411 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001412 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001413 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001414 else
1415 os << "the address of a function";
1416 return true;
1417 }
1418 case MemRegion::BlockTextRegionKind:
1419 os << "block text";
1420 return true;
1421 case MemRegion::BlockDataRegionKind:
1422 // FIXME: where the block came from?
1423 os << "a block";
1424 return true;
1425 default: {
1426 const MemSpaceRegion *MS = MR->getMemorySpace();
1427
Anna Zaks8158ef02012-01-04 23:54:01 +00001428 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001429 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1430 const VarDecl *VD;
1431 if (VR)
1432 VD = VR->getDecl();
1433 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001434 VD = nullptr;
1435
Jordy Rose3597b212010-06-07 19:32:37 +00001436 if (VD)
1437 os << "the address of the local variable '" << VD->getName() << "'";
1438 else
1439 os << "the address of a local stack variable";
1440 return true;
1441 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001442
1443 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001444 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1445 const VarDecl *VD;
1446 if (VR)
1447 VD = VR->getDecl();
1448 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001449 VD = nullptr;
1450
Jordy Rose3597b212010-06-07 19:32:37 +00001451 if (VD)
1452 os << "the address of the parameter '" << VD->getName() << "'";
1453 else
1454 os << "the address of a parameter";
1455 return true;
1456 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001457
1458 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001459 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1460 const VarDecl *VD;
1461 if (VR)
1462 VD = VR->getDecl();
1463 else
Craig Topper0dbb7832014-05-27 02:45:47 +00001464 VD = nullptr;
1465
Jordy Rose3597b212010-06-07 19:32:37 +00001466 if (VD) {
1467 if (VD->isStaticLocal())
1468 os << "the address of the static variable '" << VD->getName() << "'";
1469 else
1470 os << "the address of the global variable '" << VD->getName() << "'";
1471 } else
1472 os << "the address of a global variable";
1473 return true;
1474 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001475
1476 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001477 }
1478 }
1479}
1480
Anton Yartsev05789592013-03-28 17:05:19 +00001481void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1482 SourceRange Range,
1483 const Expr *DeallocExpr) const {
1484
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001485 if (!ChecksEnabled[CK_MallocChecker] &&
1486 !ChecksEnabled[CK_NewDeleteChecker])
1487 return;
1488
1489 Optional<MallocChecker::CheckKind> CheckKind =
1490 getCheckIfTracked(C, DeallocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001491 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001492 return;
1493
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001494 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001495 if (!BT_BadFree[*CheckKind])
1496 BT_BadFree[*CheckKind].reset(
1497 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1498
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001499 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001500 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001501
Jordy Rose3597b212010-06-07 19:32:37 +00001502 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001503 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1504 MR = ER->getSuperRegion();
1505
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001506 os << "Argument to ";
1507 if (!printAllocDeallocName(os, C, DeallocExpr))
1508 os << "deallocator";
Anton Yartsev05789592013-03-28 17:05:19 +00001509
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001510 os << " is ";
1511 bool Summarized = MR ? SummarizeRegion(os, MR)
1512 : SummarizeValue(os, ArgVal);
1513 if (Summarized)
1514 os << ", which is not memory allocated by ";
1515 else
1516 os << "not memory allocated by ";
Anton Yartsev05789592013-03-28 17:05:19 +00001517
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001518 printExpectedAllocName(os, C, DeallocExpr);
Anton Yartsev05789592013-03-28 17:05:19 +00001519
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001520 BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001521 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001522 R->addRange(Range);
Jordan Rosee10d5a72012-11-02 01:53:40 +00001523 C.emitReport(R);
Jordy Rose3597b212010-06-07 19:32:37 +00001524 }
1525}
1526
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001527void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1528 SourceRange Range) const {
1529
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001530 Optional<MallocChecker::CheckKind> CheckKind;
1531
1532 if (ChecksEnabled[CK_MallocChecker])
1533 CheckKind = CK_MallocChecker;
1534 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1535 CheckKind = CK_MismatchedDeallocatorChecker;
1536 else
Anton Yartsev5b5c7ce2015-02-19 13:36:20 +00001537 return;
1538
1539 if (ExplodedNode *N = C.generateSink()) {
1540 if (!BT_FreeAlloca[*CheckKind])
1541 BT_FreeAlloca[*CheckKind].reset(
1542 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1543
1544 BugReport *R = new BugReport(*BT_FreeAlloca[*CheckKind],
1545 "Memory allocated by alloca() should not be deallocated", N);
1546 R->markInteresting(ArgVal.getAsRegion());
1547 R->addRange(Range);
1548 C.emitReport(R);
1549 }
1550}
1551
Anton Yartseve3377fb2013-04-04 23:46:29 +00001552void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1553 SourceRange Range,
1554 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001555 const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001556 SymbolRef Sym,
1557 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001558
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001559 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001560 return;
1561
1562 if (ExplodedNode *N = C.generateSink()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001563 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001564 BT_MismatchedDealloc.reset(
1565 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1566 "Bad deallocator", "Memory Error"));
1567
Anton Yartsev05789592013-03-28 17:05:19 +00001568 SmallString<100> buf;
1569 llvm::raw_svector_ostream os(buf);
1570
1571 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1572 SmallString<20> AllocBuf;
1573 llvm::raw_svector_ostream AllocOs(AllocBuf);
1574 SmallString<20> DeallocBuf;
1575 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1576
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001577 if (OwnershipTransferred) {
1578 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1579 os << DeallocOs.str() << " cannot";
1580 else
1581 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001582
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001583 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001584
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001585 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1586 os << " allocated by " << AllocOs.str();
1587 } else {
1588 os << "Memory";
1589 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1590 os << " allocated by " << AllocOs.str();
1591
1592 os << " should be deallocated by ";
1593 printExpectedDeallocName(os, RS->getAllocationFamily());
1594
1595 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1596 os << ", not " << DeallocOs.str();
1597 }
Anton Yartsev05789592013-03-28 17:05:19 +00001598
Anton Yartseve3377fb2013-04-04 23:46:29 +00001599 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001600 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001601 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001602 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev05789592013-03-28 17:05:19 +00001603 C.emitReport(R);
1604 }
1605}
1606
Anna Zaksc89ad072013-02-07 23:05:47 +00001607void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001608 SourceRange Range, const Expr *DeallocExpr,
1609 const Expr *AllocExpr) const {
1610
Anton Yartsev05789592013-03-28 17:05:19 +00001611
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001612 if (!ChecksEnabled[CK_MallocChecker] &&
1613 !ChecksEnabled[CK_NewDeleteChecker])
1614 return;
1615
1616 Optional<MallocChecker::CheckKind> CheckKind =
1617 getCheckIfTracked(C, AllocExpr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001618 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001619 return;
1620
Anna Zaksc89ad072013-02-07 23:05:47 +00001621 ExplodedNode *N = C.generateSink();
Craig Topper0dbb7832014-05-27 02:45:47 +00001622 if (!N)
Anna Zaksc89ad072013-02-07 23:05:47 +00001623 return;
1624
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001625 if (!BT_OffsetFree[*CheckKind])
1626 BT_OffsetFree[*CheckKind].reset(
1627 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001628
1629 SmallString<100> buf;
1630 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001631 SmallString<20> AllocNameBuf;
1632 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001633
1634 const MemRegion *MR = ArgVal.getAsRegion();
1635 assert(MR && "Only MemRegion based symbols can have offset free errors");
1636
1637 RegionOffset Offset = MR->getAsOffset();
1638 assert((Offset.isValid() &&
1639 !Offset.hasSymbolicOffset() &&
1640 Offset.getOffset() != 0) &&
1641 "Only symbols with a valid offset can have offset free errors");
1642
1643 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1644
Anton Yartsev05789592013-03-28 17:05:19 +00001645 os << "Argument to ";
1646 if (!printAllocDeallocName(os, C, DeallocExpr))
1647 os << "deallocator";
1648 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001649 << offsetBytes
1650 << " "
1651 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001652 << " from the start of ";
1653 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1654 os << "memory allocated by " << AllocNameOs.str();
1655 else
1656 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001657
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001658 BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001659 R->markInteresting(MR->getBaseRegion());
1660 R->addRange(Range);
1661 C.emitReport(R);
1662}
1663
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001664void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1665 SymbolRef Sym) const {
1666
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001667 if (!ChecksEnabled[CK_MallocChecker] &&
1668 !ChecksEnabled[CK_NewDeleteChecker])
1669 return;
1670
1671 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001672 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001673 return;
1674
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001675 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001676 if (!BT_UseFree[*CheckKind])
1677 BT_UseFree[*CheckKind].reset(new BugType(
1678 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001679
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001680 BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001681 "Use of memory after it is freed", N);
1682
1683 R->markInteresting(Sym);
1684 R->addRange(Range);
David Blaikie91e79022014-09-04 23:54:33 +00001685 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001686 C.emitReport(R);
1687 }
1688}
1689
1690void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1691 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001692 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001693
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001694 if (!ChecksEnabled[CK_MallocChecker] &&
1695 !ChecksEnabled[CK_NewDeleteChecker])
1696 return;
1697
1698 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001699 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001700 return;
1701
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001702 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001703 if (!BT_DoubleFree[*CheckKind])
1704 BT_DoubleFree[*CheckKind].reset(
1705 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001706
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001707 BugReport *R =
1708 new BugReport(*BT_DoubleFree[*CheckKind],
1709 (Released ? "Attempt to free released memory"
1710 : "Attempt to free non-owned memory"),
1711 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001712 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001713 R->markInteresting(Sym);
1714 if (PrevSym)
1715 R->markInteresting(PrevSym);
David Blaikie91e79022014-09-04 23:54:33 +00001716 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001717 C.emitReport(R);
1718 }
1719}
1720
Jordan Rose656fdd52014-01-08 18:46:55 +00001721void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1722
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001723 if (!ChecksEnabled[CK_NewDeleteChecker])
1724 return;
1725
1726 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001727 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001728 return;
1729
1730 if (ExplodedNode *N = C.generateSink()) {
1731 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001732 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1733 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001734
1735 BugReport *R = new BugReport(*BT_DoubleDelete,
1736 "Attempt to delete released memory", N);
1737
1738 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001739 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
Jordan Rose656fdd52014-01-08 18:46:55 +00001740 C.emitReport(R);
1741 }
1742}
1743
Anna Zaks40a7eb32012-02-22 19:24:52 +00001744ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1745 const CallExpr *CE,
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001746 bool FreesOnFail,
1747 ProgramStateRef State) const {
1748 if (!State)
1749 return nullptr;
1750
Anna Zaksb508d292012-04-10 23:41:11 +00001751 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001752 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001753
Ted Kremenek90af9092010-12-02 07:49:45 +00001754 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001755 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001756 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001757 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001758 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001759 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001760
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001761 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001762
Ted Kremenek90af9092010-12-02 07:49:45 +00001763 DefinedOrUnknownSVal PtrEQ =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001764 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001765
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001766 // Get the size argument. If there is no size arg then give up.
1767 const Expr *Arg1 = CE->getArg(1);
1768 if (!Arg1)
Craig Topper0dbb7832014-05-27 02:45:47 +00001769 return nullptr;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001770
1771 // Get the value of the size argument.
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001772 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001773 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Craig Topper0dbb7832014-05-27 02:45:47 +00001774 return nullptr;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001775 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001776
1777 // Compare the size argument to 0.
1778 DefinedOrUnknownSVal SizeZero =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001779 svalBuilder.evalEQ(State, Arg1Val,
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001780 svalBuilder.makeIntValWithPtrWidth(0, false));
1781
Anna Zaksd56c8792012-02-13 18:05:39 +00001782 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001783 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001784 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001785 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001786 // We only assume exceptional states if they are definitely true; if the
1787 // state is under-constrained, assume regular realloc behavior.
1788 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1789 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1790
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001791 // If the ptr is NULL and the size is not 0, the call is equivalent to
1792 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001793 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001794 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001795 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001796 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001797 }
1798
Anna Zaksd56c8792012-02-13 18:05:39 +00001799 if (PrtIsNull && SizeIsZero)
Craig Topper0dbb7832014-05-27 02:45:47 +00001800 return nullptr;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001801
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001802 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001803 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001804 SymbolRef FromPtr = arg0Val.getAsSymbol();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001805 SVal RetVal = State->getSVal(CE, LCtx);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001806 SymbolRef ToPtr = RetVal.getAsSymbol();
1807 if (!FromPtr || !ToPtr)
Craig Topper0dbb7832014-05-27 02:45:47 +00001808 return nullptr;
Anna Zaksd56c8792012-02-13 18:05:39 +00001809
Anna Zaksfe6eb672012-08-24 02:28:20 +00001810 bool ReleasedAllocated = false;
1811
Anna Zaksd56c8792012-02-13 18:05:39 +00001812 // If the size is 0, free the memory.
1813 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001814 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1815 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001816 // The semantics of the return value are:
1817 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001818 // to free() is returned. We just free the input pointer and do not add
1819 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001820 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001821 }
1822
1823 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001824 if (ProgramStateRef stateFree =
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001825 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
Anna Zaksfe6eb672012-08-24 02:28:20 +00001826
Anna Zaksd56c8792012-02-13 18:05:39 +00001827 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1828 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001829 if (!stateRealloc)
Craig Topper0dbb7832014-05-27 02:45:47 +00001830 return nullptr;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001831
Anna Zaks75cfbb62012-09-12 22:57:34 +00001832 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1833 if (FreesOnFail)
1834 Kind = RPIsFreeOnFailure;
1835 else if (!ReleasedAllocated)
1836 Kind = RPDoNotTrackAfterFailure;
1837
Anna Zaksfe6eb672012-08-24 02:28:20 +00001838 // Record the info about the reallocated symbol so that we could properly
1839 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001840 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001841 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001842 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001843 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001844 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001845 }
Craig Topper0dbb7832014-05-27 02:45:47 +00001846 return nullptr;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001847}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001848
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001849ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
1850 ProgramStateRef State) {
1851 if (!State)
1852 return nullptr;
1853
Anna Zaksb508d292012-04-10 23:41:11 +00001854 if (CE->getNumArgs() < 2)
Craig Topper0dbb7832014-05-27 02:45:47 +00001855 return nullptr;
Anna Zaksb508d292012-04-10 23:41:11 +00001856
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001857 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001858 const LocationContext *LCtx = C.getLocationContext();
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001859 SVal count = State->getSVal(CE->getArg(0), LCtx);
1860 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1861 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
Ted Kremenek90af9092010-12-02 07:49:45 +00001862 svalBuilder.getContext().getSizeType());
1863 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001864
Anton Yartsevb3fa86d2015-02-10 20:13:08 +00001865 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001866}
1867
Anna Zaksfc2e1532012-03-21 19:45:08 +00001868LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00001869MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1870 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00001871 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00001872 // Walk the ExplodedGraph backwards and find the first node that referred to
1873 // the tracked symbol.
1874 const ExplodedNode *AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001875 const MemRegion *ReferenceRegion = nullptr;
Anna Zaksdf901a42012-02-23 21:38:21 +00001876
1877 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00001878 ProgramStateRef State = N->getState();
1879 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00001880 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001881
1882 // Find the most recent expression bound to the symbol in the current
1883 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00001884 if (!ReferenceRegion) {
1885 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1886 SVal Val = State->getSVal(MR);
1887 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00001888 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00001889 // Do not show local variables belonging to a function other than
1890 // where the error is reported.
1891 if (!VR ||
1892 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1893 ReferenceRegion = MR;
1894 }
1895 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00001896 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00001897
Anna Zaks486a0ff2015-02-05 01:02:53 +00001898 // Allocation node, is the last node in the current or parent context in
1899 // which the symbol was tracked.
1900 const LocationContext *NContext = N->getLocationContext();
1901 if (NContext == LeakContext ||
1902 NContext->isParentOf(LeakContext))
Anna Zaks43ffba22012-02-27 23:40:55 +00001903 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +00001904 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksdf901a42012-02-23 21:38:21 +00001905 }
1906
Anna Zaksa043d0c2013-01-08 00:25:29 +00001907 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00001908}
1909
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001910void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1911 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001912
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001913 if (!ChecksEnabled[CK_MallocChecker] &&
1914 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev6e499252013-04-05 02:25:02 +00001915 return;
1916
Anton Yartsev9907fc92015-03-04 23:18:21 +00001917 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001918 assert(RS && "cannot leak an untracked symbol");
1919 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev2487dd62015-03-10 22:24:21 +00001920
1921 if (Family == AF_Alloca)
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001922 return;
1923
Anton Yartsev2487dd62015-03-10 22:24:21 +00001924 Optional<MallocChecker::CheckKind>
1925 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00001926
Anton Yartsev2487dd62015-03-10 22:24:21 +00001927 if (!CheckKind.hasValue())
Anton Yartsev9907fc92015-03-04 23:18:21 +00001928 return;
1929
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001930 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001931 if (!BT_Leak[*CheckKind]) {
1932 BT_Leak[*CheckKind].reset(
1933 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001934 // Leaks should not be reported if they are post-dominated by a sink:
1935 // (1) Sinks are higher importance bugs.
1936 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1937 // with __noreturn functions such as assert() or exit(). We choose not
1938 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001939 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001940 }
1941
Anna Zaksdf901a42012-02-23 21:38:21 +00001942 // Most bug reports are cached at the location where they occurred.
1943 // With leaks, we want to unique them by the location where they were
1944 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00001945 PathDiagnosticLocation LocUsedForUniqueing;
Craig Topper0dbb7832014-05-27 02:45:47 +00001946 const ExplodedNode *AllocNode = nullptr;
1947 const MemRegion *Region = nullptr;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001948 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Anna Zaksa043d0c2013-01-08 00:25:29 +00001949
1950 ProgramPoint P = AllocNode->getLocation();
Craig Topper0dbb7832014-05-27 02:45:47 +00001951 const Stmt *AllocationStmt = nullptr;
David Blaikie87396b92013-02-21 22:23:56 +00001952 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001953 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00001954 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001955 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00001956 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00001957 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1958 C.getSourceManager(),
1959 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00001960
Anna Zaksfc2e1532012-03-21 19:45:08 +00001961 SmallString<200> buf;
1962 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001963 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00001964 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001965 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00001966 } else {
1967 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00001968 }
1969
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001970 BugReport *R =
1971 new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1972 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00001973 R->markInteresting(Sym);
David Blaikie91e79022014-09-04 23:54:33 +00001974 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
Jordan Rosee10d5a72012-11-02 01:53:40 +00001975 C.emitReport(R);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001976}
1977
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00001978void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1979 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00001980{
Zhongxing Xubce831f2010-08-15 08:19:57 +00001981 if (!SymReaper.hasDeadSymbols())
1982 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00001983
Ted Kremenek49b1e382012-01-26 21:29:00 +00001984 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001985 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00001986 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001987
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001988 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00001989 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1990 if (SymReaper.isDead(I->first)) {
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001991 if (I->second.isAllocated())
Anna Zaks78edc2f2012-02-09 06:48:19 +00001992 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00001993 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001994 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00001995
Zhongxing Xuc7460962009-11-13 07:48:11 +00001996 }
1997 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001998
Anna Zaksd56c8792012-02-13 18:05:39 +00001999 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002000 ReallocPairsTy RP = state->get<ReallocPairs>();
2001 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00002002 if (SymReaper.isDead(I->first) ||
2003 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00002004 state = state->remove<ReallocPairs>(I->first);
2005 }
2006 }
2007
Anna Zaks67291b92012-11-13 03:18:01 +00002008 // Cleanup the FreeReturnValue Map.
2009 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2010 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2011 if (SymReaper.isDead(I->first) ||
2012 SymReaper.isDead(I->second)) {
2013 state = state->remove<FreeReturnValue>(I->first);
2014 }
2015 }
2016
Anna Zaksdf901a42012-02-23 21:38:21 +00002017 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002018 ExplodedNode *N = C.getPredecessor();
2019 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002020 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002021 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper2341c0d2013-07-04 03:08:24 +00002022 for (SmallVectorImpl<SymbolRef>::iterator
2023 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksd3571e5a2012-02-11 21:02:40 +00002024 reportLeak(*I, N, C);
Anna Zaks78edc2f2012-02-09 06:48:19 +00002025 }
Ted Kremeneke227f492011-07-28 23:07:51 +00002026 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00002027
Anna Zaksdf901a42012-02-23 21:38:21 +00002028 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00002029}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00002030
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002031void MallocChecker::checkPreCall(const CallEvent &Call,
2032 CheckerContext &C) const {
2033
Jordan Rose656fdd52014-01-08 18:46:55 +00002034 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2035 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2036 if (!Sym || checkDoubleDelete(Sym, C))
2037 return;
2038 }
2039
Anna Zaks46d01602012-05-18 01:16:10 +00002040 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002041 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2042 const FunctionDecl *FD = FC->getDecl();
2043 if (!FD)
2044 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00002045
Anna Zaksd79b8402014-10-03 21:48:59 +00002046 ASTContext &Ctx = C.getASTContext();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002047 if (ChecksEnabled[CK_MallocChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002048 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2049 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2050 MemoryOperationKind::MOK_Free)))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002051 return;
Anna Zaks3d348342012-02-14 21:55:24 +00002052
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002053 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anna Zaksd79b8402014-10-03 21:48:59 +00002054 isStandardNewDelete(FD, Ctx))
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002055 return;
2056 }
2057
2058 // Check if the callee of a method is deleted.
2059 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2060 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2061 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2062 return;
2063 }
2064
2065 // Check arguments for being used after free.
2066 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2067 SVal ArgSVal = Call.getArgSVal(I);
2068 if (ArgSVal.getAs<Loc>()) {
2069 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00002070 if (!Sym)
2071 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00002072 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00002073 return;
2074 }
2075 }
2076}
2077
Anna Zaksa1b227b2012-02-08 23:16:56 +00002078void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2079 const Expr *E = S->getRetValue();
2080 if (!E)
2081 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00002082
2083 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00002084 ProgramStateRef State = C.getState();
2085 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00002086 SymbolRef Sym = RetVal.getAsSymbol();
2087 if (!Sym)
2088 // If we are returning a field of the allocated struct or an array element,
2089 // the callee could still free the memory.
2090 // TODO: This logic should be a part of generic symbol escape callback.
2091 if (const MemRegion *MR = RetVal.getAsRegion())
2092 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2093 if (const SymbolicRegion *BMR =
2094 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2095 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00002096
Anna Zaks3aa52252012-02-11 21:44:39 +00002097 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00002098 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00002099 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00002100}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00002101
Anna Zaks9fe80982012-03-22 00:57:20 +00002102// TODO: Blocks should be either inlined or should call invalidate regions
2103// upon invocation. After that's in place, special casing here will not be
2104// needed.
2105void MallocChecker::checkPostStmt(const BlockExpr *BE,
2106 CheckerContext &C) const {
2107
2108 // Scan the BlockDecRefExprs for any object the retain count checker
2109 // may be tracking.
2110 if (!BE->getBlockDecl()->hasCaptures())
2111 return;
2112
2113 ProgramStateRef state = C.getState();
2114 const BlockDataRegion *R =
2115 cast<BlockDataRegion>(state->getSVal(BE,
2116 C.getLocationContext()).getAsRegion());
2117
2118 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2119 E = R->referenced_vars_end();
2120
2121 if (I == E)
2122 return;
2123
2124 SmallVector<const MemRegion*, 10> Regions;
2125 const LocationContext *LC = C.getLocationContext();
2126 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2127
2128 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00002129 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00002130 if (VR->getSuperRegion() == R) {
2131 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2132 }
2133 Regions.push_back(VR);
2134 }
2135
2136 state =
2137 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2138 Regions.data() + Regions.size()).getState();
2139 C.addTransition(state);
2140}
2141
Anna Zaks46d01602012-05-18 01:16:10 +00002142bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002143 assert(Sym);
2144 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00002145 return (RS && RS->isReleased());
2146}
2147
2148bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2149 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00002150
Jordan Rose656fdd52014-01-08 18:46:55 +00002151 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002152 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2153 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00002154 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00002155
Anna Zaksa1b227b2012-02-08 23:16:56 +00002156 return false;
2157}
2158
Jordan Rose656fdd52014-01-08 18:46:55 +00002159bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2160
2161 if (isReleased(Sym, C)) {
2162 ReportDoubleDelete(C, Sym);
2163 return true;
2164 }
2165 return false;
2166}
2167
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002168// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00002169void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2170 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002171 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaksa1b227b2012-02-08 23:16:56 +00002172 if (Sym)
Anna Zaks46d01602012-05-18 01:16:10 +00002173 checkUseAfterFree(Sym, C, S);
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00002174}
Ted Kremenekd21139a2010-07-31 01:52:11 +00002175
Anna Zaksbb1ef902012-02-11 21:02:35 +00002176// If a symbolic region is assumed to NULL (or another constant), stop tracking
2177// it - assuming that allocation failed on this path.
2178ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2179 SVal Cond,
2180 bool Assumption) const {
2181 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00002182 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002183 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002184 ConstraintManager &CMgr = state->getConstraintManager();
2185 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2186 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00002187 state = state->remove<RegionState>(I.getKey());
2188 }
2189
Anna Zaksd56c8792012-02-13 18:05:39 +00002190 // Realloc returns 0 when reallocation fails, which means that we should
2191 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00002192 ReallocPairsTy RP = state->get<ReallocPairs>();
2193 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00002194 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00002195 ConstraintManager &CMgr = state->getConstraintManager();
2196 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00002197 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00002198 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00002199
Anna Zaks75cfbb62012-09-12 22:57:34 +00002200 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2201 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2202 if (RS->isReleased()) {
2203 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00002204 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00002205 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00002206 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2207 state = state->remove<RegionState>(ReallocSym);
2208 else
2209 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00002210 }
Anna Zaksd56c8792012-02-13 18:05:39 +00002211 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00002212 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00002213 }
2214
Anna Zaksbb1ef902012-02-11 21:02:35 +00002215 return state;
2216}
2217
Anna Zaks8ebeb642013-06-08 00:29:29 +00002218bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002219 const CallEvent *Call,
2220 ProgramStateRef State,
2221 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00002222 assert(Call);
Craig Topper0dbb7832014-05-27 02:45:47 +00002223 EscapingSymbol = nullptr;
2224
Jordan Rose2a833ca2014-01-15 17:25:15 +00002225 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00002226 // TODO: If we want to be more optimistic here, we'll need to make sure that
2227 // regions escape to C++ containers. They seem to do that even now, but for
2228 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002229 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002230 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002231
Jordan Rose742920c2012-07-02 19:27:35 +00002232 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00002233 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00002234 // If it's not a framework call, or if it takes a callback, assume it
2235 // can free memory.
2236 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002237 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00002238
Jordan Rose613f3c02013-03-09 00:59:10 +00002239 // If it's a method we know about, handle it explicitly post-call.
2240 // This should happen before the "freeWhenDone" check below.
2241 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002242 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00002243
Jordan Rose613f3c02013-03-09 00:59:10 +00002244 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2245 // about, we can't be sure that the object will use free() to deallocate the
2246 // memory, so we can't model it explicitly. The best we can do is use it to
2247 // decide whether the pointer escapes.
2248 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002249 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002250
Jordan Rose613f3c02013-03-09 00:59:10 +00002251 // If the first selector piece ends with "NoCopy", and there is no
2252 // "freeWhenDone" parameter set to zero, we know ownership is being
2253 // transferred. Again, though, we can't be sure that the object will use
2254 // free() to deallocate the memory, so we can't model it explicitly.
2255 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00002256 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002257 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00002258
Anna Zaks42908c72012-06-19 05:10:32 +00002259 // If the first selector starts with addPointer, insertPointer,
2260 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2261 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00002262 // that the pointers get freed by following the container itself.
2263 if (FirstSlot.startswith("addPointer") ||
2264 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00002265 FirstSlot.startswith("replacePointer") ||
2266 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002267 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00002268 }
2269
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002270 // We should escape receiver on call to 'init'. This is especially relevant
2271 // to the receiver, as the corresponding symbol is usually not referenced
2272 // after the call.
2273 if (Msg->getMethodFamily() == OMF_init) {
2274 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2275 return true;
2276 }
Anna Zaks737926b2013-05-31 22:39:13 +00002277
Jordan Rose742920c2012-07-02 19:27:35 +00002278 // Otherwise, assume that the method does not free memory.
2279 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002280 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002281 }
2282
Jordan Rose742920c2012-07-02 19:27:35 +00002283 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002284 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002285 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002286 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002287
Jordan Rose742920c2012-07-02 19:27:35 +00002288 ASTContext &ASTC = State->getStateManager().getContext();
2289
2290 // If it's one of the allocation functions we can reason about, we model
2291 // its behavior explicitly.
2292 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002293 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002294
2295 // If it's not a system call, assume it frees memory.
2296 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002297 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002298
2299 // White list the system functions whose arguments escape.
2300 const IdentifierInfo *II = FD->getIdentifier();
2301 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002302 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002303 StringRef FName = II->getName();
2304
Jordan Rose742920c2012-07-02 19:27:35 +00002305 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose7ab01822012-07-02 19:27:51 +00002306 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002307 if (FName.endswith("NoCopy")) {
2308 // Look for the deallocator argument. We know that the memory ownership
2309 // is not transferred only if the deallocator argument is
2310 // 'kCFAllocatorNull'.
2311 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2312 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2313 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2314 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2315 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002316 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002317 }
2318 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002319 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002320 }
2321
Jordan Rose742920c2012-07-02 19:27:35 +00002322 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002323 // 'closefn' is specified (and if that function does free memory),
2324 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002325 // Currently, we do not inspect the 'closefn' function (PR12101).
2326 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002327 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002328 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002329
2330 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2331 // these leaks might be intentional when setting the buffer for stdio.
2332 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2333 if (FName == "setbuf" || FName =="setbuffer" ||
2334 FName == "setlinebuf" || FName == "setvbuf") {
2335 if (Call->getNumArgs() >= 1) {
2336 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2337 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2338 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2339 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002340 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002341 }
2342 }
2343
2344 // A bunch of other functions which either take ownership of a pointer or
2345 // wrap the result up in a struct or object, meaning it can be freed later.
2346 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2347 // but the Malloc checker cannot differentiate between them. The right way
2348 // of doing this would be to implement a pointer escapes callback.
2349 if (FName == "CGBitmapContextCreate" ||
2350 FName == "CGBitmapContextCreateWithData" ||
2351 FName == "CVPixelBufferCreateWithBytes" ||
2352 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2353 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002354 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002355 }
2356
Jordan Rose7ab01822012-07-02 19:27:51 +00002357 // Handle cases where we know a buffer's /address/ can escape.
2358 // Note that the above checks handle some special cases where we know that
2359 // even though the address escapes, it's still our responsibility to free the
2360 // buffer.
2361 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002362 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002363
2364 // Otherwise, assume that the function does not free memory.
2365 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002366 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002367}
2368
Anna Zaks333481b2013-03-28 23:15:29 +00002369static bool retTrue(const RefState *RS) {
2370 return true;
2371}
2372
2373static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2374 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2375 RS->getAllocationFamily() == AF_CXXNew);
2376}
2377
Anna Zaksdc154152012-12-20 00:38:25 +00002378ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2379 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002380 const CallEvent *Call,
2381 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002382 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2383}
2384
2385ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2386 const InvalidatedSymbols &Escaped,
2387 const CallEvent *Call,
2388 PointerEscapeKind Kind) const {
2389 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2390 &checkIfNewOrNewArrayFamily);
2391}
2392
2393ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2394 const InvalidatedSymbols &Escaped,
2395 const CallEvent *Call,
2396 PointerEscapeKind Kind,
2397 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002398 // If we know that the call does not free memory, or we want to process the
2399 // call later, keep tracking the top level arguments.
Craig Topper0dbb7832014-05-27 02:45:47 +00002400 SymbolRef EscapingSymbol = nullptr;
Jordan Rose757fbb02013-05-10 17:07:16 +00002401 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002402 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2403 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002404 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002405 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002406 }
Anna Zaks3d348342012-02-14 21:55:24 +00002407
Anna Zaksdc154152012-12-20 00:38:25 +00002408 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002409 E = Escaped.end();
2410 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002411 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002412
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002413 if (EscapingSymbol && EscapingSymbol != sym)
2414 continue;
2415
Anna Zaks0d6989b2012-06-22 02:04:31 +00002416 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks93a21a82013-04-09 00:30:28 +00002417 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002418 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002419 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2420 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002421 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002422 }
Anna Zaks3d348342012-02-14 21:55:24 +00002423 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002424}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002425
Jordy Rosebf38f202012-03-18 07:43:35 +00002426static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2427 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002428 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2429 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002430
Jordan Rose0c153cb2012-11-02 01:54:06 +00002431 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002432 I != E; ++I) {
2433 SymbolRef sym = I.getKey();
2434 if (!currMap.lookup(sym))
2435 return sym;
2436 }
2437
Craig Topper0dbb7832014-05-27 02:45:47 +00002438 return nullptr;
Jordy Rosebf38f202012-03-18 07:43:35 +00002439}
2440
Anna Zaks2b5bb972012-02-09 06:25:51 +00002441PathDiagnosticPiece *
2442MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2443 const ExplodedNode *PrevN,
2444 BugReporterContext &BRC,
2445 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002446 ProgramStateRef state = N->getState();
2447 ProgramStateRef statePrev = PrevN->getState();
2448
2449 const RefState *RS = state->get<RegionState>(Sym);
2450 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002451 if (!RS)
Craig Topper0dbb7832014-05-27 02:45:47 +00002452 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002453
Craig Topper0dbb7832014-05-27 02:45:47 +00002454 const Stmt *S = nullptr;
2455 const char *Msg = nullptr;
2456 StackHintGeneratorForSymbol *StackHint = nullptr;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002457
2458 // Retrieve the associated statement.
2459 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002460 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002461 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002462 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002463 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002464 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002465 // If an assumption was made on a branch, it should be caught
2466 // here by looking at the state transition.
2467 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002468 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002469
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002470 if (!S)
Craig Topper0dbb7832014-05-27 02:45:47 +00002471 return nullptr;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002472
Jordan Rose681cce92012-07-10 22:07:42 +00002473 // FIXME: We will eventually need to handle non-statement-based events
2474 // (__attribute__((cleanup))).
2475
Anna Zaks2b5bb972012-02-09 06:25:51 +00002476 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002477 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002478 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002479 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002480 StackHint = new StackHintGeneratorForSymbol(Sym,
2481 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002482 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002483 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002484 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002485 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002486 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002487 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002488 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002489 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002490 Mode = ReallocationFailed;
2491 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002492 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002493 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002494
Jordy Rose21ff76e2012-03-24 03:15:09 +00002495 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2496 // Is it possible to fail two reallocs WITHOUT testing in between?
2497 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2498 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002499 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002500 FailedReallocSymbol = sym;
2501 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002502 }
2503
2504 // We are in a special mode if a reallocation failed later in the path.
2505 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002506 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002507
Jordy Rose21ff76e2012-03-24 03:15:09 +00002508 // Is this is the first appearance of the reallocated symbol?
2509 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002510 // We're at the reallocation point.
2511 Msg = "Attempt to reallocate memory";
2512 StackHint = new StackHintGeneratorForSymbol(Sym,
2513 "Returned reallocated memory");
Craig Topper0dbb7832014-05-27 02:45:47 +00002514 FailedReallocSymbol = nullptr;
Jordy Rose21ff76e2012-03-24 03:15:09 +00002515 Mode = Normal;
2516 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002517 }
2518
Anna Zaks2b5bb972012-02-09 06:25:51 +00002519 if (!Msg)
Craig Topper0dbb7832014-05-27 02:45:47 +00002520 return nullptr;
Anna Zakscba4f292012-03-16 23:24:20 +00002521 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002522
2523 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002524 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002525 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002526 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002527}
2528
Anna Zaks263b7e02012-05-02 00:05:20 +00002529void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2530 const char *NL, const char *Sep) const {
2531
2532 RegionStateTy RS = State->get<RegionState>();
2533
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002534 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002535 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002536 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002537 const RefState *RefS = State->get<RegionState>(I.getKey());
2538 AllocationFamily Family = RefS->getAllocationFamily();
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002539 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
Anton Yartsev2487dd62015-03-10 22:24:21 +00002540 if (!CheckKind.hasValue())
2541 CheckKind = getCheckIfTracked(Family, true);
Anton Yartsev4eb394d2015-03-07 00:31:53 +00002542
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002543 I.getKey()->dumpToStream(Out);
2544 Out << " : ";
2545 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002546 if (CheckKind.hasValue())
2547 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002548 Out << NL;
2549 }
2550 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002551}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002552
Anna Zakse4cfcd42013-04-16 00:22:55 +00002553void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2554 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002555 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002556 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2557 "Optimistic", false, checker);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002558 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2559 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2560 mgr.getCurrentCheckName();
Anna Zakse4cfcd42013-04-16 00:22:55 +00002561 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2562 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002563 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002564 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002565}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002566
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002567#define REGISTER_CHECKER(name) \
2568 void ento::register##name(CheckerManager &mgr) { \
2569 registerCStringCheckerBasic(mgr); \
2570 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002571 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2572 "Optimistic", false, checker); \
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002573 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2574 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2575 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002576
Gabor Horvathe40c71c2015-03-04 17:59:34 +00002577REGISTER_CHECKER(MallocChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +00002578REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002579REGISTER_CHECKER(MismatchedDeallocatorChecker)