blob: 1e996589c1b03120f15f1487d679b8d7f3fe7030 [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 {
Craig Topperd6d31ac2013-07-15 08:24:27 +0000103 static const char *const Table[] = {
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000104 "Allocated",
105 "Released",
106 "Relinquished"
107 };
108 OS << Table[(unsigned) K];
109 }
110
Alp Tokeref6b0072014-01-04 13:47:14 +0000111 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000112};
113
Anna Zaks75cfbb62012-09-12 22:57:34 +0000114enum ReallocPairKind {
115 RPToBeFreedAfterFailure,
116 // The symbol has been freed when reallocation failed.
117 RPIsFreeOnFailure,
118 // The symbol does not need to be freed after reallocation fails.
119 RPDoNotTrackAfterFailure
120};
121
Anna Zaksfe6eb672012-08-24 02:28:20 +0000122/// \class ReallocPair
123/// \brief Stores information about the symbol being reallocated by a call to
124/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000125struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000126 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000127 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000128 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000129
Anna Zaks75cfbb62012-09-12 22:57:34 +0000130 ReallocPair(SymbolRef S, ReallocPairKind K) :
131 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000132 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000133 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000134 ID.AddPointer(ReallocatedSym);
135 }
136 bool operator==(const ReallocPair &X) const {
137 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000138 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000139 }
140};
141
Anna Zaksa043d0c2013-01-08 00:25:29 +0000142typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000143
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000144class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000145 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000146 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000147 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000148 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000149 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000150 check::PostStmt<CXXNewExpr>,
151 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000152 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000153 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000154 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000155 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000156{
Anna Zaks546c49c2012-02-16 22:26:12 +0000157 mutable OwningPtr<BugType> BT_DoubleFree;
Jordan Rose656fdd52014-01-08 18:46:55 +0000158 mutable OwningPtr<BugType> BT_DoubleDelete;
Anna Zaks546c49c2012-02-16 22:26:12 +0000159 mutable OwningPtr<BugType> BT_Leak;
160 mutable OwningPtr<BugType> BT_UseFree;
161 mutable OwningPtr<BugType> BT_BadFree;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000162 mutable OwningPtr<BugType> BT_MismatchedDealloc;
Anna Zaksc89ad072013-02-07 23:05:47 +0000163 mutable OwningPtr<BugType> BT_OffsetFree;
Anna Zaksd5157482012-02-15 00:11:22 +0000164 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks199e8e52012-02-22 03:14:20 +0000165 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
166
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000167public:
Anna Zaksd5157482012-02-15 00:11:22 +0000168 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks199e8e52012-02-22 03:14:20 +0000169 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000170
171 /// In pessimistic mode, the checker assumes that it does not know which
172 /// functions might free the memory.
173 struct ChecksFilter {
174 DefaultBool CMallocPessimistic;
175 DefaultBool CMallocOptimistic;
Anton Yartsev13df0362013-03-25 01:35:45 +0000176 DefaultBool CNewDeleteChecker;
Jordan Rose26330562013-04-05 17:55:00 +0000177 DefaultBool CNewDeleteLeaksChecker;
Anton Yartsev05789592013-03-28 17:05:19 +0000178 DefaultBool CMismatchedDeallocatorChecker;
Anna Zakscd37bf42012-02-08 23:16:52 +0000179 };
180
181 ChecksFilter Filter;
182
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000183 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000184 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000185 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
186 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000187 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000188 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000189 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000190 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000191 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000192 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000193 void checkLocation(SVal l, bool isLoad, const Stmt *S,
194 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000195
196 ProgramStateRef checkPointerEscape(ProgramStateRef State,
197 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000198 const CallEvent *Call,
199 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000200 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
201 const InvalidatedSymbols &Escaped,
202 const CallEvent *Call,
203 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000204
Anna Zaks263b7e02012-05-02 00:05:20 +0000205 void printState(raw_ostream &Out, ProgramStateRef State,
206 const char *NL, const char *Sep) const;
207
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000208private:
Anna Zaks3d348342012-02-14 21:55:24 +0000209 void initIdentifierInfo(ASTContext &C) const;
210
Anton Yartsev05789592013-03-28 17:05:19 +0000211 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000212 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000213
214 /// \brief Print names of allocators and deallocators.
215 ///
216 /// \returns true on success.
217 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
218 const Expr *E) const;
219
220 /// \brief Print expected name of an allocator based on the deallocator's
221 /// family derived from the DeallocExpr.
222 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
223 const Expr *DeallocExpr) const;
224 /// \brief Print expected name of a deallocator based on the allocator's
225 /// family.
226 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
227
Jordan Rose613f3c02013-03-09 00:59:10 +0000228 ///@{
Anna Zaks3d348342012-02-14 21:55:24 +0000229 /// Check if this is one of the functions which can allocate/reallocate memory
230 /// pointed to by one of its arguments.
231 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks46d01602012-05-18 01:16:10 +0000232 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
233 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000234 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000235 ///@}
Richard Smith852e9ce2013-11-27 01:46:48 +0000236 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
237 const CallExpr *CE,
238 const OwnershipAttr* Att) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000239 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000240 const Expr *SizeEx, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000241 ProgramStateRef State,
242 AllocationFamily Family = AF_Malloc) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000243 return MallocMemAux(C, CE,
Anton Yartsev05789592013-03-28 17:05:19 +0000244 State->getSVal(SizeEx, C.getLocationContext()),
245 Init, State, Family);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000246 }
Anna Zaks40a7eb32012-02-22 19:24:52 +0000247
Ted Kremenek49b1e382012-01-26 21:29:00 +0000248 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000249 SVal SizeEx, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000250 ProgramStateRef State,
251 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000252
Anna Zaks40a7eb32012-02-22 19:24:52 +0000253 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev05789592013-03-28 17:05:19 +0000254 static ProgramStateRef
255 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
256 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000257
258 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
259 const OwnershipAttr* Att) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000260 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000261 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000262 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000263 bool &ReleasedAllocated,
264 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000265 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
266 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000267 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000268 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000269 bool &ReleasedAllocated,
270 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000271
Anna Zaks40a7eb32012-02-22 19:24:52 +0000272 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
273 bool FreesMemOnFailure) const;
274 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose3597b212010-06-07 19:32:37 +0000275
Anna Zaks46d01602012-05-18 01:16:10 +0000276 ///\brief Check if the memory associated with this symbol was released.
277 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
278
Anton Yartsev13df0362013-03-25 01:35:45 +0000279 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000280
Jordan Rose656fdd52014-01-08 18:46:55 +0000281 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
282
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000283 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000284 /// "interesting" and should be modeled explicitly.
285 ///
Anna Zaks8ebeb642013-06-08 00:29:29 +0000286 /// \param [out] EscapingSymbol A function might not free memory in general,
287 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000288 /// returned and the single escaping symbol is returned through the out
289 /// parameter.
290 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000291 /// We assume that pointers do not escape through calls to system functions
292 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000293 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000294 ProgramStateRef State,
295 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000296
Anna Zaks333481b2013-03-28 23:15:29 +0000297 // Implementation of the checkPointerEscape callabcks.
298 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
299 const InvalidatedSymbols &Escaped,
300 const CallEvent *Call,
301 PointerEscapeKind Kind,
302 bool(*CheckRefState)(const RefState*)) const;
303
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000304 ///@{
305 /// Tells if a given family/call/symbol is tracked by the current checker.
306 bool isTrackedByCurrentChecker(AllocationFamily Family) const;
307 bool isTrackedByCurrentChecker(CheckerContext &C,
308 const Stmt *AllocDeallocStmt) const;
309 bool isTrackedByCurrentChecker(CheckerContext &C, SymbolRef Sym) const;
310 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000311 static bool SummarizeValue(raw_ostream &os, SVal V);
312 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev05789592013-03-28 17:05:19 +0000313 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
314 const Expr *DeallocExpr) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000315 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000316 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000317 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000318 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
319 const Expr *DeallocExpr,
320 const Expr *AllocExpr = 0) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000321 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
322 SymbolRef Sym) const;
323 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000324 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000325
Jordan Rose656fdd52014-01-08 18:46:55 +0000326 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
327
Anna Zaksdf901a42012-02-23 21:38:21 +0000328 /// Find the location of the allocation for Sym on the path leading to the
329 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000330 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
331 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000332
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000333 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
334
Anna Zaks2b5bb972012-02-09 06:25:51 +0000335 /// The bug visitor which allows us to print extra diagnostics along the
336 /// BugReport path. For example, showing the allocation site of the leaked
337 /// region.
Jordy Rosef78877e2012-03-24 02:45:35 +0000338 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000339 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000340 enum NotificationMode {
341 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000342 ReallocationFailed
343 };
344
Anna Zaks2b5bb972012-02-09 06:25:51 +0000345 // The allocated region symbol tracked by the main analysis.
346 SymbolRef Sym;
347
Anna Zaks62cce9e2012-05-10 01:37:40 +0000348 // The mode we are in, i.e. what kind of diagnostics will be emitted.
349 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000350
Anna Zaks62cce9e2012-05-10 01:37:40 +0000351 // A symbol from when the primary region should have been reallocated.
352 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000353
Anna Zaks62cce9e2012-05-10 01:37:40 +0000354 bool IsLeak;
355
356 public:
357 MallocBugVisitor(SymbolRef S, bool isLeak = false)
358 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000359
Anna Zaks2b5bb972012-02-09 06:25:51 +0000360 virtual ~MallocBugVisitor() {}
361
362 void Profile(llvm::FoldingSetNodeID &ID) const {
363 static int X = 0;
364 ID.AddPointer(&X);
365 ID.AddPointer(Sym);
366 }
367
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000368 inline bool isAllocated(const RefState *S, const RefState *SPrev,
369 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000370 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000371 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000372 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000373 }
374
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000375 inline bool isReleased(const RefState *S, const RefState *SPrev,
376 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000377 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000378 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000379 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
380 }
381
Anna Zaks0d6989b2012-06-22 02:04:31 +0000382 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
383 const Stmt *Stmt) {
384 // Did not track -> relinquished. Other state (allocated) -> relinquished.
385 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
386 isa<ObjCPropertyRefExpr>(Stmt)) &&
387 (S && S->isRelinquished()) &&
388 (!SPrev || !SPrev->isRelinquished()));
389 }
390
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000391 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
392 const Stmt *Stmt) {
393 // If the expression is not a call, and the state change is
394 // released -> allocated, it must be the realloc return value
395 // check. If we have to handle more cases here, it might be cleaner just
396 // to track this extra bit in the state itself.
397 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
398 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000399 }
400
401 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
402 const ExplodedNode *PrevN,
403 BugReporterContext &BRC,
404 BugReport &BR);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000405
406 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
407 const ExplodedNode *EndPathNode,
408 BugReport &BR) {
409 if (!IsLeak)
410 return 0;
411
412 PathDiagnosticLocation L =
413 PathDiagnosticLocation::createEndOfPath(EndPathNode,
414 BRC.getSourceManager());
415 // Do not add the statement itself as a range in case of leak.
416 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
417 }
418
Anna Zakscba4f292012-03-16 23:24:20 +0000419 private:
420 class StackHintGeneratorForReallocationFailed
421 : public StackHintGeneratorForSymbol {
422 public:
423 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
424 : StackHintGeneratorForSymbol(S, M) {}
425
426 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rosec102b352012-09-22 01:24:42 +0000427 // Printed parameters start at 1, not 0.
428 ++ArgIndex;
429
Anna Zakscba4f292012-03-16 23:24:20 +0000430 SmallString<200> buf;
431 llvm::raw_svector_ostream os(buf);
432
Jordan Rosec102b352012-09-22 01:24:42 +0000433 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
434 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000435
436 return os.str();
437 }
438
439 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000440 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000441 }
442 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000443 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000444};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000445} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000446
Jordan Rose0c153cb2012-11-02 01:54:06 +0000447REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
448REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000449
Anna Zaks67291b92012-11-13 03:18:01 +0000450// A map from the freed symbol to the symbol representing the return value of
451// the free function.
452REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
453
Anna Zaksbb1ef902012-02-11 21:02:35 +0000454namespace {
455class StopTrackingCallback : public SymbolVisitor {
456 ProgramStateRef state;
457public:
458 StopTrackingCallback(ProgramStateRef st) : state(st) {}
459 ProgramStateRef getState() const { return state; }
460
461 bool VisitSymbol(SymbolRef sym) {
462 state = state->remove<RegionState>(sym);
463 return true;
464 }
465};
466} // end anonymous namespace
467
Anna Zaks3d348342012-02-14 21:55:24 +0000468void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000469 if (II_malloc)
470 return;
471 II_malloc = &Ctx.Idents.get("malloc");
472 II_free = &Ctx.Idents.get("free");
473 II_realloc = &Ctx.Idents.get("realloc");
474 II_reallocf = &Ctx.Idents.get("reallocf");
475 II_calloc = &Ctx.Idents.get("calloc");
476 II_valloc = &Ctx.Idents.get("valloc");
477 II_strdup = &Ctx.Idents.get("strdup");
478 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000479}
480
Anna Zaks3d348342012-02-14 21:55:24 +0000481bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks46d01602012-05-18 01:16:10 +0000482 if (isFreeFunction(FD, C))
483 return true;
484
485 if (isAllocationFunction(FD, C))
486 return true;
487
Anton Yartsev13df0362013-03-25 01:35:45 +0000488 if (isStandardNewDelete(FD, C))
489 return true;
490
Anna Zaks46d01602012-05-18 01:16:10 +0000491 return false;
492}
493
494bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
495 ASTContext &C) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000496 if (!FD)
497 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000498
Jordan Rose6cd16c52012-07-10 23:13:01 +0000499 if (FD->getKind() == Decl::Function) {
500 IdentifierInfo *FunI = FD->getIdentifier();
501 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000502
Jordan Rose6cd16c52012-07-10 23:13:01 +0000503 if (FunI == II_malloc || FunI == II_realloc ||
504 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
505 FunI == II_strdup || FunI == II_strndup)
506 return true;
507 }
Anna Zaks3d348342012-02-14 21:55:24 +0000508
Anna Zaks46d01602012-05-18 01:16:10 +0000509 if (Filter.CMallocOptimistic && FD->hasAttrs())
510 for (specific_attr_iterator<OwnershipAttr>
511 i = FD->specific_attr_begin<OwnershipAttr>(),
512 e = FD->specific_attr_end<OwnershipAttr>();
513 i != e; ++i)
514 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
515 return true;
516 return false;
517}
518
519bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
520 if (!FD)
521 return false;
522
Jordan Rose6cd16c52012-07-10 23:13:01 +0000523 if (FD->getKind() == Decl::Function) {
524 IdentifierInfo *FunI = FD->getIdentifier();
525 initIdentifierInfo(C);
Anna Zaks46d01602012-05-18 01:16:10 +0000526
Jordan Rose6cd16c52012-07-10 23:13:01 +0000527 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
528 return true;
529 }
Anna Zaks3d348342012-02-14 21:55:24 +0000530
Anna Zaks46d01602012-05-18 01:16:10 +0000531 if (Filter.CMallocOptimistic && FD->hasAttrs())
532 for (specific_attr_iterator<OwnershipAttr>
533 i = FD->specific_attr_begin<OwnershipAttr>(),
534 e = FD->specific_attr_end<OwnershipAttr>();
535 i != e; ++i)
536 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
537 (*i)->getOwnKind() == OwnershipAttr::Holds)
538 return true;
Anna Zaks3d348342012-02-14 21:55:24 +0000539 return false;
540}
541
Anton Yartsev8b662702013-03-28 16:10:38 +0000542// Tells if the callee is one of the following:
543// 1) A global non-placement new/delete operator function.
544// 2) A global placement operator function with the single placement argument
545// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000546bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
547 ASTContext &C) const {
548 if (!FD)
549 return false;
550
551 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
552 if (Kind != OO_New && Kind != OO_Array_New &&
553 Kind != OO_Delete && Kind != OO_Array_Delete)
554 return false;
555
Anton Yartsev8b662702013-03-28 16:10:38 +0000556 // Skip all operator new/delete methods.
557 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000558 return false;
559
560 // Return true if tested operator is a standard placement nothrow operator.
561 if (FD->getNumParams() == 2) {
562 QualType T = FD->getParamDecl(1)->getType();
563 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
564 return II->getName().equals("nothrow_t");
565 }
566
567 // Skip placement operators.
568 if (FD->getNumParams() != 1 || FD->isVariadic())
569 return false;
570
571 // One of the standard new/new[]/delete/delete[] non-placement operators.
572 return true;
573}
574
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000575void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000576 if (C.wasInlined)
577 return;
578
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000579 const FunctionDecl *FD = C.getCalleeDecl(CE);
580 if (!FD)
581 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000582
Anna Zaks40a7eb32012-02-22 19:24:52 +0000583 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000584 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000585
586 if (FD->getKind() == Decl::Function) {
587 initIdentifierInfo(C.getASTContext());
588 IdentifierInfo *FunI = FD->getIdentifier();
589
Anton Yartseve3377fb2013-04-04 23:46:29 +0000590 if (FunI == II_malloc || FunI == II_valloc) {
591 if (CE->getNumArgs() < 1)
592 return;
593 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
594 } else if (FunI == II_realloc) {
595 State = ReallocMem(C, CE, false);
596 } else if (FunI == II_reallocf) {
597 State = ReallocMem(C, CE, true);
598 } else if (FunI == II_calloc) {
599 State = CallocMem(C, CE);
600 } else if (FunI == II_free) {
601 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
602 } else if (FunI == II_strdup) {
603 State = MallocUpdateRefState(C, CE, State);
604 } else if (FunI == II_strndup) {
605 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev13df0362013-03-25 01:35:45 +0000606 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000607 else if (isStandardNewDelete(FD, C.getASTContext())) {
608 // Process direct calls to operator new/new[]/delete/delete[] functions
609 // as distinct from new/new[]/delete/delete[] expressions that are
610 // processed by the checkPostStmt callbacks for CXXNewExpr and
611 // CXXDeleteExpr.
612 OverloadedOperatorKind K = FD->getOverloadedOperator();
613 if (K == OO_New)
614 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
615 AF_CXXNew);
616 else if (K == OO_Array_New)
617 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
618 AF_CXXNewArray);
619 else if (K == OO_Delete || K == OO_Array_Delete)
620 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
621 else
622 llvm_unreachable("not a new/delete operator");
Jordan Rose6cd16c52012-07-10 23:13:01 +0000623 }
624 }
625
Anton Yartsev05789592013-03-28 17:05:19 +0000626 if (Filter.CMallocOptimistic || Filter.CMismatchedDeallocatorChecker) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000627 // Check all the attributes, if there are any.
628 // There can be multiple of these attributes.
629 if (FD->hasAttrs())
630 for (specific_attr_iterator<OwnershipAttr>
631 i = FD->specific_attr_begin<OwnershipAttr>(),
632 e = FD->specific_attr_end<OwnershipAttr>();
633 i != e; ++i) {
634 switch ((*i)->getOwnKind()) {
635 case OwnershipAttr::Returns:
636 State = MallocMemReturnsAttr(C, CE, *i);
637 break;
638 case OwnershipAttr::Takes:
639 case OwnershipAttr::Holds:
640 State = FreeMemAttr(C, CE, *i);
641 break;
642 }
643 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000644 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000645 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000646}
647
Anton Yartsev13df0362013-03-25 01:35:45 +0000648void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
649 CheckerContext &C) const {
650
651 if (NE->getNumPlacementArgs())
652 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
653 E = NE->placement_arg_end(); I != E; ++I)
654 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
655 checkUseAfterFree(Sym, C, *I);
656
Anton Yartsev13df0362013-03-25 01:35:45 +0000657 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
658 return;
659
660 ProgramStateRef State = C.getState();
661 // The return value from operator new is bound to a specified initialization
662 // value (if any) and we don't want to loose this value. So we call
663 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
664 // existing binding.
Anton Yartsev05789592013-03-28 17:05:19 +0000665 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
666 : AF_CXXNew);
Anton Yartsev13df0362013-03-25 01:35:45 +0000667 C.addTransition(State);
668}
669
670void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
671 CheckerContext &C) const {
672
Anton Yartsev05789592013-03-28 17:05:19 +0000673 if (!Filter.CNewDeleteChecker)
Anton Yartsev13df0362013-03-25 01:35:45 +0000674 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
675 checkUseAfterFree(Sym, C, DE->getArgument());
676
Anton Yartsev13df0362013-03-25 01:35:45 +0000677 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
678 return;
679
680 ProgramStateRef State = C.getState();
681 bool ReleasedAllocated;
682 State = FreeMemAux(C, DE->getArgument(), DE, State,
683 /*Hold*/false, ReleasedAllocated);
684
685 C.addTransition(State);
686}
687
Jordan Rose613f3c02013-03-09 00:59:10 +0000688static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
689 // If the first selector piece is one of the names below, assume that the
690 // object takes ownership of the memory, promising to eventually deallocate it
691 // with free().
692 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
693 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
694 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
695 if (FirstSlot == "dataWithBytesNoCopy" ||
696 FirstSlot == "initWithBytesNoCopy" ||
697 FirstSlot == "initWithCharactersNoCopy")
698 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000699
700 return false;
701}
702
Jordan Rose613f3c02013-03-09 00:59:10 +0000703static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
704 Selector S = Call.getSelector();
705
706 // FIXME: We should not rely on fully-constrained symbols being folded.
707 for (unsigned i = 1; i < S.getNumArgs(); ++i)
708 if (S.getNameForSlot(i).equals("freeWhenDone"))
709 return !Call.getArgSVal(i).isZeroConstant();
710
711 return None;
712}
713
Anna Zaks67291b92012-11-13 03:18:01 +0000714void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
715 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +0000716 if (C.wasInlined)
717 return;
718
Jordan Rose613f3c02013-03-09 00:59:10 +0000719 if (!isKnownDeallocObjCMethodName(Call))
720 return;
Anna Zaks67291b92012-11-13 03:18:01 +0000721
Jordan Rose613f3c02013-03-09 00:59:10 +0000722 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
723 if (!*FreeWhenDone)
724 return;
725
726 bool ReleasedAllocatedMemory;
727 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
728 Call.getOriginExpr(), C.getState(),
729 /*Hold=*/true, ReleasedAllocatedMemory,
730 /*RetNullOnFailure=*/true);
731
732 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +0000733}
734
Richard Smith852e9ce2013-11-27 01:46:48 +0000735ProgramStateRef
736MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
737 const OwnershipAttr *Att) const {
738 if (Att->getModule() != II_malloc)
Anna Zaks40a7eb32012-02-22 19:24:52 +0000739 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000740
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000741 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000742 if (I != E) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000743 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekd21139a2010-07-31 01:52:11 +0000744 }
Anna Zaks40a7eb32012-02-22 19:24:52 +0000745 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekd21139a2010-07-31 01:52:11 +0000746}
747
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000748ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000749 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000750 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000751 ProgramStateRef State,
752 AllocationFamily Family) {
Anna Zaks3563fde2012-06-07 03:57:32 +0000753
754 // Bind the return value to the symbolic value from the heap region.
755 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
756 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +0000757 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +0000758 SValBuilder &svalBuilder = C.getSValBuilder();
759 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000760 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
761 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +0000762 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000763
Anna Zaksd5157482012-02-15 00:11:22 +0000764 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000765 if (!RetVal.getAs<Loc>())
Anna Zaksd5157482012-02-15 00:11:22 +0000766 return 0;
767
Jordy Rose674bd552010-07-04 00:00:41 +0000768 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +0000769 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000770
Jordy Rose674bd552010-07-04 00:00:41 +0000771 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +0000772 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +0000773 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +0000774 if (!R)
Anna Zaks31886862012-02-10 01:11:00 +0000775 return 0;
David Blaikie05785d12013-02-20 22:23:23 +0000776 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000777 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000778 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +0000779 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +0000780 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +0000781 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +0000782
Anton Yartsev05789592013-03-28 17:05:19 +0000783 State = State->assume(extentMatchesSize, true);
784 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +0000785 }
Ted Kremenek90af9092010-12-02 07:49:45 +0000786
Anton Yartsev05789592013-03-28 17:05:19 +0000787 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000788}
789
790ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +0000791 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +0000792 ProgramStateRef State,
793 AllocationFamily Family) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000794 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +0000795 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +0000796
797 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000798 if (!retVal.getAs<Loc>())
Anna Zaks40a7eb32012-02-22 19:24:52 +0000799 return 0;
800
Ted Kremenek90af9092010-12-02 07:49:45 +0000801 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000802 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +0000803
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000804 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +0000805 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000806}
807
Anna Zaks40a7eb32012-02-22 19:24:52 +0000808ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
809 const CallExpr *CE,
Richard Smith852e9ce2013-11-27 01:46:48 +0000810 const OwnershipAttr *Att) const {
811 if (Att->getModule() != II_malloc)
Anna Zaks40a7eb32012-02-22 19:24:52 +0000812 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000813
Anna Zaks8dc53af2012-03-01 22:06:06 +0000814 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000815 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +0000816
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000817 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
818 I != E; ++I) {
Anna Zaks8dc53af2012-03-01 22:06:06 +0000819 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000820 Att->getOwnKind() == OwnershipAttr::Holds,
821 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +0000822 if (StateI)
823 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000824 }
Anna Zaks8dc53af2012-03-01 22:06:06 +0000825 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000826}
827
Ted Kremenek49b1e382012-01-26 21:29:00 +0000828ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +0000829 const CallExpr *CE,
830 ProgramStateRef state,
831 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000832 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000833 bool &ReleasedAllocated,
834 bool ReturnsNullOnFailure) const {
Anna Zaksb508d292012-04-10 23:41:11 +0000835 if (CE->getNumArgs() < (Num + 1))
836 return 0;
837
Anna Zaks67291b92012-11-13 03:18:01 +0000838 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
839 ReleasedAllocated, ReturnsNullOnFailure);
840}
841
Anna Zaksa14c1d02012-11-13 19:47:40 +0000842/// Checks if the previous call to free on the given symbol failed - if free
843/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +0000844static bool didPreviousFreeFail(ProgramStateRef State,
845 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +0000846 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +0000847 if (Ret) {
848 assert(*Ret && "We should not store the null return symbol");
849 ConstraintManager &CMgr = State->getConstraintManager();
850 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +0000851 RetStatusSymbol = *Ret;
852 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +0000853 }
Anna Zaksa14c1d02012-11-13 19:47:40 +0000854 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000855}
856
Anton Yartsev05789592013-03-28 17:05:19 +0000857AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +0000858 const Stmt *S) const {
859 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +0000860 return AF_None;
861
Anton Yartseve3377fb2013-04-04 23:46:29 +0000862 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +0000863 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000864
865 if (!FD)
866 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
867
Anton Yartsev05789592013-03-28 17:05:19 +0000868 ASTContext &Ctx = C.getASTContext();
869
Anton Yartseve3377fb2013-04-04 23:46:29 +0000870 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx))
Anton Yartsev05789592013-03-28 17:05:19 +0000871 return AF_Malloc;
872
873 if (isStandardNewDelete(FD, Ctx)) {
874 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +0000875 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +0000876 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000877 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +0000878 return AF_CXXNewArray;
879 }
880
881 return AF_None;
882 }
883
Anton Yartseve3377fb2013-04-04 23:46:29 +0000884 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
885 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
886
887 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +0000888 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
889
Anton Yartseve3377fb2013-04-04 23:46:29 +0000890 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +0000891 return AF_Malloc;
892
893 return AF_None;
894}
895
896bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
897 const Expr *E) const {
898 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
899 // FIXME: This doesn't handle indirect calls.
900 const FunctionDecl *FD = CE->getDirectCallee();
901 if (!FD)
902 return false;
903
904 os << *FD;
905 if (!FD->isOverloadedOperator())
906 os << "()";
907 return true;
908 }
909
910 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
911 if (Msg->isInstanceMessage())
912 os << "-";
913 else
914 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +0000915 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +0000916 return true;
917 }
918
919 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
920 os << "'"
921 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
922 << "'";
923 return true;
924 }
925
926 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
927 os << "'"
928 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
929 << "'";
930 return true;
931 }
932
933 return false;
934}
935
936void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
937 const Expr *E) const {
938 AllocationFamily Family = getAllocationFamily(C, E);
939
940 switch(Family) {
941 case AF_Malloc: os << "malloc()"; return;
942 case AF_CXXNew: os << "'new'"; return;
943 case AF_CXXNewArray: os << "'new[]'"; return;
944 case AF_None: llvm_unreachable("not a deallocation expression");
945 }
946}
947
948void MallocChecker::printExpectedDeallocName(raw_ostream &os,
949 AllocationFamily Family) const {
950 switch(Family) {
951 case AF_Malloc: os << "free()"; return;
952 case AF_CXXNew: os << "'delete'"; return;
953 case AF_CXXNewArray: os << "'delete[]'"; return;
954 case AF_None: llvm_unreachable("suspicious AF_None argument");
955 }
956}
957
Anna Zaks0d6989b2012-06-22 02:04:31 +0000958ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
959 const Expr *ArgExpr,
960 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000961 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000962 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000963 bool &ReleasedAllocated,
964 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +0000965
Anna Zaks67291b92012-11-13 03:18:01 +0000966 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +0000967 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zaks31886862012-02-10 01:11:00 +0000968 return 0;
David Blaikie2fdacbc2013-02-20 05:52:05 +0000969 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000970
971 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000972 if (!location.getAs<Loc>())
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000973 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000974
Anna Zaksad01ef52012-02-14 00:26:13 +0000975 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000976 ProgramStateRef notNullState, nullState;
Anna Zaks67291b92012-11-13 03:18:01 +0000977 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000978 if (nullState && !notNullState)
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000979 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000980
Jordy Rose3597b212010-06-07 19:32:37 +0000981 // Unknown values could easily be okay
982 // Undefined values are handled elsewhere
983 if (ArgVal.isUnknownOrUndef())
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000984 return 0;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000985
Jordy Rose3597b212010-06-07 19:32:37 +0000986 const MemRegion *R = ArgVal.getAsRegion();
987
988 // Nonlocs can't be freed, of course.
989 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
990 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +0000991 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000992 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +0000993 }
994
995 R = R->StripCasts();
996
997 // Blocks might show up as heap data, but should not be free()d
998 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +0000999 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001000 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +00001001 }
1002
1003 const MemSpaceRegion *MS = R->getMemorySpace();
1004
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001005 // Parameters, locals, statics, globals, and memory returned by alloca()
1006 // shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001007 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1008 // FIXME: at the time this code was written, malloc() regions were
1009 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1010 // This means that there isn't actually anything from HeapSpaceRegion
1011 // that should be freed, even though we allow it here.
1012 // Of course, free() can work on memory allocated outside the current
1013 // function, so UnknownSpaceRegion is always a possibility.
1014 // False negatives are better than false positives.
1015
Anton Yartsev05789592013-03-28 17:05:19 +00001016 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001017 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +00001018 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001019
1020 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001021 // Various cases could lead to non-symbol values here.
1022 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001023 if (!SrBase)
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001024 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +00001025
Anna Zaksc89ad072013-02-07 23:05:47 +00001026 SymbolRef SymBase = SrBase->getSymbol();
1027 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001028 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001029
Anton Yartseve3377fb2013-04-04 23:46:29 +00001030 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001031
Anna Zaks93a21a82013-04-09 00:30:28 +00001032 // Check for double free first.
1033 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001034 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1035 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1036 SymBase, PreviousRetStatusSymbol);
1037 return 0;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001038
Anna Zaks93a21a82013-04-09 00:30:28 +00001039 // If the pointer is allocated or escaped, but we are now trying to free it,
1040 // check that the call to free is proper.
1041 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1042
1043 // Check if an expected deallocation function matches the real one.
1044 bool DeallocMatchesAlloc =
1045 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1046 if (!DeallocMatchesAlloc) {
1047 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001048 ParentExpr, RsBase, SymBase, Hold);
Anna Zaks93a21a82013-04-09 00:30:28 +00001049 return 0;
1050 }
1051
1052 // Check if the memory location being freed is the actual location
1053 // allocated, or an offset.
1054 RegionOffset Offset = R->getAsOffset();
1055 if (Offset.isValid() &&
1056 !Offset.hasSymbolicOffset() &&
1057 Offset.getOffset() != 0) {
1058 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1059 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1060 AllocExpr);
1061 return 0;
1062 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001063 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001064 }
1065
Jordan Rose2f8b0222013-08-15 17:22:06 +00001066 ReleasedAllocated = (RsBase != 0) && RsBase->isAllocated();
Anna Zaksfe6eb672012-08-24 02:28:20 +00001067
Anna Zaksa14c1d02012-11-13 19:47:40 +00001068 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001069 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001070
Anna Zaks67291b92012-11-13 03:18:01 +00001071 // Keep track of the return value. If it is NULL, we will know that free
1072 // failed.
1073 if (ReturnsNullOnFailure) {
1074 SVal RetVal = C.getSVal(ParentExpr);
1075 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1076 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001077 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1078 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001079 }
1080 }
1081
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001082 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1083 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001084 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001085 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001086 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001087 RefState::getRelinquished(Family,
1088 ParentExpr));
1089
1090 return State->set<RegionState>(SymBase,
1091 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001092}
1093
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001094bool MallocChecker::isTrackedByCurrentChecker(AllocationFamily Family) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001095 switch (Family) {
1096 case AF_Malloc: {
1097 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic)
1098 return false;
Anton Yartsev2f910042013-04-05 02:12:04 +00001099 return true;
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001100 }
1101 case AF_CXXNew:
1102 case AF_CXXNewArray: {
Anton Yartsev7af0aa82013-04-12 23:25:40 +00001103 if (!Filter.CNewDeleteChecker)
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001104 return false;
Anton Yartsev2f910042013-04-05 02:12:04 +00001105 return true;
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001106 }
1107 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001108 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001109 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001110 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001111 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001112}
1113
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001114bool
1115MallocChecker::isTrackedByCurrentChecker(CheckerContext &C,
1116 const Stmt *AllocDeallocStmt) const {
1117 return isTrackedByCurrentChecker(getAllocationFamily(C, AllocDeallocStmt));
Anton Yartseve3377fb2013-04-04 23:46:29 +00001118}
1119
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001120bool MallocChecker::isTrackedByCurrentChecker(CheckerContext &C,
1121 SymbolRef Sym) const {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001122
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001123 const RefState *RS = C.getState()->get<RegionState>(Sym);
1124 assert(RS);
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001125 return isTrackedByCurrentChecker(RS->getAllocationFamily());
Anton Yartseve3377fb2013-04-04 23:46:29 +00001126}
1127
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001128bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001129 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001130 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001131 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001132 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001133 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001134 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001135 else
1136 return false;
1137
1138 return true;
1139}
1140
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001141bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001142 const MemRegion *MR) {
1143 switch (MR->getKind()) {
1144 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001145 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001146 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001147 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001148 else
1149 os << "the address of a function";
1150 return true;
1151 }
1152 case MemRegion::BlockTextRegionKind:
1153 os << "block text";
1154 return true;
1155 case MemRegion::BlockDataRegionKind:
1156 // FIXME: where the block came from?
1157 os << "a block";
1158 return true;
1159 default: {
1160 const MemSpaceRegion *MS = MR->getMemorySpace();
1161
Anna Zaks8158ef02012-01-04 23:54:01 +00001162 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001163 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1164 const VarDecl *VD;
1165 if (VR)
1166 VD = VR->getDecl();
1167 else
1168 VD = NULL;
1169
1170 if (VD)
1171 os << "the address of the local variable '" << VD->getName() << "'";
1172 else
1173 os << "the address of a local stack variable";
1174 return true;
1175 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001176
1177 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001178 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1179 const VarDecl *VD;
1180 if (VR)
1181 VD = VR->getDecl();
1182 else
1183 VD = NULL;
1184
1185 if (VD)
1186 os << "the address of the parameter '" << VD->getName() << "'";
1187 else
1188 os << "the address of a parameter";
1189 return true;
1190 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001191
1192 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001193 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1194 const VarDecl *VD;
1195 if (VR)
1196 VD = VR->getDecl();
1197 else
1198 VD = NULL;
1199
1200 if (VD) {
1201 if (VD->isStaticLocal())
1202 os << "the address of the static variable '" << VD->getName() << "'";
1203 else
1204 os << "the address of the global variable '" << VD->getName() << "'";
1205 } else
1206 os << "the address of a global variable";
1207 return true;
1208 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001209
1210 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001211 }
1212 }
1213}
1214
Anton Yartsev05789592013-03-28 17:05:19 +00001215void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1216 SourceRange Range,
1217 const Expr *DeallocExpr) const {
1218
1219 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1220 !Filter.CNewDeleteChecker)
1221 return;
1222
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001223 if (!isTrackedByCurrentChecker(C, DeallocExpr))
Anton Yartseve3377fb2013-04-04 23:46:29 +00001224 return;
1225
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001226 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose3597b212010-06-07 19:32:37 +00001227 if (!BT_BadFree)
Anna Zaks546c49c2012-02-16 22:26:12 +00001228 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose3597b212010-06-07 19:32:37 +00001229
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001230 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001231 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001232
Jordy Rose3597b212010-06-07 19:32:37 +00001233 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001234 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1235 MR = ER->getSuperRegion();
1236
1237 if (MR && isa<AllocaRegion>(MR))
1238 os << "Memory allocated by alloca() should not be deallocated";
1239 else {
1240 os << "Argument to ";
1241 if (!printAllocDeallocName(os, C, DeallocExpr))
1242 os << "deallocator";
1243
1244 os << " is ";
1245 bool Summarized = MR ? SummarizeRegion(os, MR)
1246 : SummarizeValue(os, ArgVal);
1247 if (Summarized)
1248 os << ", which is not memory allocated by ";
Jordy Rose3597b212010-06-07 19:32:37 +00001249 else
Anton Yartsev05789592013-03-28 17:05:19 +00001250 os << "not memory allocated by ";
1251
1252 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose3597b212010-06-07 19:32:37 +00001253 }
Anton Yartsev05789592013-03-28 17:05:19 +00001254
Anna Zaks3a6bdf82011-08-17 23:00:25 +00001255 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001256 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001257 R->addRange(Range);
Jordan Rosee10d5a72012-11-02 01:53:40 +00001258 C.emitReport(R);
Jordy Rose3597b212010-06-07 19:32:37 +00001259 }
1260}
1261
Anton Yartseve3377fb2013-04-04 23:46:29 +00001262void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1263 SourceRange Range,
1264 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001265 const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001266 SymbolRef Sym,
1267 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001268
1269 if (!Filter.CMismatchedDeallocatorChecker)
1270 return;
1271
1272 if (ExplodedNode *N = C.generateSink()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001273 if (!BT_MismatchedDealloc)
1274 BT_MismatchedDealloc.reset(new BugType("Bad deallocator",
1275 "Memory Error"));
Anton Yartsev05789592013-03-28 17:05:19 +00001276
1277 SmallString<100> buf;
1278 llvm::raw_svector_ostream os(buf);
1279
1280 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1281 SmallString<20> AllocBuf;
1282 llvm::raw_svector_ostream AllocOs(AllocBuf);
1283 SmallString<20> DeallocBuf;
1284 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1285
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001286 if (OwnershipTransferred) {
1287 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1288 os << DeallocOs.str() << " cannot";
1289 else
1290 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001291
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001292 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001293
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001294 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1295 os << " allocated by " << AllocOs.str();
1296 } else {
1297 os << "Memory";
1298 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1299 os << " allocated by " << AllocOs.str();
1300
1301 os << " should be deallocated by ";
1302 printExpectedDeallocName(os, RS->getAllocationFamily());
1303
1304 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1305 os << ", not " << DeallocOs.str();
1306 }
Anton Yartsev05789592013-03-28 17:05:19 +00001307
Anton Yartseve3377fb2013-04-04 23:46:29 +00001308 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001309 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001310 R->addRange(Range);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001311 R->addVisitor(new MallocBugVisitor(Sym));
Anton Yartsev05789592013-03-28 17:05:19 +00001312 C.emitReport(R);
1313 }
1314}
1315
Anna Zaksc89ad072013-02-07 23:05:47 +00001316void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001317 SourceRange Range, const Expr *DeallocExpr,
1318 const Expr *AllocExpr) const {
1319
1320 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1321 !Filter.CNewDeleteChecker)
1322 return;
1323
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001324 if (!isTrackedByCurrentChecker(C, AllocExpr))
Anton Yartseve3377fb2013-04-04 23:46:29 +00001325 return;
1326
Anna Zaksc89ad072013-02-07 23:05:47 +00001327 ExplodedNode *N = C.generateSink();
1328 if (N == NULL)
1329 return;
1330
1331 if (!BT_OffsetFree)
1332 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1333
1334 SmallString<100> buf;
1335 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001336 SmallString<20> AllocNameBuf;
1337 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001338
1339 const MemRegion *MR = ArgVal.getAsRegion();
1340 assert(MR && "Only MemRegion based symbols can have offset free errors");
1341
1342 RegionOffset Offset = MR->getAsOffset();
1343 assert((Offset.isValid() &&
1344 !Offset.hasSymbolicOffset() &&
1345 Offset.getOffset() != 0) &&
1346 "Only symbols with a valid offset can have offset free errors");
1347
1348 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1349
Anton Yartsev05789592013-03-28 17:05:19 +00001350 os << "Argument to ";
1351 if (!printAllocDeallocName(os, C, DeallocExpr))
1352 os << "deallocator";
1353 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001354 << offsetBytes
1355 << " "
1356 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001357 << " from the start of ";
1358 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1359 os << "memory allocated by " << AllocNameOs.str();
1360 else
1361 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001362
1363 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1364 R->markInteresting(MR->getBaseRegion());
1365 R->addRange(Range);
1366 C.emitReport(R);
1367}
1368
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001369void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1370 SymbolRef Sym) const {
1371
Anton Yartsev05789592013-03-28 17:05:19 +00001372 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1373 !Filter.CNewDeleteChecker)
1374 return;
1375
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001376 if (!isTrackedByCurrentChecker(C, Sym))
Anton Yartseve3377fb2013-04-04 23:46:29 +00001377 return;
1378
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001379 if (ExplodedNode *N = C.generateSink()) {
1380 if (!BT_UseFree)
1381 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1382
1383 BugReport *R = new BugReport(*BT_UseFree,
1384 "Use of memory after it is freed", N);
1385
1386 R->markInteresting(Sym);
1387 R->addRange(Range);
1388 R->addVisitor(new MallocBugVisitor(Sym));
1389 C.emitReport(R);
1390 }
1391}
1392
1393void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1394 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001395 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001396
Anton Yartsev05789592013-03-28 17:05:19 +00001397 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1398 !Filter.CNewDeleteChecker)
1399 return;
1400
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001401 if (!isTrackedByCurrentChecker(C, Sym))
Anton Yartseve3377fb2013-04-04 23:46:29 +00001402 return;
1403
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001404 if (ExplodedNode *N = C.generateSink()) {
1405 if (!BT_DoubleFree)
1406 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1407
1408 BugReport *R = new BugReport(*BT_DoubleFree,
1409 (Released ? "Attempt to free released memory"
1410 : "Attempt to free non-owned memory"),
1411 N);
1412 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001413 R->markInteresting(Sym);
1414 if (PrevSym)
1415 R->markInteresting(PrevSym);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001416 R->addVisitor(new MallocBugVisitor(Sym));
1417 C.emitReport(R);
1418 }
1419}
1420
Jordan Rose656fdd52014-01-08 18:46:55 +00001421void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1422
1423 if (!Filter.CNewDeleteChecker)
1424 return;
1425
1426 if (!isTrackedByCurrentChecker(C, Sym))
1427 return;
1428
1429 if (ExplodedNode *N = C.generateSink()) {
1430 if (!BT_DoubleDelete)
1431 BT_DoubleDelete.reset(new BugType("Double delete", "Memory Error"));
1432
1433 BugReport *R = new BugReport(*BT_DoubleDelete,
1434 "Attempt to delete released memory", N);
1435
1436 R->markInteresting(Sym);
1437 R->addVisitor(new MallocBugVisitor(Sym));
1438 C.emitReport(R);
1439 }
1440}
1441
Anna Zaks40a7eb32012-02-22 19:24:52 +00001442ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1443 const CallExpr *CE,
1444 bool FreesOnFail) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001445 if (CE->getNumArgs() < 2)
1446 return 0;
1447
Ted Kremenek49b1e382012-01-26 21:29:00 +00001448 ProgramStateRef state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +00001449 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001450 const LocationContext *LCtx = C.getLocationContext();
Anna Zaks31886862012-02-10 01:11:00 +00001451 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001452 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks40a7eb32012-02-22 19:24:52 +00001453 return 0;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001454 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001455
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001456 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001457
Ted Kremenek90af9092010-12-02 07:49:45 +00001458 DefinedOrUnknownSVal PtrEQ =
1459 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001460
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001461 // Get the size argument. If there is no size arg then give up.
1462 const Expr *Arg1 = CE->getArg(1);
1463 if (!Arg1)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001464 return 0;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001465
1466 // Get the value of the size argument.
Anna Zaks31886862012-02-10 01:11:00 +00001467 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001468 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks40a7eb32012-02-22 19:24:52 +00001469 return 0;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001470 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001471
1472 // Compare the size argument to 0.
1473 DefinedOrUnknownSVal SizeZero =
1474 svalBuilder.evalEQ(state, Arg1Val,
1475 svalBuilder.makeIntValWithPtrWidth(0, false));
1476
Anna Zaksd56c8792012-02-13 18:05:39 +00001477 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1478 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1479 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1480 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1481 // We only assume exceptional states if they are definitely true; if the
1482 // state is under-constrained, assume regular realloc behavior.
1483 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1484 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1485
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001486 // If the ptr is NULL and the size is not 0, the call is equivalent to
1487 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001488 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001489 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001490 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001491 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001492 }
1493
Anna Zaksd56c8792012-02-13 18:05:39 +00001494 if (PrtIsNull && SizeIsZero)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001495 return 0;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001496
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001497 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001498 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001499 SymbolRef FromPtr = arg0Val.getAsSymbol();
1500 SVal RetVal = state->getSVal(CE, LCtx);
1501 SymbolRef ToPtr = RetVal.getAsSymbol();
1502 if (!FromPtr || !ToPtr)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001503 return 0;
Anna Zaksd56c8792012-02-13 18:05:39 +00001504
Anna Zaksfe6eb672012-08-24 02:28:20 +00001505 bool ReleasedAllocated = false;
1506
Anna Zaksd56c8792012-02-13 18:05:39 +00001507 // If the size is 0, free the memory.
1508 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001509 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1510 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001511 // The semantics of the return value are:
1512 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001513 // to free() is returned. We just free the input pointer and do not add
1514 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001515 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001516 }
1517
1518 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001519 if (ProgramStateRef stateFree =
1520 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1521
Anna Zaksd56c8792012-02-13 18:05:39 +00001522 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1523 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001524 if (!stateRealloc)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001525 return 0;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001526
Anna Zaks75cfbb62012-09-12 22:57:34 +00001527 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1528 if (FreesOnFail)
1529 Kind = RPIsFreeOnFailure;
1530 else if (!ReleasedAllocated)
1531 Kind = RPDoNotTrackAfterFailure;
1532
Anna Zaksfe6eb672012-08-24 02:28:20 +00001533 // Record the info about the reallocated symbol so that we could properly
1534 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001535 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001536 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001537 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001538 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001539 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001540 }
Anna Zaks40a7eb32012-02-22 19:24:52 +00001541 return 0;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001542}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001543
Anna Zaks40a7eb32012-02-22 19:24:52 +00001544ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaksb508d292012-04-10 23:41:11 +00001545 if (CE->getNumArgs() < 2)
1546 return 0;
1547
Ted Kremenek49b1e382012-01-26 21:29:00 +00001548 ProgramStateRef state = C.getState();
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001549 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001550 const LocationContext *LCtx = C.getLocationContext();
1551 SVal count = state->getSVal(CE->getArg(0), LCtx);
1552 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001553 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1554 svalBuilder.getContext().getSizeType());
1555 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001556
Anna Zaks40a7eb32012-02-22 19:24:52 +00001557 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001558}
1559
Anna Zaksfc2e1532012-03-21 19:45:08 +00001560LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00001561MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1562 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00001563 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00001564 // Walk the ExplodedGraph backwards and find the first node that referred to
1565 // the tracked symbol.
1566 const ExplodedNode *AllocNode = N;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001567 const MemRegion *ReferenceRegion = 0;
Anna Zaksdf901a42012-02-23 21:38:21 +00001568
1569 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00001570 ProgramStateRef State = N->getState();
1571 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00001572 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001573
1574 // Find the most recent expression bound to the symbol in the current
1575 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00001576 if (!ReferenceRegion) {
1577 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1578 SVal Val = State->getSVal(MR);
1579 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00001580 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00001581 // Do not show local variables belonging to a function other than
1582 // where the error is reported.
1583 if (!VR ||
1584 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1585 ReferenceRegion = MR;
1586 }
1587 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00001588 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00001589
Anna Zaks43ffba22012-02-27 23:40:55 +00001590 // Allocation node, is the last node in the current context in which the
1591 // symbol was tracked.
1592 if (N->getLocationContext() == LeakContext)
1593 AllocNode = N;
Anna Zaksdf901a42012-02-23 21:38:21 +00001594 N = N->pred_empty() ? NULL : *(N->pred_begin());
1595 }
1596
Anna Zaksa043d0c2013-01-08 00:25:29 +00001597 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00001598}
1599
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001600void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1601 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001602
1603 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
Jordan Rose26330562013-04-05 17:55:00 +00001604 !Filter.CNewDeleteLeaksChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00001605 return;
1606
Jordan Rose26330562013-04-05 17:55:00 +00001607 const RefState *RS = C.getState()->get<RegionState>(Sym);
1608 assert(RS && "cannot leak an untracked symbol");
1609 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +00001610 if (!isTrackedByCurrentChecker(Family))
Anton Yartsev6e499252013-04-05 02:25:02 +00001611 return;
1612
Jordan Rose26330562013-04-05 17:55:00 +00001613 // Special case for new and new[]; these are controlled by a separate checker
1614 // flag so that they can be selectively disabled.
1615 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
1616 if (!Filter.CNewDeleteLeaksChecker)
1617 return;
1618
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001619 assert(N);
1620 if (!BT_Leak) {
Anna Zaks546c49c2012-02-16 22:26:12 +00001621 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001622 // Leaks should not be reported if they are post-dominated by a sink:
1623 // (1) Sinks are higher importance bugs.
1624 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1625 // with __noreturn functions such as assert() or exit(). We choose not
1626 // to report leaks on such paths.
1627 BT_Leak->setSuppressOnSink(true);
1628 }
1629
Anna Zaksdf901a42012-02-23 21:38:21 +00001630 // Most bug reports are cached at the location where they occurred.
1631 // With leaks, we want to unique them by the location where they were
1632 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00001633 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaksa043d0c2013-01-08 00:25:29 +00001634 const ExplodedNode *AllocNode = 0;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001635 const MemRegion *Region = 0;
Anna Zaksa043d0c2013-01-08 00:25:29 +00001636 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1637
1638 ProgramPoint P = AllocNode->getLocation();
1639 const Stmt *AllocationStmt = 0;
David Blaikie87396b92013-02-21 22:23:56 +00001640 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001641 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00001642 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001643 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00001644 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00001645 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1646 C.getSourceManager(),
1647 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00001648
Anna Zaksfc2e1532012-03-21 19:45:08 +00001649 SmallString<200> buf;
1650 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001651 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00001652 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001653 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00001654 } else {
1655 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00001656 }
1657
Anna Zaksa043d0c2013-01-08 00:25:29 +00001658 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1659 LocUsedForUniqueing,
1660 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00001661 R->markInteresting(Sym);
Anna Zaks62cce9e2012-05-10 01:37:40 +00001662 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rosee10d5a72012-11-02 01:53:40 +00001663 C.emitReport(R);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001664}
1665
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00001666void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1667 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00001668{
Zhongxing Xubce831f2010-08-15 08:19:57 +00001669 if (!SymReaper.hasDeadSymbols())
1670 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00001671
Ted Kremenek49b1e382012-01-26 21:29:00 +00001672 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001673 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00001674 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001675
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001676 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00001677 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1678 if (SymReaper.isDead(I->first)) {
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001679 if (I->second.isAllocated())
Anna Zaks78edc2f2012-02-09 06:48:19 +00001680 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00001681 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001682 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00001683
Zhongxing Xuc7460962009-11-13 07:48:11 +00001684 }
1685 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001686
Anna Zaksd56c8792012-02-13 18:05:39 +00001687 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00001688 ReallocPairsTy RP = state->get<ReallocPairs>();
1689 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00001690 if (SymReaper.isDead(I->first) ||
1691 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00001692 state = state->remove<ReallocPairs>(I->first);
1693 }
1694 }
1695
Anna Zaks67291b92012-11-13 03:18:01 +00001696 // Cleanup the FreeReturnValue Map.
1697 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1698 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1699 if (SymReaper.isDead(I->first) ||
1700 SymReaper.isDead(I->second)) {
1701 state = state->remove<FreeReturnValue>(I->first);
1702 }
1703 }
1704
Anna Zaksdf901a42012-02-23 21:38:21 +00001705 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001706 ExplodedNode *N = C.getPredecessor();
1707 if (!Errors.empty()) {
1708 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1709 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper2341c0d2013-07-04 03:08:24 +00001710 for (SmallVectorImpl<SymbolRef>::iterator
1711 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001712 reportLeak(*I, N, C);
Anna Zaks78edc2f2012-02-09 06:48:19 +00001713 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001714 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001715
Anna Zaksdf901a42012-02-23 21:38:21 +00001716 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001717}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00001718
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001719void MallocChecker::checkPreCall(const CallEvent &Call,
1720 CheckerContext &C) const {
1721
Jordan Rose656fdd52014-01-08 18:46:55 +00001722 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
1723 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
1724 if (!Sym || checkDoubleDelete(Sym, C))
1725 return;
1726 }
1727
Anna Zaks46d01602012-05-18 01:16:10 +00001728 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001729 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
1730 const FunctionDecl *FD = FC->getDecl();
1731 if (!FD)
1732 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00001733
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001734 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1735 isFreeFunction(FD, C.getASTContext()))
1736 return;
Anna Zaks3d348342012-02-14 21:55:24 +00001737
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001738 if (Filter.CNewDeleteChecker &&
1739 isStandardNewDelete(FD, C.getASTContext()))
1740 return;
1741 }
1742
1743 // Check if the callee of a method is deleted.
1744 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
1745 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
1746 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
1747 return;
1748 }
1749
1750 // Check arguments for being used after free.
1751 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
1752 SVal ArgSVal = Call.getArgSVal(I);
1753 if (ArgSVal.getAs<Loc>()) {
1754 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00001755 if (!Sym)
1756 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001757 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00001758 return;
1759 }
1760 }
1761}
1762
Anna Zaksa1b227b2012-02-08 23:16:56 +00001763void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1764 const Expr *E = S->getRetValue();
1765 if (!E)
1766 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00001767
1768 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00001769 ProgramStateRef State = C.getState();
1770 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00001771 SymbolRef Sym = RetVal.getAsSymbol();
1772 if (!Sym)
1773 // If we are returning a field of the allocated struct or an array element,
1774 // the callee could still free the memory.
1775 // TODO: This logic should be a part of generic symbol escape callback.
1776 if (const MemRegion *MR = RetVal.getAsRegion())
1777 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1778 if (const SymbolicRegion *BMR =
1779 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1780 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00001781
Anna Zaks3aa52252012-02-11 21:44:39 +00001782 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00001783 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00001784 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00001785}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00001786
Anna Zaks9fe80982012-03-22 00:57:20 +00001787// TODO: Blocks should be either inlined or should call invalidate regions
1788// upon invocation. After that's in place, special casing here will not be
1789// needed.
1790void MallocChecker::checkPostStmt(const BlockExpr *BE,
1791 CheckerContext &C) const {
1792
1793 // Scan the BlockDecRefExprs for any object the retain count checker
1794 // may be tracking.
1795 if (!BE->getBlockDecl()->hasCaptures())
1796 return;
1797
1798 ProgramStateRef state = C.getState();
1799 const BlockDataRegion *R =
1800 cast<BlockDataRegion>(state->getSVal(BE,
1801 C.getLocationContext()).getAsRegion());
1802
1803 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1804 E = R->referenced_vars_end();
1805
1806 if (I == E)
1807 return;
1808
1809 SmallVector<const MemRegion*, 10> Regions;
1810 const LocationContext *LC = C.getLocationContext();
1811 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1812
1813 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00001814 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00001815 if (VR->getSuperRegion() == R) {
1816 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1817 }
1818 Regions.push_back(VR);
1819 }
1820
1821 state =
1822 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1823 Regions.data() + Regions.size()).getState();
1824 C.addTransition(state);
1825}
1826
Anna Zaks46d01602012-05-18 01:16:10 +00001827bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00001828 assert(Sym);
1829 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00001830 return (RS && RS->isReleased());
1831}
1832
1833bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1834 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00001835
Jordan Rose656fdd52014-01-08 18:46:55 +00001836 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001837 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1838 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00001839 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001840
Anna Zaksa1b227b2012-02-08 23:16:56 +00001841 return false;
1842}
1843
Jordan Rose656fdd52014-01-08 18:46:55 +00001844bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
1845
1846 if (isReleased(Sym, C)) {
1847 ReportDoubleDelete(C, Sym);
1848 return true;
1849 }
1850 return false;
1851}
1852
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00001853// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00001854void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1855 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00001856 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaksa1b227b2012-02-08 23:16:56 +00001857 if (Sym)
Anna Zaks46d01602012-05-18 01:16:10 +00001858 checkUseAfterFree(Sym, C, S);
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00001859}
Ted Kremenekd21139a2010-07-31 01:52:11 +00001860
Anna Zaksbb1ef902012-02-11 21:02:35 +00001861// If a symbolic region is assumed to NULL (or another constant), stop tracking
1862// it - assuming that allocation failed on this path.
1863ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1864 SVal Cond,
1865 bool Assumption) const {
1866 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00001867 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00001868 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00001869 ConstraintManager &CMgr = state->getConstraintManager();
1870 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1871 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00001872 state = state->remove<RegionState>(I.getKey());
1873 }
1874
Anna Zaksd56c8792012-02-13 18:05:39 +00001875 // Realloc returns 0 when reallocation fails, which means that we should
1876 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00001877 ReallocPairsTy RP = state->get<ReallocPairs>();
1878 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00001879 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00001880 ConstraintManager &CMgr = state->getConstraintManager();
1881 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00001882 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00001883 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00001884
Anna Zaks75cfbb62012-09-12 22:57:34 +00001885 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1886 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1887 if (RS->isReleased()) {
1888 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00001889 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00001890 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00001891 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1892 state = state->remove<RegionState>(ReallocSym);
1893 else
1894 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00001895 }
Anna Zaksd56c8792012-02-13 18:05:39 +00001896 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00001897 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00001898 }
1899
Anna Zaksbb1ef902012-02-11 21:02:35 +00001900 return state;
1901}
1902
Anna Zaks8ebeb642013-06-08 00:29:29 +00001903bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001904 const CallEvent *Call,
1905 ProgramStateRef State,
1906 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00001907 assert(Call);
Anna Zaks8ebeb642013-06-08 00:29:29 +00001908 EscapingSymbol = 0;
1909
Jordan Rose2a833ca2014-01-15 17:25:15 +00001910 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00001911 // TODO: If we want to be more optimistic here, we'll need to make sure that
1912 // regions escape to C++ containers. They seem to do that even now, but for
1913 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00001914 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001915 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00001916
Jordan Rose742920c2012-07-02 19:27:35 +00001917 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00001918 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00001919 // If it's not a framework call, or if it takes a callback, assume it
1920 // can free memory.
1921 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001922 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00001923
Jordan Rose613f3c02013-03-09 00:59:10 +00001924 // If it's a method we know about, handle it explicitly post-call.
1925 // This should happen before the "freeWhenDone" check below.
1926 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001927 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00001928
Jordan Rose613f3c02013-03-09 00:59:10 +00001929 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1930 // about, we can't be sure that the object will use free() to deallocate the
1931 // memory, so we can't model it explicitly. The best we can do is use it to
1932 // decide whether the pointer escapes.
1933 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001934 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00001935
Jordan Rose613f3c02013-03-09 00:59:10 +00001936 // If the first selector piece ends with "NoCopy", and there is no
1937 // "freeWhenDone" parameter set to zero, we know ownership is being
1938 // transferred. Again, though, we can't be sure that the object will use
1939 // free() to deallocate the memory, so we can't model it explicitly.
1940 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00001941 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001942 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00001943
Anna Zaks42908c72012-06-19 05:10:32 +00001944 // If the first selector starts with addPointer, insertPointer,
1945 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1946 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00001947 // that the pointers get freed by following the container itself.
1948 if (FirstSlot.startswith("addPointer") ||
1949 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00001950 FirstSlot.startswith("replacePointer") ||
1951 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001952 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00001953 }
1954
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001955 // We should escape receiver on call to 'init'. This is especially relevant
1956 // to the receiver, as the corresponding symbol is usually not referenced
1957 // after the call.
1958 if (Msg->getMethodFamily() == OMF_init) {
1959 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
1960 return true;
1961 }
Anna Zaks737926b2013-05-31 22:39:13 +00001962
Jordan Rose742920c2012-07-02 19:27:35 +00001963 // Otherwise, assume that the method does not free memory.
1964 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001965 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00001966 }
1967
Jordan Rose742920c2012-07-02 19:27:35 +00001968 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00001969 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00001970 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001971 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00001972
Jordan Rose742920c2012-07-02 19:27:35 +00001973 ASTContext &ASTC = State->getStateManager().getContext();
1974
1975 // If it's one of the allocation functions we can reason about, we model
1976 // its behavior explicitly.
1977 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001978 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00001979
1980 // If it's not a system call, assume it frees memory.
1981 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001982 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00001983
1984 // White list the system functions whose arguments escape.
1985 const IdentifierInfo *II = FD->getIdentifier();
1986 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001987 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00001988 StringRef FName = II->getName();
1989
Jordan Rose742920c2012-07-02 19:27:35 +00001990 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose7ab01822012-07-02 19:27:51 +00001991 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00001992 if (FName.endswith("NoCopy")) {
1993 // Look for the deallocator argument. We know that the memory ownership
1994 // is not transferred only if the deallocator argument is
1995 // 'kCFAllocatorNull'.
1996 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1997 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1998 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1999 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2000 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002001 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002002 }
2003 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002004 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002005 }
2006
Jordan Rose742920c2012-07-02 19:27:35 +00002007 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002008 // 'closefn' is specified (and if that function does free memory),
2009 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002010 // Currently, we do not inspect the 'closefn' function (PR12101).
2011 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002012 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002013 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002014
2015 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2016 // these leaks might be intentional when setting the buffer for stdio.
2017 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2018 if (FName == "setbuf" || FName =="setbuffer" ||
2019 FName == "setlinebuf" || FName == "setvbuf") {
2020 if (Call->getNumArgs() >= 1) {
2021 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2022 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2023 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2024 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002025 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002026 }
2027 }
2028
2029 // A bunch of other functions which either take ownership of a pointer or
2030 // wrap the result up in a struct or object, meaning it can be freed later.
2031 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2032 // but the Malloc checker cannot differentiate between them. The right way
2033 // of doing this would be to implement a pointer escapes callback.
2034 if (FName == "CGBitmapContextCreate" ||
2035 FName == "CGBitmapContextCreateWithData" ||
2036 FName == "CVPixelBufferCreateWithBytes" ||
2037 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2038 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002039 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002040 }
2041
Jordan Rose7ab01822012-07-02 19:27:51 +00002042 // Handle cases where we know a buffer's /address/ can escape.
2043 // Note that the above checks handle some special cases where we know that
2044 // even though the address escapes, it's still our responsibility to free the
2045 // buffer.
2046 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002047 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002048
2049 // Otherwise, assume that the function does not free memory.
2050 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002051 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002052}
2053
Anna Zaks333481b2013-03-28 23:15:29 +00002054static bool retTrue(const RefState *RS) {
2055 return true;
2056}
2057
2058static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2059 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2060 RS->getAllocationFamily() == AF_CXXNew);
2061}
2062
Anna Zaksdc154152012-12-20 00:38:25 +00002063ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2064 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002065 const CallEvent *Call,
2066 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002067 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2068}
2069
2070ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2071 const InvalidatedSymbols &Escaped,
2072 const CallEvent *Call,
2073 PointerEscapeKind Kind) const {
2074 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2075 &checkIfNewOrNewArrayFamily);
2076}
2077
2078ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2079 const InvalidatedSymbols &Escaped,
2080 const CallEvent *Call,
2081 PointerEscapeKind Kind,
2082 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002083 // If we know that the call does not free memory, or we want to process the
2084 // call later, keep tracking the top level arguments.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002085 SymbolRef EscapingSymbol = 0;
Jordan Rose757fbb02013-05-10 17:07:16 +00002086 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002087 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2088 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002089 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002090 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002091 }
Anna Zaks3d348342012-02-14 21:55:24 +00002092
Anna Zaksdc154152012-12-20 00:38:25 +00002093 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002094 E = Escaped.end();
2095 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002096 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002097
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002098 if (EscapingSymbol && EscapingSymbol != sym)
2099 continue;
2100
Anna Zaks0d6989b2012-06-22 02:04:31 +00002101 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks93a21a82013-04-09 00:30:28 +00002102 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002103 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002104 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2105 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002106 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002107 }
Anna Zaks3d348342012-02-14 21:55:24 +00002108 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002109}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002110
Jordy Rosebf38f202012-03-18 07:43:35 +00002111static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2112 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002113 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2114 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002115
Jordan Rose0c153cb2012-11-02 01:54:06 +00002116 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002117 I != E; ++I) {
2118 SymbolRef sym = I.getKey();
2119 if (!currMap.lookup(sym))
2120 return sym;
2121 }
2122
2123 return NULL;
2124}
2125
Anna Zaks2b5bb972012-02-09 06:25:51 +00002126PathDiagnosticPiece *
2127MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2128 const ExplodedNode *PrevN,
2129 BugReporterContext &BRC,
2130 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002131 ProgramStateRef state = N->getState();
2132 ProgramStateRef statePrev = PrevN->getState();
2133
2134 const RefState *RS = state->get<RegionState>(Sym);
2135 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002136 if (!RS)
Anna Zaks2b5bb972012-02-09 06:25:51 +00002137 return 0;
2138
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002139 const Stmt *S = 0;
2140 const char *Msg = 0;
Anna Zakscba4f292012-03-16 23:24:20 +00002141 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002142
2143 // Retrieve the associated statement.
2144 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002145 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002146 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002147 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002148 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002149 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002150 // If an assumption was made on a branch, it should be caught
2151 // here by looking at the state transition.
2152 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002153 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002154
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002155 if (!S)
Anna Zaks2b5bb972012-02-09 06:25:51 +00002156 return 0;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002157
Jordan Rose681cce92012-07-10 22:07:42 +00002158 // FIXME: We will eventually need to handle non-statement-based events
2159 // (__attribute__((cleanup))).
2160
Anna Zaks2b5bb972012-02-09 06:25:51 +00002161 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002162 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002163 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002164 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002165 StackHint = new StackHintGeneratorForSymbol(Sym,
2166 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002167 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002168 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002169 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002170 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002171 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002172 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002173 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002174 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002175 Mode = ReallocationFailed;
2176 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002177 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002178 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002179
Jordy Rose21ff76e2012-03-24 03:15:09 +00002180 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2181 // Is it possible to fail two reallocs WITHOUT testing in between?
2182 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2183 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002184 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002185 FailedReallocSymbol = sym;
2186 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002187 }
2188
2189 // We are in a special mode if a reallocation failed later in the path.
2190 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002191 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002192
Jordy Rose21ff76e2012-03-24 03:15:09 +00002193 // Is this is the first appearance of the reallocated symbol?
2194 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002195 // We're at the reallocation point.
2196 Msg = "Attempt to reallocate memory";
2197 StackHint = new StackHintGeneratorForSymbol(Sym,
2198 "Returned reallocated memory");
2199 FailedReallocSymbol = NULL;
2200 Mode = Normal;
2201 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002202 }
2203
Anna Zaks2b5bb972012-02-09 06:25:51 +00002204 if (!Msg)
2205 return 0;
Anna Zakscba4f292012-03-16 23:24:20 +00002206 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002207
2208 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002209 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002210 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002211 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002212}
2213
Anna Zaks263b7e02012-05-02 00:05:20 +00002214void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2215 const char *NL, const char *Sep) const {
2216
2217 RegionStateTy RS = State->get<RegionState>();
2218
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002219 if (!RS.isEmpty()) {
2220 Out << Sep << "MallocChecker:" << NL;
2221 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2222 I.getKey()->dumpToStream(Out);
2223 Out << " : ";
2224 I.getData().dump(Out);
2225 Out << NL;
2226 }
2227 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002228}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002229
Anna Zakse4cfcd42013-04-16 00:22:55 +00002230void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2231 registerCStringCheckerBasic(mgr);
2232 mgr.registerChecker<MallocChecker>()->Filter.CNewDeleteLeaksChecker = true;
2233 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2234 // checker.
2235 mgr.registerChecker<MallocChecker>()->Filter.CNewDeleteChecker = true;
2236}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002237
Anna Zakscd37bf42012-02-08 23:16:52 +00002238#define REGISTER_CHECKER(name) \
2239void ento::register##name(CheckerManager &mgr) {\
Anna Zakse56167e2012-02-17 22:35:31 +00002240 registerCStringCheckerBasic(mgr); \
Anna Zakscd37bf42012-02-08 23:16:52 +00002241 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002242}
Anna Zakscd37bf42012-02-08 23:16:52 +00002243
2244REGISTER_CHECKER(MallocPessimistic)
2245REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev13df0362013-03-25 01:35:45 +00002246REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002247REGISTER_CHECKER(MismatchedDeallocatorChecker)