blob: e7edc20ac3e3379992c6153d8a65402f2dc7fa3a [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"
18#include "clang/Basic/SourceManager.h"
19#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000020#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000021#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000027#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000030#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000031#include <climits>
32
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000033using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000034using namespace ento;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000035
36namespace {
37
Anton Yartsev05789592013-03-28 17:05:19 +000038// Used to check correspondence between allocators and deallocators.
39enum AllocationFamily {
40 AF_None,
41 AF_Malloc,
42 AF_CXXNew,
43 AF_CXXNewArray
44};
45
Zhongxing Xu1239de12009-12-11 00:55:44 +000046class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000047 enum Kind { // Reference to allocated memory.
48 Allocated,
49 // Reference to released/freed memory.
50 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000051 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000052 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000053 Relinquished,
54 // We are no longer guaranteed to have observed all manipulations
55 // of this pointer/memory. For example, it could have been
56 // passed as a parameter to an opaque function.
57 Escaped
58 };
Anton Yartsev05789592013-03-28 17:05:19 +000059
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000060 const Stmt *S;
Anton Yartsev05789592013-03-28 17:05:19 +000061 unsigned K : 2; // Kind enum, but stored as a bitfield.
62 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
63 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000064
Anton Yartsev05789592013-03-28 17:05:19 +000065 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000066 : S(s), K(k), Family(family) {
67 assert(family != AF_None);
68 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000069public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000070 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000071 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000072 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000073 bool isEscaped() const { return K == Escaped; }
74 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000075 return (AllocationFamily)Family;
76 }
Anna Zaksd56c8792012-02-13 18:05:39 +000077 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000078
79 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000080 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000081 }
82
Anton Yartsev05789592013-03-28 17:05:19 +000083 static RefState getAllocated(unsigned family, const Stmt *s) {
84 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000085 }
Anton Yartsev05789592013-03-28 17:05:19 +000086 static RefState getReleased(unsigned family, const Stmt *s) {
87 return RefState(Released, s, family);
88 }
89 static RefState getRelinquished(unsigned family, const Stmt *s) {
90 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +000091 }
Anna Zaks93a21a82013-04-09 00:30:28 +000092 static RefState getEscaped(const RefState *RS) {
93 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
94 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000095
96 void Profile(llvm::FoldingSetNodeID &ID) const {
97 ID.AddInteger(K);
98 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +000099 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000100 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000101
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000102 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000103 switch (static_cast<Kind>(K)) {
104#define CASE(ID) case ID: OS << #ID; break;
105 CASE(Allocated)
106 CASE(Released)
107 CASE(Relinquished)
108 CASE(Escaped)
109 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000110 }
111
Alp Tokeref6b0072014-01-04 13:47:14 +0000112 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000113};
114
Anna Zaks75cfbb62012-09-12 22:57:34 +0000115enum ReallocPairKind {
116 RPToBeFreedAfterFailure,
117 // The symbol has been freed when reallocation failed.
118 RPIsFreeOnFailure,
119 // The symbol does not need to be freed after reallocation fails.
120 RPDoNotTrackAfterFailure
121};
122
Anna Zaksfe6eb672012-08-24 02:28:20 +0000123/// \class ReallocPair
124/// \brief Stores information about the symbol being reallocated by a call to
125/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000126struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000127 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000128 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000129 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000130
Anna Zaks75cfbb62012-09-12 22:57:34 +0000131 ReallocPair(SymbolRef S, ReallocPairKind K) :
132 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000133 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000134 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000135 ID.AddPointer(ReallocatedSym);
136 }
137 bool operator==(const ReallocPair &X) const {
138 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000139 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000140 }
141};
142
Anna Zaksa043d0c2013-01-08 00:25:29 +0000143typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000144
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000145class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000146 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000147 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000148 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000149 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000150 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000151 check::PostStmt<CXXNewExpr>,
152 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000153 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000154 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000155 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000156 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000157{
Anna Zaks546c49c2012-02-16 22:26:12 +0000158 mutable OwningPtr<BugType> BT_DoubleFree;
Jordan Rose656fdd52014-01-08 18:46:55 +0000159 mutable OwningPtr<BugType> BT_DoubleDelete;
Anna Zaks546c49c2012-02-16 22:26:12 +0000160 mutable OwningPtr<BugType> BT_Leak;
161 mutable OwningPtr<BugType> BT_UseFree;
162 mutable OwningPtr<BugType> BT_BadFree;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000163 mutable OwningPtr<BugType> BT_MismatchedDealloc;
Anna Zaksc89ad072013-02-07 23:05:47 +0000164 mutable OwningPtr<BugType> BT_OffsetFree;
Anna Zaksd5157482012-02-15 00:11:22 +0000165 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks199e8e52012-02-22 03:14:20 +0000166 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
167
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000168public:
Anna Zaksd5157482012-02-15 00:11:22 +0000169 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks199e8e52012-02-22 03:14:20 +0000170 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000171
172 /// In pessimistic mode, the checker assumes that it does not know which
173 /// functions might free the memory.
174 struct ChecksFilter {
175 DefaultBool CMallocPessimistic;
176 DefaultBool CMallocOptimistic;
Anton Yartsev13df0362013-03-25 01:35:45 +0000177 DefaultBool CNewDeleteChecker;
Jordan Rose26330562013-04-05 17:55:00 +0000178 DefaultBool CNewDeleteLeaksChecker;
Anton Yartsev05789592013-03-28 17:05:19 +0000179 DefaultBool CMismatchedDeallocatorChecker;
Anna Zakscd37bf42012-02-08 23:16:52 +0000180 };
181
182 ChecksFilter Filter;
183
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000184 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000185 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000186 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
187 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000188 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000189 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000190 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000191 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000192 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000193 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000194 void checkLocation(SVal l, bool isLoad, const Stmt *S,
195 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000196
197 ProgramStateRef checkPointerEscape(ProgramStateRef State,
198 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000199 const CallEvent *Call,
200 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000201 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
202 const InvalidatedSymbols &Escaped,
203 const CallEvent *Call,
204 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000205
Anna Zaks263b7e02012-05-02 00:05:20 +0000206 void printState(raw_ostream &Out, ProgramStateRef State,
207 const char *NL, const char *Sep) const;
208
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000209private:
Anna Zaks3d348342012-02-14 21:55:24 +0000210 void initIdentifierInfo(ASTContext &C) const;
211
Anton Yartsev05789592013-03-28 17:05:19 +0000212 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000213 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000214
215 /// \brief Print names of allocators and deallocators.
216 ///
217 /// \returns true on success.
218 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
219 const Expr *E) const;
220
221 /// \brief Print expected name of an allocator based on the deallocator's
222 /// family derived from the DeallocExpr.
223 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
224 const Expr *DeallocExpr) const;
225 /// \brief Print expected name of a deallocator based on the allocator's
226 /// family.
227 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
228
Jordan Rose613f3c02013-03-09 00:59:10 +0000229 ///@{
Anna Zaks3d348342012-02-14 21:55:24 +0000230 /// Check if this is one of the functions which can allocate/reallocate memory
231 /// pointed to by one of its arguments.
232 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks46d01602012-05-18 01:16:10 +0000233 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
234 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000235 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000236 ///@}
Richard Smith852e9ce2013-11-27 01:46:48 +0000237 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
238 const CallExpr *CE,
239 const OwnershipAttr* Att) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000240 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000241 const Expr *SizeEx, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000242 ProgramStateRef State,
243 AllocationFamily Family = AF_Malloc) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000244 return MallocMemAux(C, CE,
Anton Yartsev05789592013-03-28 17:05:19 +0000245 State->getSVal(SizeEx, C.getLocationContext()),
246 Init, State, Family);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000247 }
Anna Zaks40a7eb32012-02-22 19:24:52 +0000248
Ted Kremenek49b1e382012-01-26 21:29:00 +0000249 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000250 SVal SizeEx, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000251 ProgramStateRef State,
252 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000253
Anna Zaks40a7eb32012-02-22 19:24:52 +0000254 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev05789592013-03-28 17:05:19 +0000255 static ProgramStateRef
256 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
257 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000258
259 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
260 const OwnershipAttr* Att) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000261 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000262 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000263 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000264 bool &ReleasedAllocated,
265 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000266 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
267 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000268 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000269 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000270 bool &ReleasedAllocated,
271 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000272
Anna Zaks40a7eb32012-02-22 19:24:52 +0000273 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
274 bool FreesMemOnFailure) const;
275 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose3597b212010-06-07 19:32:37 +0000276
Anna Zaks46d01602012-05-18 01:16:10 +0000277 ///\brief Check if the memory associated with this symbol was released.
278 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
279
Anton Yartsev13df0362013-03-25 01:35:45 +0000280 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000281
Jordan Rose656fdd52014-01-08 18:46:55 +0000282 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
283
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000284 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000285 /// "interesting" and should be modeled explicitly.
286 ///
Anna Zaks8ebeb642013-06-08 00:29:29 +0000287 /// \param [out] EscapingSymbol A function might not free memory in general,
288 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000289 /// returned and the single escaping symbol is returned through the out
290 /// parameter.
291 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000292 /// We assume that pointers do not escape through calls to system functions
293 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000294 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000295 ProgramStateRef State,
296 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000297
Anna Zaks333481b2013-03-28 23:15:29 +0000298 // Implementation of the checkPointerEscape callabcks.
299 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
300 const InvalidatedSymbols &Escaped,
301 const CallEvent *Call,
302 PointerEscapeKind Kind,
303 bool(*CheckRefState)(const RefState*)) const;
304
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000305 ///@{
306 /// Tells if a given family/call/symbol is tracked by the current checker.
307 bool isTrackedByCurrentChecker(AllocationFamily Family) const;
308 bool isTrackedByCurrentChecker(CheckerContext &C,
309 const Stmt *AllocDeallocStmt) const;
310 bool isTrackedByCurrentChecker(CheckerContext &C, SymbolRef Sym) const;
311 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000312 static bool SummarizeValue(raw_ostream &os, SVal V);
313 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev05789592013-03-28 17:05:19 +0000314 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
315 const Expr *DeallocExpr) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000316 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000317 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000318 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000319 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
320 const Expr *DeallocExpr,
321 const Expr *AllocExpr = 0) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000322 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
323 SymbolRef Sym) const;
324 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000325 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000326
Jordan Rose656fdd52014-01-08 18:46:55 +0000327 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
328
Anna Zaksdf901a42012-02-23 21:38:21 +0000329 /// Find the location of the allocation for Sym on the path leading to the
330 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000331 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
332 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000333
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000334 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
335
Anna Zaks2b5bb972012-02-09 06:25:51 +0000336 /// The bug visitor which allows us to print extra diagnostics along the
337 /// BugReport path. For example, showing the allocation site of the leaked
338 /// region.
Jordy Rosef78877e2012-03-24 02:45:35 +0000339 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000340 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000341 enum NotificationMode {
342 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000343 ReallocationFailed
344 };
345
Anna Zaks2b5bb972012-02-09 06:25:51 +0000346 // The allocated region symbol tracked by the main analysis.
347 SymbolRef Sym;
348
Anna Zaks62cce9e2012-05-10 01:37:40 +0000349 // The mode we are in, i.e. what kind of diagnostics will be emitted.
350 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000351
Anna Zaks62cce9e2012-05-10 01:37:40 +0000352 // A symbol from when the primary region should have been reallocated.
353 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000354
Anna Zaks62cce9e2012-05-10 01:37:40 +0000355 bool IsLeak;
356
357 public:
358 MallocBugVisitor(SymbolRef S, bool isLeak = false)
359 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000360
Anna Zaks2b5bb972012-02-09 06:25:51 +0000361 virtual ~MallocBugVisitor() {}
362
363 void Profile(llvm::FoldingSetNodeID &ID) const {
364 static int X = 0;
365 ID.AddPointer(&X);
366 ID.AddPointer(Sym);
367 }
368
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000369 inline bool isAllocated(const RefState *S, const RefState *SPrev,
370 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000371 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000372 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000373 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000374 }
375
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000376 inline bool isReleased(const RefState *S, const RefState *SPrev,
377 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000378 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000379 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000380 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
381 }
382
Anna Zaks0d6989b2012-06-22 02:04:31 +0000383 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
384 const Stmt *Stmt) {
385 // Did not track -> relinquished. Other state (allocated) -> relinquished.
386 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
387 isa<ObjCPropertyRefExpr>(Stmt)) &&
388 (S && S->isRelinquished()) &&
389 (!SPrev || !SPrev->isRelinquished()));
390 }
391
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000392 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
393 const Stmt *Stmt) {
394 // If the expression is not a call, and the state change is
395 // released -> allocated, it must be the realloc return value
396 // check. If we have to handle more cases here, it might be cleaner just
397 // to track this extra bit in the state itself.
398 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
399 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000400 }
401
402 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
403 const ExplodedNode *PrevN,
404 BugReporterContext &BRC,
405 BugReport &BR);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000406
407 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
408 const ExplodedNode *EndPathNode,
409 BugReport &BR) {
410 if (!IsLeak)
411 return 0;
412
413 PathDiagnosticLocation L =
414 PathDiagnosticLocation::createEndOfPath(EndPathNode,
415 BRC.getSourceManager());
416 // Do not add the statement itself as a range in case of leak.
417 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
418 }
419
Anna Zakscba4f292012-03-16 23:24:20 +0000420 private:
421 class StackHintGeneratorForReallocationFailed
422 : public StackHintGeneratorForSymbol {
423 public:
424 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
425 : StackHintGeneratorForSymbol(S, M) {}
426
427 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rosec102b352012-09-22 01:24:42 +0000428 // Printed parameters start at 1, not 0.
429 ++ArgIndex;
430
Anna Zakscba4f292012-03-16 23:24:20 +0000431 SmallString<200> buf;
432 llvm::raw_svector_ostream os(buf);
433
Jordan Rosec102b352012-09-22 01:24:42 +0000434 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
435 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000436
437 return os.str();
438 }
439
440 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000441 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000442 }
443 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000444 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000445};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000446} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000447
Jordan Rose0c153cb2012-11-02 01:54:06 +0000448REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
449REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000450
Anna Zaks67291b92012-11-13 03:18:01 +0000451// A map from the freed symbol to the symbol representing the return value of
452// the free function.
453REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
454
Anna Zaksbb1ef902012-02-11 21:02:35 +0000455namespace {
456class StopTrackingCallback : public SymbolVisitor {
457 ProgramStateRef state;
458public:
459 StopTrackingCallback(ProgramStateRef st) : state(st) {}
460 ProgramStateRef getState() const { return state; }
461
462 bool VisitSymbol(SymbolRef sym) {
463 state = state->remove<RegionState>(sym);
464 return true;
465 }
466};
467} // end anonymous namespace
468
Anna Zaks3d348342012-02-14 21:55:24 +0000469void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000470 if (II_malloc)
471 return;
472 II_malloc = &Ctx.Idents.get("malloc");
473 II_free = &Ctx.Idents.get("free");
474 II_realloc = &Ctx.Idents.get("realloc");
475 II_reallocf = &Ctx.Idents.get("reallocf");
476 II_calloc = &Ctx.Idents.get("calloc");
477 II_valloc = &Ctx.Idents.get("valloc");
478 II_strdup = &Ctx.Idents.get("strdup");
479 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000480}
481
Anna Zaks3d348342012-02-14 21:55:24 +0000482bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks46d01602012-05-18 01:16:10 +0000483 if (isFreeFunction(FD, C))
484 return true;
485
486 if (isAllocationFunction(FD, C))
487 return true;
488
Anton Yartsev13df0362013-03-25 01:35:45 +0000489 if (isStandardNewDelete(FD, C))
490 return true;
491
Anna Zaks46d01602012-05-18 01:16:10 +0000492 return false;
493}
494
495bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
496 ASTContext &C) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000497 if (!FD)
498 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000499
Jordan Rose6cd16c52012-07-10 23:13:01 +0000500 if (FD->getKind() == Decl::Function) {
501 IdentifierInfo *FunI = FD->getIdentifier();
502 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000503
Jordan Rose6cd16c52012-07-10 23:13:01 +0000504 if (FunI == II_malloc || FunI == II_realloc ||
505 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
506 FunI == II_strdup || FunI == II_strndup)
507 return true;
508 }
Anna Zaks3d348342012-02-14 21:55:24 +0000509
Anna Zaks46d01602012-05-18 01:16:10 +0000510 if (Filter.CMallocOptimistic && FD->hasAttrs())
511 for (specific_attr_iterator<OwnershipAttr>
512 i = FD->specific_attr_begin<OwnershipAttr>(),
513 e = FD->specific_attr_end<OwnershipAttr>();
514 i != e; ++i)
515 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
516 return true;
517 return false;
518}
519
520bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
521 if (!FD)
522 return false;
523
Jordan Rose6cd16c52012-07-10 23:13:01 +0000524 if (FD->getKind() == Decl::Function) {
525 IdentifierInfo *FunI = FD->getIdentifier();
526 initIdentifierInfo(C);
Anna Zaks46d01602012-05-18 01:16:10 +0000527
Jordan Rose6cd16c52012-07-10 23:13:01 +0000528 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
529 return true;
530 }
Anna Zaks3d348342012-02-14 21:55:24 +0000531
Anna Zaks46d01602012-05-18 01:16:10 +0000532 if (Filter.CMallocOptimistic && FD->hasAttrs())
533 for (specific_attr_iterator<OwnershipAttr>
534 i = FD->specific_attr_begin<OwnershipAttr>(),
535 e = FD->specific_attr_end<OwnershipAttr>();
536 i != e; ++i)
537 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
538 (*i)->getOwnKind() == OwnershipAttr::Holds)
539 return true;
Anna Zaks3d348342012-02-14 21:55:24 +0000540 return false;
541}
542
Anton Yartsev8b662702013-03-28 16:10:38 +0000543// Tells if the callee is one of the following:
544// 1) A global non-placement new/delete operator function.
545// 2) A global placement operator function with the single placement argument
546// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000547bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
548 ASTContext &C) const {
549 if (!FD)
550 return false;
551
552 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
553 if (Kind != OO_New && Kind != OO_Array_New &&
554 Kind != OO_Delete && Kind != OO_Array_Delete)
555 return false;
556
Anton Yartsev8b662702013-03-28 16:10:38 +0000557 // Skip all operator new/delete methods.
558 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000559 return false;
560
561 // Return true if tested operator is a standard placement nothrow operator.
562 if (FD->getNumParams() == 2) {
563 QualType T = FD->getParamDecl(1)->getType();
564 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
565 return II->getName().equals("nothrow_t");
566 }
567
568 // Skip placement operators.
569 if (FD->getNumParams() != 1 || FD->isVariadic())
570 return false;
571
572 // One of the standard new/new[]/delete/delete[] non-placement operators.
573 return true;
574}
575
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000576void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000577 if (C.wasInlined)
578 return;
579
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000580 const FunctionDecl *FD = C.getCalleeDecl(CE);
581 if (!FD)
582 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000583
Anna Zaks40a7eb32012-02-22 19:24:52 +0000584 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000585 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000586
587 if (FD->getKind() == Decl::Function) {
588 initIdentifierInfo(C.getASTContext());
589 IdentifierInfo *FunI = FD->getIdentifier();
590
Anton Yartseve3377fb2013-04-04 23:46:29 +0000591 if (FunI == II_malloc || FunI == II_valloc) {
592 if (CE->getNumArgs() < 1)
593 return;
594 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
595 } else if (FunI == II_realloc) {
596 State = ReallocMem(C, CE, false);
597 } else if (FunI == II_reallocf) {
598 State = ReallocMem(C, CE, true);
599 } else if (FunI == II_calloc) {
600 State = CallocMem(C, CE);
601 } else if (FunI == II_free) {
602 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
603 } else if (FunI == II_strdup) {
604 State = MallocUpdateRefState(C, CE, State);
605 } else if (FunI == II_strndup) {
606 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev13df0362013-03-25 01:35:45 +0000607 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000608 else if (isStandardNewDelete(FD, C.getASTContext())) {
609 // Process direct calls to operator new/new[]/delete/delete[] functions
610 // as distinct from new/new[]/delete/delete[] expressions that are
611 // processed by the checkPostStmt callbacks for CXXNewExpr and
612 // CXXDeleteExpr.
613 OverloadedOperatorKind K = FD->getOverloadedOperator();
614 if (K == OO_New)
615 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
616 AF_CXXNew);
617 else if (K == OO_Array_New)
618 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
619 AF_CXXNewArray);
620 else if (K == OO_Delete || K == OO_Array_Delete)
621 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
622 else
623 llvm_unreachable("not a new/delete operator");
Jordan Rose6cd16c52012-07-10 23:13:01 +0000624 }
625 }
626
Anton Yartsev05789592013-03-28 17:05:19 +0000627 if (Filter.CMallocOptimistic || Filter.CMismatchedDeallocatorChecker) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000628 // Check all the attributes, if there are any.
629 // There can be multiple of these attributes.
630 if (FD->hasAttrs())
631 for (specific_attr_iterator<OwnershipAttr>
632 i = FD->specific_attr_begin<OwnershipAttr>(),
633 e = FD->specific_attr_end<OwnershipAttr>();
634 i != e; ++i) {
635 switch ((*i)->getOwnKind()) {
636 case OwnershipAttr::Returns:
637 State = MallocMemReturnsAttr(C, CE, *i);
638 break;
639 case OwnershipAttr::Takes:
640 case OwnershipAttr::Holds:
641 State = FreeMemAttr(C, CE, *i);
642 break;
643 }
644 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000645 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000646 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000647}
648
Anton Yartsev13df0362013-03-25 01:35:45 +0000649void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
650 CheckerContext &C) const {
651
652 if (NE->getNumPlacementArgs())
653 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
654 E = NE->placement_arg_end(); I != E; ++I)
655 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
656 checkUseAfterFree(Sym, C, *I);
657
Anton Yartsev13df0362013-03-25 01:35:45 +0000658 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
659 return;
660
661 ProgramStateRef State = C.getState();
662 // The return value from operator new is bound to a specified initialization
663 // value (if any) and we don't want to loose this value. So we call
664 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
665 // existing binding.
Anton Yartsev05789592013-03-28 17:05:19 +0000666 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
667 : AF_CXXNew);
Anton Yartsev13df0362013-03-25 01:35:45 +0000668 C.addTransition(State);
669}
670
671void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
672 CheckerContext &C) const {
673
Anton Yartsev05789592013-03-28 17:05:19 +0000674 if (!Filter.CNewDeleteChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +0000675 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
676 checkUseAfterFree(Sym, C, DE->getArgument());
677
Anton Yartsev13df0362013-03-25 01:35:45 +0000678 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
679 return;
680
681 ProgramStateRef State = C.getState();
682 bool ReleasedAllocated;
683 State = FreeMemAux(C, DE->getArgument(), DE, State,
684 /*Hold*/false, ReleasedAllocated);
685
686 C.addTransition(State);
687}
688
Jordan Rose613f3c02013-03-09 00:59:10 +0000689static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
690 // If the first selector piece is one of the names below, assume that the
691 // object takes ownership of the memory, promising to eventually deallocate it
692 // with free().
693 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
694 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
695 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
696 if (FirstSlot == "dataWithBytesNoCopy" ||
697 FirstSlot == "initWithBytesNoCopy" ||
698 FirstSlot == "initWithCharactersNoCopy")
699 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000700
701 return false;
702}
703
Jordan Rose613f3c02013-03-09 00:59:10 +0000704static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
705 Selector S = Call.getSelector();
706
707 // FIXME: We should not rely on fully-constrained symbols being folded.
708 for (unsigned i = 1; i < S.getNumArgs(); ++i)
709 if (S.getNameForSlot(i).equals("freeWhenDone"))
710 return !Call.getArgSVal(i).isZeroConstant();
711
712 return None;
713}
714
Anna Zaks67291b92012-11-13 03:18:01 +0000715void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
716 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +0000717 if (C.wasInlined)
718 return;
719
Jordan Rose613f3c02013-03-09 00:59:10 +0000720 if (!isKnownDeallocObjCMethodName(Call))
721 return;
Anna Zaks67291b92012-11-13 03:18:01 +0000722
Jordan Rose613f3c02013-03-09 00:59:10 +0000723 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
724 if (!*FreeWhenDone)
725 return;
726
727 bool ReleasedAllocatedMemory;
728 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
729 Call.getOriginExpr(), C.getState(),
730 /*Hold=*/true, ReleasedAllocatedMemory,
731 /*RetNullOnFailure=*/true);
732
733 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +0000734}
735
Richard Smith852e9ce2013-11-27 01:46:48 +0000736ProgramStateRef
737MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
738 const OwnershipAttr *Att) const {
739 if (Att->getModule() != II_malloc)
Anna Zaks40a7eb32012-02-22 19:24:52 +0000740 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000741
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000742 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000743 if (I != E) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000744 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekd21139a2010-07-31 01:52:11 +0000745 }
Anna Zaks40a7eb32012-02-22 19:24:52 +0000746 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekd21139a2010-07-31 01:52:11 +0000747}
748
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000749ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000750 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000751 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000752 ProgramStateRef State,
753 AllocationFamily Family) {
Anna Zaks3563fde2012-06-07 03:57:32 +0000754
755 // Bind the return value to the symbolic value from the heap region.
756 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
757 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +0000758 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +0000759 SValBuilder &svalBuilder = C.getSValBuilder();
760 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000761 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
762 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +0000763 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000764
Anna Zaksd5157482012-02-15 00:11:22 +0000765 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000766 if (!RetVal.getAs<Loc>())
Anna Zaksd5157482012-02-15 00:11:22 +0000767 return 0;
768
Jordy Rose674bd552010-07-04 00:00:41 +0000769 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +0000770 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000771
Jordy Rose674bd552010-07-04 00:00:41 +0000772 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +0000773 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +0000774 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +0000775 if (!R)
Anna Zaks31886862012-02-10 01:11:00 +0000776 return 0;
David Blaikie05785d12013-02-20 22:23:23 +0000777 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000778 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000779 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +0000780 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +0000781 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +0000782 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +0000783
Anton Yartsev05789592013-03-28 17:05:19 +0000784 State = State->assume(extentMatchesSize, true);
785 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +0000786 }
Ted Kremenek90af9092010-12-02 07:49:45 +0000787
Anton Yartsev05789592013-03-28 17:05:19 +0000788 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000789}
790
791ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +0000792 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +0000793 ProgramStateRef State,
794 AllocationFamily Family) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000795 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +0000796 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +0000797
798 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000799 if (!retVal.getAs<Loc>())
Anna Zaks40a7eb32012-02-22 19:24:52 +0000800 return 0;
801
Ted Kremenek90af9092010-12-02 07:49:45 +0000802 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000803 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +0000804
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000805 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +0000806 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000807}
808
Anna Zaks40a7eb32012-02-22 19:24:52 +0000809ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
810 const CallExpr *CE,
Richard Smith852e9ce2013-11-27 01:46:48 +0000811 const OwnershipAttr *Att) const {
812 if (Att->getModule() != II_malloc)
Anna Zaks40a7eb32012-02-22 19:24:52 +0000813 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000814
Anna Zaks8dc53af2012-03-01 22:06:06 +0000815 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000816 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +0000817
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000818 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
819 I != E; ++I) {
Anna Zaks8dc53af2012-03-01 22:06:06 +0000820 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000821 Att->getOwnKind() == OwnershipAttr::Holds,
822 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +0000823 if (StateI)
824 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000825 }
Anna Zaks8dc53af2012-03-01 22:06:06 +0000826 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000827}
828
Ted Kremenek49b1e382012-01-26 21:29:00 +0000829ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +0000830 const CallExpr *CE,
831 ProgramStateRef state,
832 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000833 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000834 bool &ReleasedAllocated,
835 bool ReturnsNullOnFailure) const {
Anna Zaksb508d292012-04-10 23:41:11 +0000836 if (CE->getNumArgs() < (Num + 1))
837 return 0;
838
Anna Zaks67291b92012-11-13 03:18:01 +0000839 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
840 ReleasedAllocated, ReturnsNullOnFailure);
841}
842
Anna Zaksa14c1d02012-11-13 19:47:40 +0000843/// Checks if the previous call to free on the given symbol failed - if free
844/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +0000845static bool didPreviousFreeFail(ProgramStateRef State,
846 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +0000847 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +0000848 if (Ret) {
849 assert(*Ret && "We should not store the null return symbol");
850 ConstraintManager &CMgr = State->getConstraintManager();
851 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +0000852 RetStatusSymbol = *Ret;
853 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +0000854 }
Anna Zaksa14c1d02012-11-13 19:47:40 +0000855 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000856}
857
Anton Yartsev05789592013-03-28 17:05:19 +0000858AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +0000859 const Stmt *S) const {
860 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +0000861 return AF_None;
862
Anton Yartseve3377fb2013-04-04 23:46:29 +0000863 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +0000864 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000865
866 if (!FD)
867 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
868
Anton Yartsev05789592013-03-28 17:05:19 +0000869 ASTContext &Ctx = C.getASTContext();
870
Anton Yartseve3377fb2013-04-04 23:46:29 +0000871 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx))
Anton Yartsev05789592013-03-28 17:05:19 +0000872 return AF_Malloc;
873
874 if (isStandardNewDelete(FD, Ctx)) {
875 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +0000876 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +0000877 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000878 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +0000879 return AF_CXXNewArray;
880 }
881
882 return AF_None;
883 }
884
Anton Yartseve3377fb2013-04-04 23:46:29 +0000885 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
886 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
887
888 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +0000889 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
890
Anton Yartseve3377fb2013-04-04 23:46:29 +0000891 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +0000892 return AF_Malloc;
893
894 return AF_None;
895}
896
897bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
898 const Expr *E) const {
899 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
900 // FIXME: This doesn't handle indirect calls.
901 const FunctionDecl *FD = CE->getDirectCallee();
902 if (!FD)
903 return false;
904
905 os << *FD;
906 if (!FD->isOverloadedOperator())
907 os << "()";
908 return true;
909 }
910
911 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
912 if (Msg->isInstanceMessage())
913 os << "-";
914 else
915 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +0000916 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +0000917 return true;
918 }
919
920 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
921 os << "'"
922 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
923 << "'";
924 return true;
925 }
926
927 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
928 os << "'"
929 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
930 << "'";
931 return true;
932 }
933
934 return false;
935}
936
937void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
938 const Expr *E) const {
939 AllocationFamily Family = getAllocationFamily(C, E);
940
941 switch(Family) {
942 case AF_Malloc: os << "malloc()"; return;
943 case AF_CXXNew: os << "'new'"; return;
944 case AF_CXXNewArray: os << "'new[]'"; return;
945 case AF_None: llvm_unreachable("not a deallocation expression");
946 }
947}
948
949void MallocChecker::printExpectedDeallocName(raw_ostream &os,
950 AllocationFamily Family) const {
951 switch(Family) {
952 case AF_Malloc: os << "free()"; return;
953 case AF_CXXNew: os << "'delete'"; return;
954 case AF_CXXNewArray: os << "'delete[]'"; return;
955 case AF_None: llvm_unreachable("suspicious AF_None argument");
956 }
957}
958
Anna Zaks0d6989b2012-06-22 02:04:31 +0000959ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
960 const Expr *ArgExpr,
961 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000962 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000963 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000964 bool &ReleasedAllocated,
965 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +0000966
Anna Zaks67291b92012-11-13 03:18:01 +0000967 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +0000968 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zaks31886862012-02-10 01:11:00 +0000969 return 0;
David Blaikie2fdacbc2013-02-20 05:52:05 +0000970 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000971
972 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000973 if (!location.getAs<Loc>())
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000974 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000975
Anna Zaksad01ef52012-02-14 00:26:13 +0000976 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000977 ProgramStateRef notNullState, nullState;
Anna Zaks67291b92012-11-13 03:18:01 +0000978 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000979 if (nullState && !notNullState)
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000980 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000981
Jordy Rose3597b212010-06-07 19:32:37 +0000982 // Unknown values could easily be okay
983 // Undefined values are handled elsewhere
984 if (ArgVal.isUnknownOrUndef())
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000985 return 0;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000986
Jordy Rose3597b212010-06-07 19:32:37 +0000987 const MemRegion *R = ArgVal.getAsRegion();
988
989 // Nonlocs can't be freed, of course.
990 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
991 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +0000992 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000993 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +0000994 }
995
996 R = R->StripCasts();
997
998 // Blocks might show up as heap data, but should not be free()d
999 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001000 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001001 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +00001002 }
1003
1004 const MemSpaceRegion *MS = R->getMemorySpace();
1005
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001006 // Parameters, locals, statics, globals, and memory returned by alloca()
1007 // shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001008 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1009 // FIXME: at the time this code was written, malloc() regions were
1010 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1011 // This means that there isn't actually anything from HeapSpaceRegion
1012 // that should be freed, even though we allow it here.
1013 // Of course, free() can work on memory allocated outside the current
1014 // function, so UnknownSpaceRegion is always a possibility.
1015 // False negatives are better than false positives.
1016
Anton Yartsev05789592013-03-28 17:05:19 +00001017 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001018 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +00001019 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001020
1021 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001022 // Various cases could lead to non-symbol values here.
1023 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001024 if (!SrBase)
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001025 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +00001026
Anna Zaksc89ad072013-02-07 23:05:47 +00001027 SymbolRef SymBase = SrBase->getSymbol();
1028 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001029 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001030
Anton Yartseve3377fb2013-04-04 23:46:29 +00001031 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001032
Anna Zaks93a21a82013-04-09 00:30:28 +00001033 // Check for double free first.
1034 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001035 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1036 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1037 SymBase, PreviousRetStatusSymbol);
1038 return 0;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001039
Anna Zaks93a21a82013-04-09 00:30:28 +00001040 // If the pointer is allocated or escaped, but we are now trying to free it,
1041 // check that the call to free is proper.
1042 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1043
1044 // Check if an expected deallocation function matches the real one.
1045 bool DeallocMatchesAlloc =
1046 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1047 if (!DeallocMatchesAlloc) {
1048 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001049 ParentExpr, RsBase, SymBase, Hold);
Anna Zaks93a21a82013-04-09 00:30:28 +00001050 return 0;
1051 }
1052
1053 // Check if the memory location being freed is the actual location
1054 // allocated, or an offset.
1055 RegionOffset Offset = R->getAsOffset();
1056 if (Offset.isValid() &&
1057 !Offset.hasSymbolicOffset() &&
1058 Offset.getOffset() != 0) {
1059 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1060 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1061 AllocExpr);
1062 return 0;
1063 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001064 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001065 }
1066
Jordan Rose2f8b0222013-08-15 17:22:06 +00001067 ReleasedAllocated = (RsBase != 0) && RsBase->isAllocated();
Anna Zaksfe6eb672012-08-24 02:28:20 +00001068
Anna Zaksa14c1d02012-11-13 19:47:40 +00001069 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001070 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001071
Anna Zaks67291b92012-11-13 03:18:01 +00001072 // Keep track of the return value. If it is NULL, we will know that free
1073 // failed.
1074 if (ReturnsNullOnFailure) {
1075 SVal RetVal = C.getSVal(ParentExpr);
1076 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1077 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001078 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1079 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001080 }
1081 }
1082
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001083 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1084 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001085 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001086 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001087 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001088 RefState::getRelinquished(Family,
1089 ParentExpr));
1090
1091 return State->set<RegionState>(SymBase,
1092 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001093}
1094
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001095bool MallocChecker::isTrackedByCurrentChecker(AllocationFamily Family) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001096 switch (Family) {
1097 case AF_Malloc: {
1098 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic)
1099 return false;
Anton Yartsev2f910042013-04-05 02:12:04 +00001100 return true;
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001101 }
1102 case AF_CXXNew:
1103 case AF_CXXNewArray: {
Anton Yartsev7af0aa82013-04-12 23:25:40 +00001104 if (!Filter.CNewDeleteChecker)
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001105 return false;
Anton Yartsev2f910042013-04-05 02:12:04 +00001106 return true;
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001107 }
1108 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001109 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001110 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001111 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001112 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001113}
1114
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001115bool
1116MallocChecker::isTrackedByCurrentChecker(CheckerContext &C,
1117 const Stmt *AllocDeallocStmt) const {
1118 return isTrackedByCurrentChecker(getAllocationFamily(C, AllocDeallocStmt));
Anton Yartseve3377fb2013-04-04 23:46:29 +00001119}
1120
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001121bool MallocChecker::isTrackedByCurrentChecker(CheckerContext &C,
1122 SymbolRef Sym) const {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001123
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001124 const RefState *RS = C.getState()->get<RegionState>(Sym);
1125 assert(RS);
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001126 return isTrackedByCurrentChecker(RS->getAllocationFamily());
Anton Yartseve3377fb2013-04-04 23:46:29 +00001127}
1128
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001129bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001130 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001131 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001132 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001133 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001134 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001135 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001136 else
1137 return false;
1138
1139 return true;
1140}
1141
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001142bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001143 const MemRegion *MR) {
1144 switch (MR->getKind()) {
1145 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001146 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001147 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001148 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001149 else
1150 os << "the address of a function";
1151 return true;
1152 }
1153 case MemRegion::BlockTextRegionKind:
1154 os << "block text";
1155 return true;
1156 case MemRegion::BlockDataRegionKind:
1157 // FIXME: where the block came from?
1158 os << "a block";
1159 return true;
1160 default: {
1161 const MemSpaceRegion *MS = MR->getMemorySpace();
1162
Anna Zaks8158ef02012-01-04 23:54:01 +00001163 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001164 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1165 const VarDecl *VD;
1166 if (VR)
1167 VD = VR->getDecl();
1168 else
1169 VD = NULL;
1170
1171 if (VD)
1172 os << "the address of the local variable '" << VD->getName() << "'";
1173 else
1174 os << "the address of a local stack variable";
1175 return true;
1176 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001177
1178 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001179 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1180 const VarDecl *VD;
1181 if (VR)
1182 VD = VR->getDecl();
1183 else
1184 VD = NULL;
1185
1186 if (VD)
1187 os << "the address of the parameter '" << VD->getName() << "'";
1188 else
1189 os << "the address of a parameter";
1190 return true;
1191 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001192
1193 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001194 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1195 const VarDecl *VD;
1196 if (VR)
1197 VD = VR->getDecl();
1198 else
1199 VD = NULL;
1200
1201 if (VD) {
1202 if (VD->isStaticLocal())
1203 os << "the address of the static variable '" << VD->getName() << "'";
1204 else
1205 os << "the address of the global variable '" << VD->getName() << "'";
1206 } else
1207 os << "the address of a global variable";
1208 return true;
1209 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001210
1211 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001212 }
1213 }
1214}
1215
Anton Yartsev05789592013-03-28 17:05:19 +00001216void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1217 SourceRange Range,
1218 const Expr *DeallocExpr) const {
1219
1220 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1221 !Filter.CNewDeleteChecker)
1222 return;
1223
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001224 if (!isTrackedByCurrentChecker(C, DeallocExpr))
Anton Yartseve3377fb2013-04-04 23:46:29 +00001225 return;
1226
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001227 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose3597b212010-06-07 19:32:37 +00001228 if (!BT_BadFree)
Anna Zaks546c49c2012-02-16 22:26:12 +00001229 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose3597b212010-06-07 19:32:37 +00001230
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001231 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001232 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001233
Jordy Rose3597b212010-06-07 19:32:37 +00001234 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001235 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1236 MR = ER->getSuperRegion();
1237
1238 if (MR && isa<AllocaRegion>(MR))
1239 os << "Memory allocated by alloca() should not be deallocated";
1240 else {
1241 os << "Argument to ";
1242 if (!printAllocDeallocName(os, C, DeallocExpr))
1243 os << "deallocator";
1244
1245 os << " is ";
1246 bool Summarized = MR ? SummarizeRegion(os, MR)
1247 : SummarizeValue(os, ArgVal);
1248 if (Summarized)
1249 os << ", which is not memory allocated by ";
Jordy Rose3597b212010-06-07 19:32:37 +00001250 else
Anton Yartsev05789592013-03-28 17:05:19 +00001251 os << "not memory allocated by ";
1252
1253 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose3597b212010-06-07 19:32:37 +00001254 }
Anton Yartsev05789592013-03-28 17:05:19 +00001255
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001256 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001257 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001258 R->addRange(Range);
Jordan Rosee10d5a72012-11-02 01:53:40 +00001259 C.emitReport(R);
Jordy Rose3597b212010-06-07 19:32:37 +00001260 }
1261}
1262
Anton Yartseve3377fb2013-04-04 23:46:29 +00001263void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1264 SourceRange Range,
1265 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001266 const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001267 SymbolRef Sym,
1268 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001269
1270 if (!Filter.CMismatchedDeallocatorChecker)
1271 return;
1272
1273 if (ExplodedNode *N = C.generateSink()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001274 if (!BT_MismatchedDealloc)
1275 BT_MismatchedDealloc.reset(new BugType("Bad deallocator",
1276 "Memory Error"));
Anton Yartsev05789592013-03-28 17:05:19 +00001277
1278 SmallString<100> buf;
1279 llvm::raw_svector_ostream os(buf);
1280
1281 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1282 SmallString<20> AllocBuf;
1283 llvm::raw_svector_ostream AllocOs(AllocBuf);
1284 SmallString<20> DeallocBuf;
1285 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1286
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001287 if (OwnershipTransferred) {
1288 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1289 os << DeallocOs.str() << " cannot";
1290 else
1291 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001292
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001293 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001294
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001295 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1296 os << " allocated by " << AllocOs.str();
1297 } else {
1298 os << "Memory";
1299 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1300 os << " allocated by " << AllocOs.str();
1301
1302 os << " should be deallocated by ";
1303 printExpectedDeallocName(os, RS->getAllocationFamily());
1304
1305 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1306 os << ", not " << DeallocOs.str();
1307 }
Anton Yartsev05789592013-03-28 17:05:19 +00001308
Anton Yartseve3377fb2013-04-04 23:46:29 +00001309 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001310 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001311 R->addRange(Range);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001312 R->addVisitor(new MallocBugVisitor(Sym));
Anton Yartsev05789592013-03-28 17:05:19 +00001313 C.emitReport(R);
1314 }
1315}
1316
Anna Zaksc89ad072013-02-07 23:05:47 +00001317void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001318 SourceRange Range, const Expr *DeallocExpr,
1319 const Expr *AllocExpr) const {
1320
1321 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1322 !Filter.CNewDeleteChecker)
1323 return;
1324
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001325 if (!isTrackedByCurrentChecker(C, AllocExpr))
Anton Yartseve3377fb2013-04-04 23:46:29 +00001326 return;
1327
Anna Zaksc89ad072013-02-07 23:05:47 +00001328 ExplodedNode *N = C.generateSink();
1329 if (N == NULL)
1330 return;
1331
1332 if (!BT_OffsetFree)
1333 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1334
1335 SmallString<100> buf;
1336 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001337 SmallString<20> AllocNameBuf;
1338 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001339
1340 const MemRegion *MR = ArgVal.getAsRegion();
1341 assert(MR && "Only MemRegion based symbols can have offset free errors");
1342
1343 RegionOffset Offset = MR->getAsOffset();
1344 assert((Offset.isValid() &&
1345 !Offset.hasSymbolicOffset() &&
1346 Offset.getOffset() != 0) &&
1347 "Only symbols with a valid offset can have offset free errors");
1348
1349 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1350
Anton Yartsev05789592013-03-28 17:05:19 +00001351 os << "Argument to ";
1352 if (!printAllocDeallocName(os, C, DeallocExpr))
1353 os << "deallocator";
1354 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001355 << offsetBytes
1356 << " "
1357 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001358 << " from the start of ";
1359 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1360 os << "memory allocated by " << AllocNameOs.str();
1361 else
1362 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001363
1364 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1365 R->markInteresting(MR->getBaseRegion());
1366 R->addRange(Range);
1367 C.emitReport(R);
1368}
1369
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001370void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1371 SymbolRef Sym) const {
1372
Anton Yartsev05789592013-03-28 17:05:19 +00001373 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1374 !Filter.CNewDeleteChecker)
1375 return;
1376
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001377 if (!isTrackedByCurrentChecker(C, Sym))
Anton Yartseve3377fb2013-04-04 23:46:29 +00001378 return;
1379
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001380 if (ExplodedNode *N = C.generateSink()) {
1381 if (!BT_UseFree)
1382 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1383
1384 BugReport *R = new BugReport(*BT_UseFree,
1385 "Use of memory after it is freed", N);
1386
1387 R->markInteresting(Sym);
1388 R->addRange(Range);
1389 R->addVisitor(new MallocBugVisitor(Sym));
1390 C.emitReport(R);
1391 }
1392}
1393
1394void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1395 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001396 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001397
Anton Yartsev05789592013-03-28 17:05:19 +00001398 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1399 !Filter.CNewDeleteChecker)
1400 return;
1401
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001402 if (!isTrackedByCurrentChecker(C, Sym))
Anton Yartseve3377fb2013-04-04 23:46:29 +00001403 return;
1404
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001405 if (ExplodedNode *N = C.generateSink()) {
1406 if (!BT_DoubleFree)
1407 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1408
1409 BugReport *R = new BugReport(*BT_DoubleFree,
1410 (Released ? "Attempt to free released memory"
1411 : "Attempt to free non-owned memory"),
1412 N);
1413 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001414 R->markInteresting(Sym);
1415 if (PrevSym)
1416 R->markInteresting(PrevSym);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001417 R->addVisitor(new MallocBugVisitor(Sym));
1418 C.emitReport(R);
1419 }
1420}
1421
Jordan Rose656fdd52014-01-08 18:46:55 +00001422void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1423
1424 if (!Filter.CNewDeleteChecker)
1425 return;
1426
1427 if (!isTrackedByCurrentChecker(C, Sym))
1428 return;
1429
1430 if (ExplodedNode *N = C.generateSink()) {
1431 if (!BT_DoubleDelete)
1432 BT_DoubleDelete.reset(new BugType("Double delete", "Memory Error"));
1433
1434 BugReport *R = new BugReport(*BT_DoubleDelete,
1435 "Attempt to delete released memory", N);
1436
1437 R->markInteresting(Sym);
1438 R->addVisitor(new MallocBugVisitor(Sym));
1439 C.emitReport(R);
1440 }
1441}
1442
Anna Zaks40a7eb32012-02-22 19:24:52 +00001443ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1444 const CallExpr *CE,
1445 bool FreesOnFail) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001446 if (CE->getNumArgs() < 2)
1447 return 0;
1448
Ted Kremenek49b1e382012-01-26 21:29:00 +00001449 ProgramStateRef state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +00001450 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001451 const LocationContext *LCtx = C.getLocationContext();
Anna Zaks31886862012-02-10 01:11:00 +00001452 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001453 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks40a7eb32012-02-22 19:24:52 +00001454 return 0;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001455 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001456
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001457 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001458
Ted Kremenek90af9092010-12-02 07:49:45 +00001459 DefinedOrUnknownSVal PtrEQ =
1460 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001461
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001462 // Get the size argument. If there is no size arg then give up.
1463 const Expr *Arg1 = CE->getArg(1);
1464 if (!Arg1)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001465 return 0;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001466
1467 // Get the value of the size argument.
Anna Zaks31886862012-02-10 01:11:00 +00001468 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001469 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks40a7eb32012-02-22 19:24:52 +00001470 return 0;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001471 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001472
1473 // Compare the size argument to 0.
1474 DefinedOrUnknownSVal SizeZero =
1475 svalBuilder.evalEQ(state, Arg1Val,
1476 svalBuilder.makeIntValWithPtrWidth(0, false));
1477
Anna Zaksd56c8792012-02-13 18:05:39 +00001478 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1479 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1480 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1481 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1482 // We only assume exceptional states if they are definitely true; if the
1483 // state is under-constrained, assume regular realloc behavior.
1484 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1485 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1486
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001487 // If the ptr is NULL and the size is not 0, the call is equivalent to
1488 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001489 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001490 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001491 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001492 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001493 }
1494
Anna Zaksd56c8792012-02-13 18:05:39 +00001495 if (PrtIsNull && SizeIsZero)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001496 return 0;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001497
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001498 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001499 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001500 SymbolRef FromPtr = arg0Val.getAsSymbol();
1501 SVal RetVal = state->getSVal(CE, LCtx);
1502 SymbolRef ToPtr = RetVal.getAsSymbol();
1503 if (!FromPtr || !ToPtr)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001504 return 0;
Anna Zaksd56c8792012-02-13 18:05:39 +00001505
Anna Zaksfe6eb672012-08-24 02:28:20 +00001506 bool ReleasedAllocated = false;
1507
Anna Zaksd56c8792012-02-13 18:05:39 +00001508 // If the size is 0, free the memory.
1509 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001510 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1511 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001512 // The semantics of the return value are:
1513 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001514 // to free() is returned. We just free the input pointer and do not add
1515 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001516 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001517 }
1518
1519 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001520 if (ProgramStateRef stateFree =
1521 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1522
Anna Zaksd56c8792012-02-13 18:05:39 +00001523 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1524 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001525 if (!stateRealloc)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001526 return 0;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001527
Anna Zaks75cfbb62012-09-12 22:57:34 +00001528 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1529 if (FreesOnFail)
1530 Kind = RPIsFreeOnFailure;
1531 else if (!ReleasedAllocated)
1532 Kind = RPDoNotTrackAfterFailure;
1533
Anna Zaksfe6eb672012-08-24 02:28:20 +00001534 // Record the info about the reallocated symbol so that we could properly
1535 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001536 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001537 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001538 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001539 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001540 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001541 }
Anna Zaks40a7eb32012-02-22 19:24:52 +00001542 return 0;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001543}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001544
Anna Zaks40a7eb32012-02-22 19:24:52 +00001545ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaksb508d292012-04-10 23:41:11 +00001546 if (CE->getNumArgs() < 2)
1547 return 0;
1548
Ted Kremenek49b1e382012-01-26 21:29:00 +00001549 ProgramStateRef state = C.getState();
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001550 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001551 const LocationContext *LCtx = C.getLocationContext();
1552 SVal count = state->getSVal(CE->getArg(0), LCtx);
1553 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001554 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1555 svalBuilder.getContext().getSizeType());
1556 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001557
Anna Zaks40a7eb32012-02-22 19:24:52 +00001558 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001559}
1560
Anna Zaksfc2e1532012-03-21 19:45:08 +00001561LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00001562MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1563 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00001564 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00001565 // Walk the ExplodedGraph backwards and find the first node that referred to
1566 // the tracked symbol.
1567 const ExplodedNode *AllocNode = N;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001568 const MemRegion *ReferenceRegion = 0;
Anna Zaksdf901a42012-02-23 21:38:21 +00001569
1570 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00001571 ProgramStateRef State = N->getState();
1572 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00001573 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001574
1575 // Find the most recent expression bound to the symbol in the current
1576 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00001577 if (!ReferenceRegion) {
1578 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1579 SVal Val = State->getSVal(MR);
1580 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00001581 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00001582 // Do not show local variables belonging to a function other than
1583 // where the error is reported.
1584 if (!VR ||
1585 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1586 ReferenceRegion = MR;
1587 }
1588 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00001589 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00001590
Anna Zaks43ffba22012-02-27 23:40:55 +00001591 // Allocation node, is the last node in the current context in which the
1592 // symbol was tracked.
1593 if (N->getLocationContext() == LeakContext)
1594 AllocNode = N;
Anna Zaksdf901a42012-02-23 21:38:21 +00001595 N = N->pred_empty() ? NULL : *(N->pred_begin());
1596 }
1597
Anna Zaksa043d0c2013-01-08 00:25:29 +00001598 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00001599}
1600
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001601void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1602 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001603
1604 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
Jordan Rose26330562013-04-05 17:55:00 +00001605 !Filter.CNewDeleteLeaksChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00001606 return;
1607
Jordan Rose26330562013-04-05 17:55:00 +00001608 const RefState *RS = C.getState()->get<RegionState>(Sym);
1609 assert(RS && "cannot leak an untracked symbol");
1610 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001611 if (!isTrackedByCurrentChecker(Family))
Anton Yartsev6e499252013-04-05 02:25:02 +00001612 return;
1613
Jordan Rose26330562013-04-05 17:55:00 +00001614 // Special case for new and new[]; these are controlled by a separate checker
1615 // flag so that they can be selectively disabled.
1616 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
1617 if (!Filter.CNewDeleteLeaksChecker)
1618 return;
1619
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001620 assert(N);
1621 if (!BT_Leak) {
Anna Zaks546c49c2012-02-16 22:26:12 +00001622 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001623 // Leaks should not be reported if they are post-dominated by a sink:
1624 // (1) Sinks are higher importance bugs.
1625 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1626 // with __noreturn functions such as assert() or exit(). We choose not
1627 // to report leaks on such paths.
1628 BT_Leak->setSuppressOnSink(true);
1629 }
1630
Anna Zaksdf901a42012-02-23 21:38:21 +00001631 // Most bug reports are cached at the location where they occurred.
1632 // With leaks, we want to unique them by the location where they were
1633 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00001634 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaksa043d0c2013-01-08 00:25:29 +00001635 const ExplodedNode *AllocNode = 0;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001636 const MemRegion *Region = 0;
Anna Zaksa043d0c2013-01-08 00:25:29 +00001637 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1638
1639 ProgramPoint P = AllocNode->getLocation();
1640 const Stmt *AllocationStmt = 0;
David Blaikie87396b92013-02-21 22:23:56 +00001641 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001642 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00001643 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001644 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00001645 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00001646 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1647 C.getSourceManager(),
1648 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00001649
Anna Zaksfc2e1532012-03-21 19:45:08 +00001650 SmallString<200> buf;
1651 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001652 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00001653 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001654 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00001655 } else {
1656 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00001657 }
1658
Anna Zaksa043d0c2013-01-08 00:25:29 +00001659 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1660 LocUsedForUniqueing,
1661 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00001662 R->markInteresting(Sym);
Anna Zaks62cce9e2012-05-10 01:37:40 +00001663 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rosee10d5a72012-11-02 01:53:40 +00001664 C.emitReport(R);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001665}
1666
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00001667void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1668 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00001669{
Zhongxing Xubce831f2010-08-15 08:19:57 +00001670 if (!SymReaper.hasDeadSymbols())
1671 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00001672
Ted Kremenek49b1e382012-01-26 21:29:00 +00001673 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001674 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00001675 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001676
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001677 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00001678 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1679 if (SymReaper.isDead(I->first)) {
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001680 if (I->second.isAllocated())
Anna Zaks78edc2f2012-02-09 06:48:19 +00001681 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00001682 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001683 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00001684
Zhongxing Xuc7460962009-11-13 07:48:11 +00001685 }
1686 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001687
Anna Zaksd56c8792012-02-13 18:05:39 +00001688 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00001689 ReallocPairsTy RP = state->get<ReallocPairs>();
1690 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00001691 if (SymReaper.isDead(I->first) ||
1692 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00001693 state = state->remove<ReallocPairs>(I->first);
1694 }
1695 }
1696
Anna Zaks67291b92012-11-13 03:18:01 +00001697 // Cleanup the FreeReturnValue Map.
1698 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1699 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1700 if (SymReaper.isDead(I->first) ||
1701 SymReaper.isDead(I->second)) {
1702 state = state->remove<FreeReturnValue>(I->first);
1703 }
1704 }
1705
Anna Zaksdf901a42012-02-23 21:38:21 +00001706 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001707 ExplodedNode *N = C.getPredecessor();
1708 if (!Errors.empty()) {
1709 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1710 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper2341c0d2013-07-04 03:08:24 +00001711 for (SmallVectorImpl<SymbolRef>::iterator
1712 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001713 reportLeak(*I, N, C);
Anna Zaks78edc2f2012-02-09 06:48:19 +00001714 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001715 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001716
Anna Zaksdf901a42012-02-23 21:38:21 +00001717 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001718}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00001719
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001720void MallocChecker::checkPreCall(const CallEvent &Call,
1721 CheckerContext &C) const {
1722
Jordan Rose656fdd52014-01-08 18:46:55 +00001723 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
1724 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
1725 if (!Sym || checkDoubleDelete(Sym, C))
1726 return;
1727 }
1728
Anna Zaks46d01602012-05-18 01:16:10 +00001729 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001730 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
1731 const FunctionDecl *FD = FC->getDecl();
1732 if (!FD)
1733 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00001734
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001735 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1736 isFreeFunction(FD, C.getASTContext()))
1737 return;
Anna Zaks3d348342012-02-14 21:55:24 +00001738
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001739 if (Filter.CNewDeleteChecker &&
1740 isStandardNewDelete(FD, C.getASTContext()))
1741 return;
1742 }
1743
1744 // Check if the callee of a method is deleted.
1745 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
1746 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
1747 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
1748 return;
1749 }
1750
1751 // Check arguments for being used after free.
1752 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
1753 SVal ArgSVal = Call.getArgSVal(I);
1754 if (ArgSVal.getAs<Loc>()) {
1755 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00001756 if (!Sym)
1757 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001758 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00001759 return;
1760 }
1761 }
1762}
1763
Anna Zaksa1b227b2012-02-08 23:16:56 +00001764void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1765 const Expr *E = S->getRetValue();
1766 if (!E)
1767 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00001768
1769 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00001770 ProgramStateRef State = C.getState();
1771 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00001772 SymbolRef Sym = RetVal.getAsSymbol();
1773 if (!Sym)
1774 // If we are returning a field of the allocated struct or an array element,
1775 // the callee could still free the memory.
1776 // TODO: This logic should be a part of generic symbol escape callback.
1777 if (const MemRegion *MR = RetVal.getAsRegion())
1778 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1779 if (const SymbolicRegion *BMR =
1780 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1781 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00001782
Anna Zaks3aa52252012-02-11 21:44:39 +00001783 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00001784 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00001785 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00001786}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00001787
Anna Zaks9fe80982012-03-22 00:57:20 +00001788// TODO: Blocks should be either inlined or should call invalidate regions
1789// upon invocation. After that's in place, special casing here will not be
1790// needed.
1791void MallocChecker::checkPostStmt(const BlockExpr *BE,
1792 CheckerContext &C) const {
1793
1794 // Scan the BlockDecRefExprs for any object the retain count checker
1795 // may be tracking.
1796 if (!BE->getBlockDecl()->hasCaptures())
1797 return;
1798
1799 ProgramStateRef state = C.getState();
1800 const BlockDataRegion *R =
1801 cast<BlockDataRegion>(state->getSVal(BE,
1802 C.getLocationContext()).getAsRegion());
1803
1804 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1805 E = R->referenced_vars_end();
1806
1807 if (I == E)
1808 return;
1809
1810 SmallVector<const MemRegion*, 10> Regions;
1811 const LocationContext *LC = C.getLocationContext();
1812 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1813
1814 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00001815 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00001816 if (VR->getSuperRegion() == R) {
1817 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1818 }
1819 Regions.push_back(VR);
1820 }
1821
1822 state =
1823 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1824 Regions.data() + Regions.size()).getState();
1825 C.addTransition(state);
1826}
1827
Anna Zaks46d01602012-05-18 01:16:10 +00001828bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00001829 assert(Sym);
1830 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00001831 return (RS && RS->isReleased());
1832}
1833
1834bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1835 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00001836
Jordan Rose656fdd52014-01-08 18:46:55 +00001837 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001838 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1839 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00001840 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001841
Anna Zaksa1b227b2012-02-08 23:16:56 +00001842 return false;
1843}
1844
Jordan Rose656fdd52014-01-08 18:46:55 +00001845bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
1846
1847 if (isReleased(Sym, C)) {
1848 ReportDoubleDelete(C, Sym);
1849 return true;
1850 }
1851 return false;
1852}
1853
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00001854// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00001855void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1856 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00001857 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaksa1b227b2012-02-08 23:16:56 +00001858 if (Sym)
Anna Zaks46d01602012-05-18 01:16:10 +00001859 checkUseAfterFree(Sym, C, S);
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00001860}
Ted Kremenekd21139a2010-07-31 01:52:11 +00001861
Anna Zaksbb1ef902012-02-11 21:02:35 +00001862// If a symbolic region is assumed to NULL (or another constant), stop tracking
1863// it - assuming that allocation failed on this path.
1864ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1865 SVal Cond,
1866 bool Assumption) const {
1867 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00001868 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00001869 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00001870 ConstraintManager &CMgr = state->getConstraintManager();
1871 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1872 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00001873 state = state->remove<RegionState>(I.getKey());
1874 }
1875
Anna Zaksd56c8792012-02-13 18:05:39 +00001876 // Realloc returns 0 when reallocation fails, which means that we should
1877 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00001878 ReallocPairsTy RP = state->get<ReallocPairs>();
1879 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00001880 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00001881 ConstraintManager &CMgr = state->getConstraintManager();
1882 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00001883 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00001884 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00001885
Anna Zaks75cfbb62012-09-12 22:57:34 +00001886 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1887 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1888 if (RS->isReleased()) {
1889 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00001890 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00001891 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00001892 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1893 state = state->remove<RegionState>(ReallocSym);
1894 else
1895 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00001896 }
Anna Zaksd56c8792012-02-13 18:05:39 +00001897 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00001898 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00001899 }
1900
Anna Zaksbb1ef902012-02-11 21:02:35 +00001901 return state;
1902}
1903
Anna Zaks8ebeb642013-06-08 00:29:29 +00001904bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001905 const CallEvent *Call,
1906 ProgramStateRef State,
1907 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00001908 assert(Call);
Anna Zaks8ebeb642013-06-08 00:29:29 +00001909 EscapingSymbol = 0;
1910
Jordan Rose2a833ca2014-01-15 17:25:15 +00001911 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00001912 // TODO: If we want to be more optimistic here, we'll need to make sure that
1913 // regions escape to C++ containers. They seem to do that even now, but for
1914 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00001915 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001916 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00001917
Jordan Rose742920c2012-07-02 19:27:35 +00001918 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00001919 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00001920 // If it's not a framework call, or if it takes a callback, assume it
1921 // can free memory.
1922 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001923 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00001924
Jordan Rose613f3c02013-03-09 00:59:10 +00001925 // If it's a method we know about, handle it explicitly post-call.
1926 // This should happen before the "freeWhenDone" check below.
1927 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001928 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00001929
Jordan Rose613f3c02013-03-09 00:59:10 +00001930 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1931 // about, we can't be sure that the object will use free() to deallocate the
1932 // memory, so we can't model it explicitly. The best we can do is use it to
1933 // decide whether the pointer escapes.
1934 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001935 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00001936
Jordan Rose613f3c02013-03-09 00:59:10 +00001937 // If the first selector piece ends with "NoCopy", and there is no
1938 // "freeWhenDone" parameter set to zero, we know ownership is being
1939 // transferred. Again, though, we can't be sure that the object will use
1940 // free() to deallocate the memory, so we can't model it explicitly.
1941 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00001942 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001943 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00001944
Anna Zaks42908c72012-06-19 05:10:32 +00001945 // If the first selector starts with addPointer, insertPointer,
1946 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1947 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00001948 // that the pointers get freed by following the container itself.
1949 if (FirstSlot.startswith("addPointer") ||
1950 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00001951 FirstSlot.startswith("replacePointer") ||
1952 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001953 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00001954 }
1955
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001956 // We should escape receiver on call to 'init'. This is especially relevant
1957 // to the receiver, as the corresponding symbol is usually not referenced
1958 // after the call.
1959 if (Msg->getMethodFamily() == OMF_init) {
1960 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
1961 return true;
1962 }
Anna Zaks737926b2013-05-31 22:39:13 +00001963
Jordan Rose742920c2012-07-02 19:27:35 +00001964 // Otherwise, assume that the method does not free memory.
1965 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001966 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00001967 }
1968
Jordan Rose742920c2012-07-02 19:27:35 +00001969 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00001970 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00001971 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001972 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00001973
Jordan Rose742920c2012-07-02 19:27:35 +00001974 ASTContext &ASTC = State->getStateManager().getContext();
1975
1976 // If it's one of the allocation functions we can reason about, we model
1977 // its behavior explicitly.
1978 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001979 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00001980
1981 // If it's not a system call, assume it frees memory.
1982 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001983 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00001984
1985 // White list the system functions whose arguments escape.
1986 const IdentifierInfo *II = FD->getIdentifier();
1987 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001988 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00001989 StringRef FName = II->getName();
1990
Jordan Rose742920c2012-07-02 19:27:35 +00001991 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose7ab01822012-07-02 19:27:51 +00001992 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00001993 if (FName.endswith("NoCopy")) {
1994 // Look for the deallocator argument. We know that the memory ownership
1995 // is not transferred only if the deallocator argument is
1996 // 'kCFAllocatorNull'.
1997 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1998 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1999 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2000 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2001 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002002 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002003 }
2004 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002005 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002006 }
2007
Jordan Rose742920c2012-07-02 19:27:35 +00002008 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002009 // 'closefn' is specified (and if that function does free memory),
2010 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002011 // Currently, we do not inspect the 'closefn' function (PR12101).
2012 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002013 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002014 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002015
2016 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2017 // these leaks might be intentional when setting the buffer for stdio.
2018 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2019 if (FName == "setbuf" || FName =="setbuffer" ||
2020 FName == "setlinebuf" || FName == "setvbuf") {
2021 if (Call->getNumArgs() >= 1) {
2022 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2023 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2024 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2025 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002026 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002027 }
2028 }
2029
2030 // A bunch of other functions which either take ownership of a pointer or
2031 // wrap the result up in a struct or object, meaning it can be freed later.
2032 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2033 // but the Malloc checker cannot differentiate between them. The right way
2034 // of doing this would be to implement a pointer escapes callback.
2035 if (FName == "CGBitmapContextCreate" ||
2036 FName == "CGBitmapContextCreateWithData" ||
2037 FName == "CVPixelBufferCreateWithBytes" ||
2038 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2039 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002040 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002041 }
2042
Jordan Rose7ab01822012-07-02 19:27:51 +00002043 // Handle cases where we know a buffer's /address/ can escape.
2044 // Note that the above checks handle some special cases where we know that
2045 // even though the address escapes, it's still our responsibility to free the
2046 // buffer.
2047 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002048 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002049
2050 // Otherwise, assume that the function does not free memory.
2051 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002052 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002053}
2054
Anna Zaks333481b2013-03-28 23:15:29 +00002055static bool retTrue(const RefState *RS) {
2056 return true;
2057}
2058
2059static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2060 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2061 RS->getAllocationFamily() == AF_CXXNew);
2062}
2063
Anna Zaksdc154152012-12-20 00:38:25 +00002064ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2065 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002066 const CallEvent *Call,
2067 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002068 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2069}
2070
2071ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2072 const InvalidatedSymbols &Escaped,
2073 const CallEvent *Call,
2074 PointerEscapeKind Kind) const {
2075 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2076 &checkIfNewOrNewArrayFamily);
2077}
2078
2079ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2080 const InvalidatedSymbols &Escaped,
2081 const CallEvent *Call,
2082 PointerEscapeKind Kind,
2083 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002084 // If we know that the call does not free memory, or we want to process the
2085 // call later, keep tracking the top level arguments.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002086 SymbolRef EscapingSymbol = 0;
Jordan Rose757fbb02013-05-10 17:07:16 +00002087 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002088 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2089 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002090 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002091 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002092 }
Anna Zaks3d348342012-02-14 21:55:24 +00002093
Anna Zaksdc154152012-12-20 00:38:25 +00002094 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002095 E = Escaped.end();
2096 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002097 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002098
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002099 if (EscapingSymbol && EscapingSymbol != sym)
2100 continue;
2101
Anna Zaks0d6989b2012-06-22 02:04:31 +00002102 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks93a21a82013-04-09 00:30:28 +00002103 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002104 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002105 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2106 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002107 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002108 }
Anna Zaks3d348342012-02-14 21:55:24 +00002109 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002110}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002111
Jordy Rosebf38f202012-03-18 07:43:35 +00002112static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2113 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002114 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2115 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002116
Jordan Rose0c153cb2012-11-02 01:54:06 +00002117 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002118 I != E; ++I) {
2119 SymbolRef sym = I.getKey();
2120 if (!currMap.lookup(sym))
2121 return sym;
2122 }
2123
2124 return NULL;
2125}
2126
Anna Zaks2b5bb972012-02-09 06:25:51 +00002127PathDiagnosticPiece *
2128MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2129 const ExplodedNode *PrevN,
2130 BugReporterContext &BRC,
2131 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002132 ProgramStateRef state = N->getState();
2133 ProgramStateRef statePrev = PrevN->getState();
2134
2135 const RefState *RS = state->get<RegionState>(Sym);
2136 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002137 if (!RS)
Anna Zaks2b5bb972012-02-09 06:25:51 +00002138 return 0;
2139
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002140 const Stmt *S = 0;
2141 const char *Msg = 0;
Anna Zakscba4f292012-03-16 23:24:20 +00002142 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002143
2144 // Retrieve the associated statement.
2145 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002146 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002147 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002148 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002149 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002150 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002151 // If an assumption was made on a branch, it should be caught
2152 // here by looking at the state transition.
2153 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002154 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002155
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002156 if (!S)
Anna Zaks2b5bb972012-02-09 06:25:51 +00002157 return 0;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002158
Jordan Rose681cce92012-07-10 22:07:42 +00002159 // FIXME: We will eventually need to handle non-statement-based events
2160 // (__attribute__((cleanup))).
2161
Anna Zaks2b5bb972012-02-09 06:25:51 +00002162 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002163 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002164 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002165 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002166 StackHint = new StackHintGeneratorForSymbol(Sym,
2167 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002168 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002169 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002170 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002171 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002172 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002173 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002174 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002175 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002176 Mode = ReallocationFailed;
2177 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002178 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002179 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002180
Jordy Rose21ff76e2012-03-24 03:15:09 +00002181 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2182 // Is it possible to fail two reallocs WITHOUT testing in between?
2183 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2184 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002185 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002186 FailedReallocSymbol = sym;
2187 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002188 }
2189
2190 // We are in a special mode if a reallocation failed later in the path.
2191 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002192 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002193
Jordy Rose21ff76e2012-03-24 03:15:09 +00002194 // Is this is the first appearance of the reallocated symbol?
2195 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002196 // We're at the reallocation point.
2197 Msg = "Attempt to reallocate memory";
2198 StackHint = new StackHintGeneratorForSymbol(Sym,
2199 "Returned reallocated memory");
2200 FailedReallocSymbol = NULL;
2201 Mode = Normal;
2202 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002203 }
2204
Anna Zaks2b5bb972012-02-09 06:25:51 +00002205 if (!Msg)
2206 return 0;
Anna Zakscba4f292012-03-16 23:24:20 +00002207 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002208
2209 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002210 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002211 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002212 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002213}
2214
Anna Zaks263b7e02012-05-02 00:05:20 +00002215void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2216 const char *NL, const char *Sep) const {
2217
2218 RegionStateTy RS = State->get<RegionState>();
2219
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002220 if (!RS.isEmpty()) {
2221 Out << Sep << "MallocChecker:" << NL;
2222 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2223 I.getKey()->dumpToStream(Out);
2224 Out << " : ";
2225 I.getData().dump(Out);
2226 Out << NL;
2227 }
2228 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002229}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002230
Anna Zakse4cfcd42013-04-16 00:22:55 +00002231void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2232 registerCStringCheckerBasic(mgr);
2233 mgr.registerChecker<MallocChecker>()->Filter.CNewDeleteLeaksChecker = true;
2234 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2235 // checker.
2236 mgr.registerChecker<MallocChecker>()->Filter.CNewDeleteChecker = true;
2237}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002238
Anna Zakscd37bf42012-02-08 23:16:52 +00002239#define REGISTER_CHECKER(name) \
2240void ento::register##name(CheckerManager &mgr) {\
Anna Zakse56167e2012-02-17 22:35:31 +00002241 registerCStringCheckerBasic(mgr); \
Anna Zakscd37bf42012-02-08 23:16:52 +00002242 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002243}
Anna Zakscd37bf42012-02-08 23:16:52 +00002244
2245REGISTER_CHECKER(MallocPessimistic)
2246REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev13df0362013-03-25 01:35:45 +00002247REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002248REGISTER_CHECKER(MismatchedDeallocatorChecker)