blob: 1fa15d09cbc5d22567354ea196723cac990cced3 [file] [log] [blame]
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines malloc/free checker, which checks for potential memory
11// leaks, double free, and use-after-free problems.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000020#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000021#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000027#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000029#include "llvm/ADT/SmallString.h"
Jordan Rose615a0922012-09-22 01:24:42 +000030#include "llvm/ADT/StringExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000031#include <climits>
32
Zhongxing Xu589c0f22009-11-12 08:38:56 +000033using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000034using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000035
36namespace {
37
Anton Yartsev849c7bf2013-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 Xu7fb14642009-12-11 00:55:44 +000046class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000047 enum Kind { // Reference to allocated memory.
48 Allocated,
49 // Reference to released/freed memory.
50 Released,
Anna Zaks050cdd72012-06-20 20:57:46 +000051 // The responsibility for freeing resources has transfered from
52 // this reference. A relinquished symbol should not be freed.
Anna Zaks04130232013-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 Yartsev849c7bf2013-03-28 17:05:19 +000059
Zhongxing Xu243fde92009-11-17 07:54:15 +000060 const Stmt *S;
Anton Yartsev849c7bf2013-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 Xu243fde92009-11-17 07:54:15 +000064
Anton Yartsev849c7bf2013-03-28 17:05:19 +000065 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks04130232013-04-09 00:30:28 +000066 : S(s), K(k), Family(family) {
67 assert(family != AF_None);
68 }
Zhongxing Xu7fb14642009-12-11 00:55:44 +000069public:
Anna Zaks050cdd72012-06-20 20:57:46 +000070 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000071 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000072 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks04130232013-04-09 00:30:28 +000073 bool isEscaped() const { return K == Escaped; }
74 AllocationFamily getAllocationFamily() const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +000075 return (AllocationFamily)Family;
76 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000077 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000078
79 bool operator==(const RefState &X) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +000080 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu243fde92009-11-17 07:54:15 +000081 }
82
Anton Yartsev849c7bf2013-03-28 17:05:19 +000083 static RefState getAllocated(unsigned family, const Stmt *s) {
84 return RefState(Allocated, s, family);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000085 }
Anton Yartsev849c7bf2013-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 Kremenekdde201b2010-08-06 21:12:55 +000091 }
Anna Zaks04130232013-04-09 00:30:28 +000092 static RefState getEscaped(const RefState *RS) {
93 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
94 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000095
96 void Profile(llvm::FoldingSetNodeID &ID) const {
97 ID.AddInteger(K);
98 ID.AddPointer(S);
Anton Yartsev849c7bf2013-03-28 17:05:19 +000099 ID.AddInteger(Family);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000100 }
Ted Kremenekc37fad62013-01-03 01:30:12 +0000101
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000102 void dump(raw_ostream &OS) const {
Craig Topper3aa29df2013-07-15 08:24:27 +0000103 static const char *const Table[] = {
Ted Kremenekc37fad62013-01-03 01:30:12 +0000104 "Allocated",
105 "Released",
106 "Relinquished"
107 };
108 OS << Table[(unsigned) K];
109 }
110
111 LLVM_ATTRIBUTE_USED void dump() const {
112 dump(llvm::errs());
113 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000114};
115
Anna Zaks9dc298b2012-09-12 22:57:34 +0000116enum ReallocPairKind {
117 RPToBeFreedAfterFailure,
118 // The symbol has been freed when reallocation failed.
119 RPIsFreeOnFailure,
120 // The symbol does not need to be freed after reallocation fails.
121 RPDoNotTrackAfterFailure
122};
123
Anna Zaks55dd9562012-08-24 02:28:20 +0000124/// \class ReallocPair
125/// \brief Stores information about the symbol being reallocated by a call to
126/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +0000127struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +0000128 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000129 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +0000130 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +0000131
Anna Zaks9dc298b2012-09-12 22:57:34 +0000132 ReallocPair(SymbolRef S, ReallocPairKind K) :
133 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +0000134 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +0000135 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +0000136 ID.AddPointer(ReallocatedSym);
137 }
138 bool operator==(const ReallocPair &X) const {
139 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +0000140 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +0000141 }
142};
143
Anna Zaks97bfb552013-01-08 00:25:29 +0000144typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000145
Anna Zaksb319e022012-02-08 20:13:28 +0000146class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000147 check::PointerEscape,
Anna Zaks41988f32013-03-28 23:15:29 +0000148 check::ConstPointerEscape,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000149 check::PreStmt<ReturnStmt>,
Anton Yartsev55e57a52013-04-10 22:21:41 +0000150 check::PreCall,
Anna Zaksb319e022012-02-08 20:13:28 +0000151 check::PostStmt<CallExpr>,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000152 check::PostStmt<CXXNewExpr>,
153 check::PreStmt<CXXDeleteExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000154 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000155 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000156 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000157 eval::Assume>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000158{
Anna Zaksfebdc322012-02-16 22:26:12 +0000159 mutable OwningPtr<BugType> BT_DoubleFree;
160 mutable OwningPtr<BugType> BT_Leak;
161 mutable OwningPtr<BugType> BT_UseFree;
162 mutable OwningPtr<BugType> BT_BadFree;
Anton Yartsev648cb712013-04-04 23:46:29 +0000163 mutable OwningPtr<BugType> BT_MismatchedDealloc;
Anna Zaks118aa752013-02-07 23:05:47 +0000164 mutable OwningPtr<BugType> BT_OffsetFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000165 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000166 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
167
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000168public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000169 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000170 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000171
172 /// In pessimistic mode, the checker assumes that it does not know which
173 /// functions might free the memory.
174 struct ChecksFilter {
175 DefaultBool CMallocPessimistic;
176 DefaultBool CMallocOptimistic;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000177 DefaultBool CNewDeleteChecker;
Jordan Rosee85deb32013-04-05 17:55:00 +0000178 DefaultBool CNewDeleteLeaksChecker;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000179 DefaultBool CMismatchedDeallocatorChecker;
Anna Zaks231361a2012-02-08 23:16:52 +0000180 };
181
182 ChecksFilter Filter;
183
Anton Yartsev55e57a52013-04-10 22:21:41 +0000184 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000185 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000186 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
187 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000188 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000189 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000190 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000191 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000192 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000193 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000194 void checkLocation(SVal l, bool isLoad, const Stmt *S,
195 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000196
197 ProgramStateRef checkPointerEscape(ProgramStateRef State,
198 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000199 const CallEvent *Call,
200 PointerEscapeKind Kind) const;
Anna Zaks41988f32013-03-28 23:15:29 +0000201 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
202 const InvalidatedSymbols &Escaped,
203 const CallEvent *Call,
204 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000205
Anna Zaks93c5a242012-05-02 00:05:20 +0000206 void printState(raw_ostream &Out, ProgramStateRef State,
207 const char *NL, const char *Sep) const;
208
Zhongxing Xu7b760962009-11-13 07:25:27 +0000209private:
Anna Zaks66c40402012-02-14 21:55:24 +0000210 void initIdentifierInfo(ASTContext &C) const;
211
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000212 /// \brief Determine family of a deallocation expression.
Anton Yartsev648cb712013-04-04 23:46:29 +0000213 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000214
215 /// \brief Print names of allocators and deallocators.
216 ///
217 /// \returns true on success.
218 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
219 const Expr *E) const;
220
221 /// \brief Print expected name of an allocator based on the deallocator's
222 /// family derived from the DeallocExpr.
223 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
224 const Expr *DeallocExpr) const;
225 /// \brief Print expected name of a deallocator based on the allocator's
226 /// family.
227 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
228
Jordan Rose9fe09f32013-03-09 00:59:10 +0000229 ///@{
Anna Zaks66c40402012-02-14 21:55:24 +0000230 /// Check if this is one of the functions which can allocate/reallocate memory
231 /// pointed to by one of its arguments.
232 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000233 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
234 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000235 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose9fe09f32013-03-09 00:59:10 +0000236 ///@}
Anna Zaks87cb5be2012-02-22 19:24:52 +0000237 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
238 const CallExpr *CE,
239 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000240 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000241 const Expr *SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000242 ProgramStateRef State,
243 AllocationFamily Family = AF_Malloc) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000244 return MallocMemAux(C, CE,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000245 State->getSVal(SizeEx, C.getLocationContext()),
246 Init, State, Family);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000247 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000248
Ted Kremenek8bef8232012-01-26 21:29:00 +0000249 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000250 SVal SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000251 ProgramStateRef State,
252 AllocationFamily Family = AF_Malloc);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000253
Anna Zaks87cb5be2012-02-22 19:24:52 +0000254 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000255 static ProgramStateRef
256 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
257 AllocationFamily Family = AF_Malloc);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000258
259 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
260 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000261 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000262 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000263 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000264 bool &ReleasedAllocated,
265 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000266 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
267 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000268 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000269 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000270 bool &ReleasedAllocated,
271 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000272
Anna Zaks87cb5be2012-02-22 19:24:52 +0000273 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
274 bool FreesMemOnFailure) const;
275 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000276
Anna Zaks14345182012-05-18 01:16:10 +0000277 ///\brief Check if the memory associated with this symbol was released.
278 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
279
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000280 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaks91c2a112012-02-08 23:16:56 +0000281
Anna Zakse7a5c822013-05-31 23:47:32 +0000282 /// Check if the function is known free memory, or if it is
Jordan Rose9fe09f32013-03-09 00:59:10 +0000283 /// "interesting" and should be modeled explicitly.
284 ///
Anna Zaks33708592013-06-08 00:29:29 +0000285 /// \param [out] EscapingSymbol A function might not free memory in general,
286 /// but could be known to free a particular symbol. In this case, false is
Anna Zakse7a5c822013-05-31 23:47:32 +0000287 /// returned and the single escaping symbol is returned through the out
288 /// parameter.
289 ///
Jordan Rose9fe09f32013-03-09 00:59:10 +0000290 /// We assume that pointers do not escape through calls to system functions
291 /// not handled by this checker.
Anna Zaks33708592013-06-08 00:29:29 +0000292 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zakse7a5c822013-05-31 23:47:32 +0000293 ProgramStateRef State,
294 SymbolRef &EscapingSymbol) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000295
Anna Zaks41988f32013-03-28 23:15:29 +0000296 // Implementation of the checkPointerEscape callabcks.
297 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
298 const InvalidatedSymbols &Escaped,
299 const CallEvent *Call,
300 PointerEscapeKind Kind,
301 bool(*CheckRefState)(const RefState*)) const;
302
Anton Yartsev9ae7a922013-04-11 00:05:20 +0000303 ///@{
304 /// Tells if a given family/call/symbol is tracked by the current checker.
305 bool isTrackedByCurrentChecker(AllocationFamily Family) const;
306 bool isTrackedByCurrentChecker(CheckerContext &C,
307 const Stmt *AllocDeallocStmt) const;
308 bool isTrackedByCurrentChecker(CheckerContext &C, SymbolRef Sym) const;
309 ///@}
Ted Kremenek9c378f72011-08-12 23:37:29 +0000310 static bool SummarizeValue(raw_ostream &os, SVal V);
311 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000312 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
313 const Expr *DeallocExpr) const;
Anton Yartsev648cb712013-04-04 23:46:29 +0000314 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartseva3ae9372013-04-05 11:25:10 +0000315 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsev30845182013-09-16 17:51:25 +0000316 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000317 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
318 const Expr *DeallocExpr,
319 const Expr *AllocExpr = 0) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000320 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
321 SymbolRef Sym) const;
322 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000323 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000324
Anna Zaksca8e36e2012-02-23 21:38:21 +0000325 /// Find the location of the allocation for Sym on the path leading to the
326 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000327 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
328 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000329
Anna Zaksda046772012-02-11 21:02:40 +0000330 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
331
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000332 /// The bug visitor which allows us to print extra diagnostics along the
333 /// BugReport path. For example, showing the allocation site of the leaked
334 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000335 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000336 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000337 enum NotificationMode {
338 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000339 ReallocationFailed
340 };
341
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000342 // The allocated region symbol tracked by the main analysis.
343 SymbolRef Sym;
344
Anna Zaks88feba02012-05-10 01:37:40 +0000345 // The mode we are in, i.e. what kind of diagnostics will be emitted.
346 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000347
Anna Zaks88feba02012-05-10 01:37:40 +0000348 // A symbol from when the primary region should have been reallocated.
349 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000350
Anna Zaks88feba02012-05-10 01:37:40 +0000351 bool IsLeak;
352
353 public:
354 MallocBugVisitor(SymbolRef S, bool isLeak = false)
355 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000356
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000357 virtual ~MallocBugVisitor() {}
358
359 void Profile(llvm::FoldingSetNodeID &ID) const {
360 static int X = 0;
361 ID.AddPointer(&X);
362 ID.AddPointer(Sym);
363 }
364
Anna Zaksfe571602012-02-16 22:26:07 +0000365 inline bool isAllocated(const RefState *S, const RefState *SPrev,
366 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000367 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000368 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000369 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000370 }
371
Anna Zaksfe571602012-02-16 22:26:07 +0000372 inline bool isReleased(const RefState *S, const RefState *SPrev,
373 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000374 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000375 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000376 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
377 }
378
Anna Zaks5b7aa342012-06-22 02:04:31 +0000379 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
380 const Stmt *Stmt) {
381 // Did not track -> relinquished. Other state (allocated) -> relinquished.
382 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
383 isa<ObjCPropertyRefExpr>(Stmt)) &&
384 (S && S->isRelinquished()) &&
385 (!SPrev || !SPrev->isRelinquished()));
386 }
387
Anna Zaksfe571602012-02-16 22:26:07 +0000388 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
389 const Stmt *Stmt) {
390 // If the expression is not a call, and the state change is
391 // released -> allocated, it must be the realloc return value
392 // check. If we have to handle more cases here, it might be cleaner just
393 // to track this extra bit in the state itself.
394 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
395 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000396 }
397
398 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
399 const ExplodedNode *PrevN,
400 BugReporterContext &BRC,
401 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000402
403 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
404 const ExplodedNode *EndPathNode,
405 BugReport &BR) {
406 if (!IsLeak)
407 return 0;
408
409 PathDiagnosticLocation L =
410 PathDiagnosticLocation::createEndOfPath(EndPathNode,
411 BRC.getSourceManager());
412 // Do not add the statement itself as a range in case of leak.
413 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
414 }
415
Anna Zaks56a938f2012-03-16 23:24:20 +0000416 private:
417 class StackHintGeneratorForReallocationFailed
418 : public StackHintGeneratorForSymbol {
419 public:
420 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
421 : StackHintGeneratorForSymbol(S, M) {}
422
423 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000424 // Printed parameters start at 1, not 0.
425 ++ArgIndex;
426
Anna Zaks56a938f2012-03-16 23:24:20 +0000427 SmallString<200> buf;
428 llvm::raw_svector_ostream os(buf);
429
Jordan Rose615a0922012-09-22 01:24:42 +0000430 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
431 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000432
433 return os.str();
434 }
435
436 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000437 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000438 }
439 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000440 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000441};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000442} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000443
Jordan Rose166d5022012-11-02 01:54:06 +0000444REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
445REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000446
Anna Zaks4141e4d2012-11-13 03:18:01 +0000447// A map from the freed symbol to the symbol representing the return value of
448// the free function.
449REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
450
Anna Zaks4fb54872012-02-11 21:02:35 +0000451namespace {
452class StopTrackingCallback : public SymbolVisitor {
453 ProgramStateRef state;
454public:
455 StopTrackingCallback(ProgramStateRef st) : state(st) {}
456 ProgramStateRef getState() const { return state; }
457
458 bool VisitSymbol(SymbolRef sym) {
459 state = state->remove<RegionState>(sym);
460 return true;
461 }
462};
463} // end anonymous namespace
464
Anna Zaks66c40402012-02-14 21:55:24 +0000465void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000466 if (II_malloc)
467 return;
468 II_malloc = &Ctx.Idents.get("malloc");
469 II_free = &Ctx.Idents.get("free");
470 II_realloc = &Ctx.Idents.get("realloc");
471 II_reallocf = &Ctx.Idents.get("reallocf");
472 II_calloc = &Ctx.Idents.get("calloc");
473 II_valloc = &Ctx.Idents.get("valloc");
474 II_strdup = &Ctx.Idents.get("strdup");
475 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000476}
477
Anna Zaks66c40402012-02-14 21:55:24 +0000478bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000479 if (isFreeFunction(FD, C))
480 return true;
481
482 if (isAllocationFunction(FD, C))
483 return true;
484
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000485 if (isStandardNewDelete(FD, C))
486 return true;
487
Anna Zaks14345182012-05-18 01:16:10 +0000488 return false;
489}
490
491bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
492 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000493 if (!FD)
494 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000495
Jordan Rose5ef6e942012-07-10 23:13:01 +0000496 if (FD->getKind() == Decl::Function) {
497 IdentifierInfo *FunI = FD->getIdentifier();
498 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000499
Jordan Rose5ef6e942012-07-10 23:13:01 +0000500 if (FunI == II_malloc || FunI == II_realloc ||
501 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
502 FunI == II_strdup || FunI == II_strndup)
503 return true;
504 }
Anna Zaks66c40402012-02-14 21:55:24 +0000505
Anna Zaks14345182012-05-18 01:16:10 +0000506 if (Filter.CMallocOptimistic && FD->hasAttrs())
507 for (specific_attr_iterator<OwnershipAttr>
508 i = FD->specific_attr_begin<OwnershipAttr>(),
509 e = FD->specific_attr_end<OwnershipAttr>();
510 i != e; ++i)
511 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
512 return true;
513 return false;
514}
515
516bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
517 if (!FD)
518 return false;
519
Jordan Rose5ef6e942012-07-10 23:13:01 +0000520 if (FD->getKind() == Decl::Function) {
521 IdentifierInfo *FunI = FD->getIdentifier();
522 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000523
Jordan Rose5ef6e942012-07-10 23:13:01 +0000524 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
525 return true;
526 }
Anna Zaks66c40402012-02-14 21:55:24 +0000527
Anna Zaks14345182012-05-18 01:16:10 +0000528 if (Filter.CMallocOptimistic && FD->hasAttrs())
529 for (specific_attr_iterator<OwnershipAttr>
530 i = FD->specific_attr_begin<OwnershipAttr>(),
531 e = FD->specific_attr_end<OwnershipAttr>();
532 i != e; ++i)
533 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
534 (*i)->getOwnKind() == OwnershipAttr::Holds)
535 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000536 return false;
537}
538
Anton Yartsev69746282013-03-28 16:10:38 +0000539// Tells if the callee is one of the following:
540// 1) A global non-placement new/delete operator function.
541// 2) A global placement operator function with the single placement argument
542// of type std::nothrow_t.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000543bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
544 ASTContext &C) const {
545 if (!FD)
546 return false;
547
548 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
549 if (Kind != OO_New && Kind != OO_Array_New &&
550 Kind != OO_Delete && Kind != OO_Array_Delete)
551 return false;
552
Anton Yartsev69746282013-03-28 16:10:38 +0000553 // Skip all operator new/delete methods.
554 if (isa<CXXMethodDecl>(FD))
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000555 return false;
556
557 // Return true if tested operator is a standard placement nothrow operator.
558 if (FD->getNumParams() == 2) {
559 QualType T = FD->getParamDecl(1)->getType();
560 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
561 return II->getName().equals("nothrow_t");
562 }
563
564 // Skip placement operators.
565 if (FD->getNumParams() != 1 || FD->isVariadic())
566 return false;
567
568 // One of the standard new/new[]/delete/delete[] non-placement operators.
569 return true;
570}
571
Anna Zaksb319e022012-02-08 20:13:28 +0000572void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000573 if (C.wasInlined)
574 return;
575
Anna Zaksb319e022012-02-08 20:13:28 +0000576 const FunctionDecl *FD = C.getCalleeDecl(CE);
577 if (!FD)
578 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000579
Anna Zaks87cb5be2012-02-22 19:24:52 +0000580 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000581 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000582
583 if (FD->getKind() == Decl::Function) {
584 initIdentifierInfo(C.getASTContext());
585 IdentifierInfo *FunI = FD->getIdentifier();
586
Anton Yartsev648cb712013-04-04 23:46:29 +0000587 if (FunI == II_malloc || FunI == II_valloc) {
588 if (CE->getNumArgs() < 1)
589 return;
590 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
591 } else if (FunI == II_realloc) {
592 State = ReallocMem(C, CE, false);
593 } else if (FunI == II_reallocf) {
594 State = ReallocMem(C, CE, true);
595 } else if (FunI == II_calloc) {
596 State = CallocMem(C, CE);
597 } else if (FunI == II_free) {
598 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
599 } else if (FunI == II_strdup) {
600 State = MallocUpdateRefState(C, CE, State);
601 } else if (FunI == II_strndup) {
602 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000603 }
Anton Yartsev648cb712013-04-04 23:46:29 +0000604 else if (isStandardNewDelete(FD, C.getASTContext())) {
605 // Process direct calls to operator new/new[]/delete/delete[] functions
606 // as distinct from new/new[]/delete/delete[] expressions that are
607 // processed by the checkPostStmt callbacks for CXXNewExpr and
608 // CXXDeleteExpr.
609 OverloadedOperatorKind K = FD->getOverloadedOperator();
610 if (K == OO_New)
611 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
612 AF_CXXNew);
613 else if (K == OO_Array_New)
614 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
615 AF_CXXNewArray);
616 else if (K == OO_Delete || K == OO_Array_Delete)
617 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
618 else
619 llvm_unreachable("not a new/delete operator");
Jordan Rose5ef6e942012-07-10 23:13:01 +0000620 }
621 }
622
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000623 if (Filter.CMallocOptimistic || Filter.CMismatchedDeallocatorChecker) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000624 // Check all the attributes, if there are any.
625 // There can be multiple of these attributes.
626 if (FD->hasAttrs())
627 for (specific_attr_iterator<OwnershipAttr>
628 i = FD->specific_attr_begin<OwnershipAttr>(),
629 e = FD->specific_attr_end<OwnershipAttr>();
630 i != e; ++i) {
631 switch ((*i)->getOwnKind()) {
632 case OwnershipAttr::Returns:
633 State = MallocMemReturnsAttr(C, CE, *i);
634 break;
635 case OwnershipAttr::Takes:
636 case OwnershipAttr::Holds:
637 State = FreeMemAttr(C, CE, *i);
638 break;
639 }
640 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000641 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000642 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000643}
644
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000645void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
646 CheckerContext &C) const {
647
648 if (NE->getNumPlacementArgs())
649 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
650 E = NE->placement_arg_end(); I != E; ++I)
651 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
652 checkUseAfterFree(Sym, C, *I);
653
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000654 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
655 return;
656
657 ProgramStateRef State = C.getState();
658 // The return value from operator new is bound to a specified initialization
659 // value (if any) and we don't want to loose this value. So we call
660 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
661 // existing binding.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000662 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
663 : AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000664 C.addTransition(State);
665}
666
667void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
668 CheckerContext &C) const {
669
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000670 if (!Filter.CNewDeleteChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000671 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
672 checkUseAfterFree(Sym, C, DE->getArgument());
673
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000674 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
675 return;
676
677 ProgramStateRef State = C.getState();
678 bool ReleasedAllocated;
679 State = FreeMemAux(C, DE->getArgument(), DE, State,
680 /*Hold*/false, ReleasedAllocated);
681
682 C.addTransition(State);
683}
684
Jordan Rose9fe09f32013-03-09 00:59:10 +0000685static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
686 // If the first selector piece is one of the names below, assume that the
687 // object takes ownership of the memory, promising to eventually deallocate it
688 // with free().
689 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
690 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
691 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
692 if (FirstSlot == "dataWithBytesNoCopy" ||
693 FirstSlot == "initWithBytesNoCopy" ||
694 FirstSlot == "initWithCharactersNoCopy")
695 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000696
697 return false;
698}
699
Jordan Rose9fe09f32013-03-09 00:59:10 +0000700static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
701 Selector S = Call.getSelector();
702
703 // FIXME: We should not rely on fully-constrained symbols being folded.
704 for (unsigned i = 1; i < S.getNumArgs(); ++i)
705 if (S.getNameForSlot(i).equals("freeWhenDone"))
706 return !Call.getArgSVal(i).isZeroConstant();
707
708 return None;
709}
710
Anna Zaks4141e4d2012-11-13 03:18:01 +0000711void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
712 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000713 if (C.wasInlined)
714 return;
715
Jordan Rose9fe09f32013-03-09 00:59:10 +0000716 if (!isKnownDeallocObjCMethodName(Call))
717 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000718
Jordan Rose9fe09f32013-03-09 00:59:10 +0000719 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
720 if (!*FreeWhenDone)
721 return;
722
723 bool ReleasedAllocatedMemory;
724 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
725 Call.getOriginExpr(), C.getState(),
726 /*Hold=*/true, ReleasedAllocatedMemory,
727 /*RetNullOnFailure=*/true);
728
729 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000730}
731
Anna Zaks87cb5be2012-02-22 19:24:52 +0000732ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
733 const CallExpr *CE,
734 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000735 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000736 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000737
Sean Huntcf807c42010-08-18 23:23:40 +0000738 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000739 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000740 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000741 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000742 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000743}
744
Anna Zaksb319e022012-02-08 20:13:28 +0000745ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000746 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000747 SVal Size, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000748 ProgramStateRef State,
749 AllocationFamily Family) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000750
751 // Bind the return value to the symbolic value from the heap region.
752 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
753 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000754 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000755 SValBuilder &svalBuilder = C.getSValBuilder();
756 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000757 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
758 .castAs<DefinedSVal>();
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000759 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000760
Anna Zaksb16ce452012-02-15 00:11:22 +0000761 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000762 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000763 return 0;
764
Jordy Rose32f26562010-07-04 00:00:41 +0000765 // Fill the region with the initialization value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000766 State = State->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000767
Jordy Rose32f26562010-07-04 00:00:41 +0000768 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000769 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000770 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000771 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000772 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000773 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000774 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000775 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000776 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000777 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000778 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000779
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000780 State = State->assume(extentMatchesSize, true);
781 assert(State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000782 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000783
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000784 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000785}
786
787ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000788 const Expr *E,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000789 ProgramStateRef State,
790 AllocationFamily Family) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000791 // Get the return value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000792 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000793
794 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000795 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000796 return 0;
797
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000798 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000799 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000800
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000801 // Set the symbol's state to Allocated.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000802 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000803}
804
Anna Zaks87cb5be2012-02-22 19:24:52 +0000805ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
806 const CallExpr *CE,
807 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000808 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000809 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000810
Anna Zaksb3d72752012-03-01 22:06:06 +0000811 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000812 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000813
Sean Huntcf807c42010-08-18 23:23:40 +0000814 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
815 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000816 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000817 Att->getOwnKind() == OwnershipAttr::Holds,
818 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000819 if (StateI)
820 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000821 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000822 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000823}
824
Ted Kremenek8bef8232012-01-26 21:29:00 +0000825ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000826 const CallExpr *CE,
827 ProgramStateRef state,
828 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000829 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000830 bool &ReleasedAllocated,
831 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000832 if (CE->getNumArgs() < (Num + 1))
833 return 0;
834
Anna Zaks4141e4d2012-11-13 03:18:01 +0000835 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
836 ReleasedAllocated, ReturnsNullOnFailure);
837}
838
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000839/// Checks if the previous call to free on the given symbol failed - if free
840/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000841static bool didPreviousFreeFail(ProgramStateRef State,
842 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000843 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000844 if (Ret) {
845 assert(*Ret && "We should not store the null return symbol");
846 ConstraintManager &CMgr = State->getConstraintManager();
847 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000848 RetStatusSymbol = *Ret;
849 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000850 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000851 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000852}
853
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000854AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartsev648cb712013-04-04 23:46:29 +0000855 const Stmt *S) const {
856 if (!S)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000857 return AF_None;
858
Anton Yartsev648cb712013-04-04 23:46:29 +0000859 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000860 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartsev648cb712013-04-04 23:46:29 +0000861
862 if (!FD)
863 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
864
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000865 ASTContext &Ctx = C.getASTContext();
866
Anton Yartsev648cb712013-04-04 23:46:29 +0000867 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000868 return AF_Malloc;
869
870 if (isStandardNewDelete(FD, Ctx)) {
871 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartsev648cb712013-04-04 23:46:29 +0000872 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000873 return AF_CXXNew;
Anton Yartsev648cb712013-04-04 23:46:29 +0000874 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000875 return AF_CXXNewArray;
876 }
877
878 return AF_None;
879 }
880
Anton Yartsev648cb712013-04-04 23:46:29 +0000881 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
882 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
883
884 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000885 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
886
Anton Yartsev648cb712013-04-04 23:46:29 +0000887 if (isa<ObjCMessageExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000888 return AF_Malloc;
889
890 return AF_None;
891}
892
893bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
894 const Expr *E) const {
895 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
896 // FIXME: This doesn't handle indirect calls.
897 const FunctionDecl *FD = CE->getDirectCallee();
898 if (!FD)
899 return false;
900
901 os << *FD;
902 if (!FD->isOverloadedOperator())
903 os << "()";
904 return true;
905 }
906
907 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
908 if (Msg->isInstanceMessage())
909 os << "-";
910 else
911 os << "+";
912 os << Msg->getSelector().getAsString();
913 return true;
914 }
915
916 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
917 os << "'"
918 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
919 << "'";
920 return true;
921 }
922
923 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
924 os << "'"
925 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
926 << "'";
927 return true;
928 }
929
930 return false;
931}
932
933void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
934 const Expr *E) const {
935 AllocationFamily Family = getAllocationFamily(C, E);
936
937 switch(Family) {
938 case AF_Malloc: os << "malloc()"; return;
939 case AF_CXXNew: os << "'new'"; return;
940 case AF_CXXNewArray: os << "'new[]'"; return;
941 case AF_None: llvm_unreachable("not a deallocation expression");
942 }
943}
944
945void MallocChecker::printExpectedDeallocName(raw_ostream &os,
946 AllocationFamily Family) const {
947 switch(Family) {
948 case AF_Malloc: os << "free()"; return;
949 case AF_CXXNew: os << "'delete'"; return;
950 case AF_CXXNewArray: os << "'delete[]'"; return;
951 case AF_None: llvm_unreachable("suspicious AF_None argument");
952 }
953}
954
Anna Zaks5b7aa342012-06-22 02:04:31 +0000955ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
956 const Expr *ArgExpr,
957 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000958 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000959 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000960 bool &ReleasedAllocated,
961 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000962
Anna Zaks4141e4d2012-11-13 03:18:01 +0000963 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000964 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000965 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000966 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000967
968 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000969 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000970 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000971
Anna Zaksb276bd92012-02-14 00:26:13 +0000972 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000973 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000974 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000975 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000976 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000977
Jordy Rose43859f62010-06-07 19:32:37 +0000978 // Unknown values could easily be okay
979 // Undefined values are handled elsewhere
980 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000981 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000982
Jordy Rose43859f62010-06-07 19:32:37 +0000983 const MemRegion *R = ArgVal.getAsRegion();
984
985 // Nonlocs can't be freed, of course.
986 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
987 if (!R) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000988 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000989 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000990 }
991
992 R = R->StripCasts();
993
994 // Blocks might show up as heap data, but should not be free()d
995 if (isa<BlockDataRegion>(R)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000996 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000997 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000998 }
999
1000 const MemSpaceRegion *MS = R->getMemorySpace();
1001
Anton Yartsevbb369952013-03-13 14:39:10 +00001002 // Parameters, locals, statics, globals, and memory returned by alloca()
1003 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +00001004 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1005 // FIXME: at the time this code was written, malloc() regions were
1006 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1007 // This means that there isn't actually anything from HeapSpaceRegion
1008 // that should be freed, even though we allow it here.
1009 // Of course, free() can work on memory allocated outside the current
1010 // function, so UnknownSpaceRegion is always a possibility.
1011 // False negatives are better than false positives.
1012
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001013 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +00001014 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001015 }
Anna Zaks118aa752013-02-07 23:05:47 +00001016
1017 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +00001018 // Various cases could lead to non-symbol values here.
1019 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +00001020 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +00001021 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001022
Anna Zaks118aa752013-02-07 23:05:47 +00001023 SymbolRef SymBase = SrBase->getSymbol();
1024 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001025 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +00001026
Anton Yartsev648cb712013-04-04 23:46:29 +00001027 if (RsBase) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001028
Anna Zaks04130232013-04-09 00:30:28 +00001029 // Check for double free first.
1030 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartsev648cb712013-04-04 23:46:29 +00001031 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1032 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1033 SymBase, PreviousRetStatusSymbol);
1034 return 0;
Anton Yartsev648cb712013-04-04 23:46:29 +00001035
Anna Zaks04130232013-04-09 00:30:28 +00001036 // If the pointer is allocated or escaped, but we are now trying to free it,
1037 // check that the call to free is proper.
1038 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1039
1040 // Check if an expected deallocation function matches the real one.
1041 bool DeallocMatchesAlloc =
1042 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1043 if (!DeallocMatchesAlloc) {
1044 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsev30845182013-09-16 17:51:25 +00001045 ParentExpr, RsBase, SymBase, Hold);
Anna Zaks04130232013-04-09 00:30:28 +00001046 return 0;
1047 }
1048
1049 // Check if the memory location being freed is the actual location
1050 // allocated, or an offset.
1051 RegionOffset Offset = R->getAsOffset();
1052 if (Offset.isValid() &&
1053 !Offset.hasSymbolicOffset() &&
1054 Offset.getOffset() != 0) {
1055 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1056 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1057 AllocExpr);
1058 return 0;
1059 }
Anton Yartsev648cb712013-04-04 23:46:29 +00001060 }
Anna Zaks118aa752013-02-07 23:05:47 +00001061 }
1062
Jordan Rose68502e52013-08-15 17:22:06 +00001063 ReleasedAllocated = (RsBase != 0) && RsBase->isAllocated();
Anna Zaks55dd9562012-08-24 02:28:20 +00001064
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001065 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +00001066 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001067
Anna Zaks4141e4d2012-11-13 03:18:01 +00001068 // Keep track of the return value. If it is NULL, we will know that free
1069 // failed.
1070 if (ReturnsNullOnFailure) {
1071 SVal RetVal = C.getSVal(ParentExpr);
1072 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1073 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +00001074 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1075 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +00001076 }
1077 }
1078
Anton Yartseva3989b82013-04-05 19:08:04 +00001079 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1080 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001081 // Normal free.
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001082 if (Hold)
Anna Zaks118aa752013-02-07 23:05:47 +00001083 return State->set<RegionState>(SymBase,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001084 RefState::getRelinquished(Family,
1085 ParentExpr));
1086
1087 return State->set<RegionState>(SymBase,
1088 RefState::getReleased(Family, ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001089}
1090
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001091bool MallocChecker::isTrackedByCurrentChecker(AllocationFamily Family) const {
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001092 switch (Family) {
1093 case AF_Malloc: {
1094 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic)
1095 return false;
Anton Yartsevc8454312013-04-05 02:12:04 +00001096 return true;
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001097 }
1098 case AF_CXXNew:
1099 case AF_CXXNewArray: {
Anton Yartsev9df151c2013-04-12 23:25:40 +00001100 if (!Filter.CNewDeleteChecker)
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001101 return false;
Anton Yartsevc8454312013-04-05 02:12:04 +00001102 return true;
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001103 }
1104 case AF_None: {
Anton Yartseva3989b82013-04-05 19:08:04 +00001105 llvm_unreachable("no family");
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001106 }
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001107 }
Anton Yartsevc8454312013-04-05 02:12:04 +00001108 llvm_unreachable("unhandled family");
Anton Yartsev648cb712013-04-04 23:46:29 +00001109}
1110
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001111bool
1112MallocChecker::isTrackedByCurrentChecker(CheckerContext &C,
1113 const Stmt *AllocDeallocStmt) const {
1114 return isTrackedByCurrentChecker(getAllocationFamily(C, AllocDeallocStmt));
Anton Yartsev648cb712013-04-04 23:46:29 +00001115}
1116
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001117bool MallocChecker::isTrackedByCurrentChecker(CheckerContext &C,
1118 SymbolRef Sym) const {
Anton Yartsev648cb712013-04-04 23:46:29 +00001119
Anton Yartseva3989b82013-04-05 19:08:04 +00001120 const RefState *RS = C.getState()->get<RegionState>(Sym);
1121 assert(RS);
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001122 return isTrackedByCurrentChecker(RS->getAllocationFamily());
Anton Yartsev648cb712013-04-04 23:46:29 +00001123}
1124
Ted Kremenek9c378f72011-08-12 23:37:29 +00001125bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001126 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001127 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001128 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001129 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001130 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +00001131 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +00001132 else
1133 return false;
1134
1135 return true;
1136}
1137
Ted Kremenek9c378f72011-08-12 23:37:29 +00001138bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +00001139 const MemRegion *MR) {
1140 switch (MR->getKind()) {
1141 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +00001142 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +00001143 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001144 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +00001145 else
1146 os << "the address of a function";
1147 return true;
1148 }
1149 case MemRegion::BlockTextRegionKind:
1150 os << "block text";
1151 return true;
1152 case MemRegion::BlockDataRegionKind:
1153 // FIXME: where the block came from?
1154 os << "a block";
1155 return true;
1156 default: {
1157 const MemSpaceRegion *MS = MR->getMemorySpace();
1158
Anna Zakseb31a762012-01-04 23:54:01 +00001159 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001160 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1161 const VarDecl *VD;
1162 if (VR)
1163 VD = VR->getDecl();
1164 else
1165 VD = NULL;
1166
1167 if (VD)
1168 os << "the address of the local variable '" << VD->getName() << "'";
1169 else
1170 os << "the address of a local stack variable";
1171 return true;
1172 }
Anna Zakseb31a762012-01-04 23:54:01 +00001173
1174 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001175 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1176 const VarDecl *VD;
1177 if (VR)
1178 VD = VR->getDecl();
1179 else
1180 VD = NULL;
1181
1182 if (VD)
1183 os << "the address of the parameter '" << VD->getName() << "'";
1184 else
1185 os << "the address of a parameter";
1186 return true;
1187 }
Anna Zakseb31a762012-01-04 23:54:01 +00001188
1189 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001190 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1191 const VarDecl *VD;
1192 if (VR)
1193 VD = VR->getDecl();
1194 else
1195 VD = NULL;
1196
1197 if (VD) {
1198 if (VD->isStaticLocal())
1199 os << "the address of the static variable '" << VD->getName() << "'";
1200 else
1201 os << "the address of the global variable '" << VD->getName() << "'";
1202 } else
1203 os << "the address of a global variable";
1204 return true;
1205 }
Anna Zakseb31a762012-01-04 23:54:01 +00001206
1207 return false;
Jordy Rose43859f62010-06-07 19:32:37 +00001208 }
1209 }
1210}
1211
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001212void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1213 SourceRange Range,
1214 const Expr *DeallocExpr) const {
1215
1216 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1217 !Filter.CNewDeleteChecker)
1218 return;
1219
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001220 if (!isTrackedByCurrentChecker(C, DeallocExpr))
Anton Yartsev648cb712013-04-04 23:46:29 +00001221 return;
1222
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001223 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +00001224 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001225 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +00001226
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001227 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +00001228 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001229
Jordy Rose43859f62010-06-07 19:32:37 +00001230 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001231 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1232 MR = ER->getSuperRegion();
1233
1234 if (MR && isa<AllocaRegion>(MR))
1235 os << "Memory allocated by alloca() should not be deallocated";
1236 else {
1237 os << "Argument to ";
1238 if (!printAllocDeallocName(os, C, DeallocExpr))
1239 os << "deallocator";
1240
1241 os << " is ";
1242 bool Summarized = MR ? SummarizeRegion(os, MR)
1243 : SummarizeValue(os, ArgVal);
1244 if (Summarized)
1245 os << ", which is not memory allocated by ";
Jordy Rose43859f62010-06-07 19:32:37 +00001246 else
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001247 os << "not memory allocated by ";
1248
1249 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose43859f62010-06-07 19:32:37 +00001250 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001251
Anna Zakse172e8b2011-08-17 23:00:25 +00001252 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001253 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001254 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001255 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001256 }
1257}
1258
Anton Yartsev648cb712013-04-04 23:46:29 +00001259void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1260 SourceRange Range,
1261 const Expr *DeallocExpr,
Anton Yartseva3ae9372013-04-05 11:25:10 +00001262 const RefState *RS,
Anton Yartsev30845182013-09-16 17:51:25 +00001263 SymbolRef Sym,
1264 bool OwnershipTransferred) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001265
1266 if (!Filter.CMismatchedDeallocatorChecker)
1267 return;
1268
1269 if (ExplodedNode *N = C.generateSink()) {
Anton Yartsev648cb712013-04-04 23:46:29 +00001270 if (!BT_MismatchedDealloc)
1271 BT_MismatchedDealloc.reset(new BugType("Bad deallocator",
1272 "Memory Error"));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001273
1274 SmallString<100> buf;
1275 llvm::raw_svector_ostream os(buf);
1276
1277 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1278 SmallString<20> AllocBuf;
1279 llvm::raw_svector_ostream AllocOs(AllocBuf);
1280 SmallString<20> DeallocBuf;
1281 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1282
Anton Yartsev30845182013-09-16 17:51:25 +00001283 if (OwnershipTransferred) {
1284 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1285 os << DeallocOs.str() << " cannot";
1286 else
1287 os << "Cannot";
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001288
Anton Yartsev30845182013-09-16 17:51:25 +00001289 os << " take ownership of memory";
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001290
Anton Yartsev30845182013-09-16 17:51:25 +00001291 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1292 os << " allocated by " << AllocOs.str();
1293 } else {
1294 os << "Memory";
1295 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1296 os << " allocated by " << AllocOs.str();
1297
1298 os << " should be deallocated by ";
1299 printExpectedDeallocName(os, RS->getAllocationFamily());
1300
1301 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1302 os << ", not " << DeallocOs.str();
1303 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001304
Anton Yartsev648cb712013-04-04 23:46:29 +00001305 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001306 R->markInteresting(Sym);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001307 R->addRange(Range);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001308 R->addVisitor(new MallocBugVisitor(Sym));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001309 C.emitReport(R);
1310 }
1311}
1312
Anna Zaks118aa752013-02-07 23:05:47 +00001313void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001314 SourceRange Range, const Expr *DeallocExpr,
1315 const Expr *AllocExpr) const {
1316
1317 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1318 !Filter.CNewDeleteChecker)
1319 return;
1320
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001321 if (!isTrackedByCurrentChecker(C, AllocExpr))
Anton Yartsev648cb712013-04-04 23:46:29 +00001322 return;
1323
Anna Zaks118aa752013-02-07 23:05:47 +00001324 ExplodedNode *N = C.generateSink();
1325 if (N == NULL)
1326 return;
1327
1328 if (!BT_OffsetFree)
1329 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1330
1331 SmallString<100> buf;
1332 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001333 SmallString<20> AllocNameBuf;
1334 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaks118aa752013-02-07 23:05:47 +00001335
1336 const MemRegion *MR = ArgVal.getAsRegion();
1337 assert(MR && "Only MemRegion based symbols can have offset free errors");
1338
1339 RegionOffset Offset = MR->getAsOffset();
1340 assert((Offset.isValid() &&
1341 !Offset.hasSymbolicOffset() &&
1342 Offset.getOffset() != 0) &&
1343 "Only symbols with a valid offset can have offset free errors");
1344
1345 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1346
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001347 os << "Argument to ";
1348 if (!printAllocDeallocName(os, C, DeallocExpr))
1349 os << "deallocator";
1350 os << " is offset by "
Anna Zaks118aa752013-02-07 23:05:47 +00001351 << offsetBytes
1352 << " "
1353 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001354 << " from the start of ";
1355 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1356 os << "memory allocated by " << AllocNameOs.str();
1357 else
1358 os << "allocated memory";
Anna Zaks118aa752013-02-07 23:05:47 +00001359
1360 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1361 R->markInteresting(MR->getBaseRegion());
1362 R->addRange(Range);
1363 C.emitReport(R);
1364}
1365
Anton Yartsevbb369952013-03-13 14:39:10 +00001366void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1367 SymbolRef Sym) const {
1368
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001369 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1370 !Filter.CNewDeleteChecker)
1371 return;
1372
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001373 if (!isTrackedByCurrentChecker(C, Sym))
Anton Yartsev648cb712013-04-04 23:46:29 +00001374 return;
1375
Anton Yartsevbb369952013-03-13 14:39:10 +00001376 if (ExplodedNode *N = C.generateSink()) {
1377 if (!BT_UseFree)
1378 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1379
1380 BugReport *R = new BugReport(*BT_UseFree,
1381 "Use of memory after it is freed", N);
1382
1383 R->markInteresting(Sym);
1384 R->addRange(Range);
1385 R->addVisitor(new MallocBugVisitor(Sym));
1386 C.emitReport(R);
1387 }
1388}
1389
1390void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1391 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001392 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001393
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001394 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1395 !Filter.CNewDeleteChecker)
1396 return;
1397
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001398 if (!isTrackedByCurrentChecker(C, Sym))
Anton Yartsev648cb712013-04-04 23:46:29 +00001399 return;
1400
Anton Yartsevbb369952013-03-13 14:39:10 +00001401 if (ExplodedNode *N = C.generateSink()) {
1402 if (!BT_DoubleFree)
1403 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1404
1405 BugReport *R = new BugReport(*BT_DoubleFree,
1406 (Released ? "Attempt to free released memory"
1407 : "Attempt to free non-owned memory"),
1408 N);
1409 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001410 R->markInteresting(Sym);
1411 if (PrevSym)
1412 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001413 R->addVisitor(new MallocBugVisitor(Sym));
1414 C.emitReport(R);
1415 }
1416}
1417
Anna Zaks87cb5be2012-02-22 19:24:52 +00001418ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1419 const CallExpr *CE,
1420 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001421 if (CE->getNumArgs() < 2)
1422 return 0;
1423
Ted Kremenek8bef8232012-01-26 21:29:00 +00001424 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001425 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001426 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001427 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001428 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001429 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001430 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001431
Ted Kremenek846eabd2010-12-01 21:28:31 +00001432 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001433
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001434 DefinedOrUnknownSVal PtrEQ =
1435 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001436
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001437 // Get the size argument. If there is no size arg then give up.
1438 const Expr *Arg1 = CE->getArg(1);
1439 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001440 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001441
1442 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001443 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001444 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001445 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001446 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001447
1448 // Compare the size argument to 0.
1449 DefinedOrUnknownSVal SizeZero =
1450 svalBuilder.evalEQ(state, Arg1Val,
1451 svalBuilder.makeIntValWithPtrWidth(0, false));
1452
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001453 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1454 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1455 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1456 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1457 // We only assume exceptional states if they are definitely true; if the
1458 // state is under-constrained, assume regular realloc behavior.
1459 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1460 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1461
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001462 // If the ptr is NULL and the size is not 0, the call is equivalent to
1463 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001464 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001465 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001466 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001467 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001468 }
1469
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001470 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001471 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001472
Anna Zaks30838b92012-02-13 20:57:07 +00001473 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001474 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001475 SymbolRef FromPtr = arg0Val.getAsSymbol();
1476 SVal RetVal = state->getSVal(CE, LCtx);
1477 SymbolRef ToPtr = RetVal.getAsSymbol();
1478 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001479 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001480
Anna Zaks55dd9562012-08-24 02:28:20 +00001481 bool ReleasedAllocated = false;
1482
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001483 // If the size is 0, free the memory.
1484 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001485 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1486 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001487 // The semantics of the return value are:
1488 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001489 // to free() is returned. We just free the input pointer and do not add
1490 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001491 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001492 }
1493
1494 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001495 if (ProgramStateRef stateFree =
1496 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1497
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001498 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1499 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001500 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001501 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001502
Anna Zaks9dc298b2012-09-12 22:57:34 +00001503 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1504 if (FreesOnFail)
1505 Kind = RPIsFreeOnFailure;
1506 else if (!ReleasedAllocated)
1507 Kind = RPDoNotTrackAfterFailure;
1508
Anna Zaks55dd9562012-08-24 02:28:20 +00001509 // Record the info about the reallocated symbol so that we could properly
1510 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001511 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001512 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001513 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001514 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001515 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001516 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001517 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001518}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001519
Anna Zaks87cb5be2012-02-22 19:24:52 +00001520ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001521 if (CE->getNumArgs() < 2)
1522 return 0;
1523
Ted Kremenek8bef8232012-01-26 21:29:00 +00001524 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001525 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001526 const LocationContext *LCtx = C.getLocationContext();
1527 SVal count = state->getSVal(CE->getArg(0), LCtx);
1528 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001529 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1530 svalBuilder.getContext().getSizeType());
1531 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001532
Anna Zaks87cb5be2012-02-22 19:24:52 +00001533 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001534}
1535
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001536LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001537MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1538 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001539 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001540 // Walk the ExplodedGraph backwards and find the first node that referred to
1541 // the tracked symbol.
1542 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001543 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001544
1545 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001546 ProgramStateRef State = N->getState();
1547 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001548 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001549
1550 // Find the most recent expression bound to the symbol in the current
1551 // context.
Anna Zaks27d99dd2013-04-10 21:42:02 +00001552 if (!ReferenceRegion) {
1553 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1554 SVal Val = State->getSVal(MR);
1555 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks8cf91f72013-04-10 22:56:33 +00001556 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00001557 // Do not show local variables belonging to a function other than
1558 // where the error is reported.
1559 if (!VR ||
1560 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1561 ReferenceRegion = MR;
1562 }
1563 }
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001564 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001565
Anna Zaks7752d292012-02-27 23:40:55 +00001566 // Allocation node, is the last node in the current context in which the
1567 // symbol was tracked.
1568 if (N->getLocationContext() == LeakContext)
1569 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001570 N = N->pred_empty() ? NULL : *(N->pred_begin());
1571 }
1572
Anna Zaks97bfb552013-01-08 00:25:29 +00001573 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001574}
1575
Anna Zaksda046772012-02-11 21:02:40 +00001576void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1577 CheckerContext &C) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001578
1579 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
Jordan Rosee85deb32013-04-05 17:55:00 +00001580 !Filter.CNewDeleteLeaksChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001581 return;
1582
Jordan Rosee85deb32013-04-05 17:55:00 +00001583 const RefState *RS = C.getState()->get<RegionState>(Sym);
1584 assert(RS && "cannot leak an untracked symbol");
1585 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001586 if (!isTrackedByCurrentChecker(Family))
Anton Yartsev418780f2013-04-05 02:25:02 +00001587 return;
1588
Jordan Rosee85deb32013-04-05 17:55:00 +00001589 // Special case for new and new[]; these are controlled by a separate checker
1590 // flag so that they can be selectively disabled.
1591 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
1592 if (!Filter.CNewDeleteLeaksChecker)
1593 return;
1594
Anna Zaksda046772012-02-11 21:02:40 +00001595 assert(N);
1596 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001597 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001598 // Leaks should not be reported if they are post-dominated by a sink:
1599 // (1) Sinks are higher importance bugs.
1600 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1601 // with __noreturn functions such as assert() or exit(). We choose not
1602 // to report leaks on such paths.
1603 BT_Leak->setSuppressOnSink(true);
1604 }
1605
Anna Zaksca8e36e2012-02-23 21:38:21 +00001606 // Most bug reports are cached at the location where they occurred.
1607 // With leaks, we want to unique them by the location where they were
1608 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001609 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001610 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001611 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001612 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1613
1614 ProgramPoint P = AllocNode->getLocation();
1615 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001616 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001617 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001618 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001619 AllocationStmt = SP->getStmt();
Anton Yartsev418780f2013-04-05 02:25:02 +00001620 if (AllocationStmt)
Anna Zaks97bfb552013-01-08 00:25:29 +00001621 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1622 C.getSourceManager(),
1623 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001624
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001625 SmallString<200> buf;
1626 llvm::raw_svector_ostream os(buf);
Jordan Rose919e8a12012-08-08 18:23:36 +00001627 if (Region && Region->canPrintPretty()) {
Anna Zaks9e2f5972013-04-12 18:40:21 +00001628 os << "Potential leak of memory pointed to by ";
Jordan Rose919e8a12012-08-08 18:23:36 +00001629 Region->printPretty(os);
Anna Zaks68eb4c22013-04-06 00:41:36 +00001630 } else {
1631 os << "Potential memory leak";
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001632 }
1633
Anna Zaks97bfb552013-01-08 00:25:29 +00001634 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1635 LocUsedForUniqueing,
1636 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001637 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001638 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001639 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001640}
1641
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001642void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1643 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001644{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001645 if (!SymReaper.hasDeadSymbols())
1646 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001647
Ted Kremenek8bef8232012-01-26 21:29:00 +00001648 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001649 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001650 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001651
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001652 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001653 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1654 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001655 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001656 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001657 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001658 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001659
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001660 }
1661 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001662
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001663 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001664 ReallocPairsTy RP = state->get<ReallocPairs>();
1665 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001666 if (SymReaper.isDead(I->first) ||
1667 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001668 state = state->remove<ReallocPairs>(I->first);
1669 }
1670 }
1671
Anna Zaks4141e4d2012-11-13 03:18:01 +00001672 // Cleanup the FreeReturnValue Map.
1673 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1674 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1675 if (SymReaper.isDead(I->first) ||
1676 SymReaper.isDead(I->second)) {
1677 state = state->remove<FreeReturnValue>(I->first);
1678 }
1679 }
1680
Anna Zaksca8e36e2012-02-23 21:38:21 +00001681 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001682 ExplodedNode *N = C.getPredecessor();
1683 if (!Errors.empty()) {
1684 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1685 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper09d19ef2013-07-04 03:08:24 +00001686 for (SmallVectorImpl<SymbolRef>::iterator
1687 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001688 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001689 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001690 }
Anna Zaks54458702012-10-29 22:51:54 +00001691
Anna Zaksca8e36e2012-02-23 21:38:21 +00001692 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001693}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001694
Anton Yartsev55e57a52013-04-10 22:21:41 +00001695void MallocChecker::checkPreCall(const CallEvent &Call,
1696 CheckerContext &C) const {
1697
Anna Zaks14345182012-05-18 01:16:10 +00001698 // We will check for double free in the post visit.
Anton Yartsev55e57a52013-04-10 22:21:41 +00001699 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
1700 const FunctionDecl *FD = FC->getDecl();
1701 if (!FD)
1702 return;
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001703
Anton Yartsev55e57a52013-04-10 22:21:41 +00001704 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1705 isFreeFunction(FD, C.getASTContext()))
1706 return;
Anna Zaks66c40402012-02-14 21:55:24 +00001707
Anton Yartsev55e57a52013-04-10 22:21:41 +00001708 if (Filter.CNewDeleteChecker &&
1709 isStandardNewDelete(FD, C.getASTContext()))
1710 return;
1711 }
1712
1713 // Check if the callee of a method is deleted.
1714 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
1715 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
1716 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
1717 return;
1718 }
1719
1720 // Check arguments for being used after free.
1721 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
1722 SVal ArgSVal = Call.getArgSVal(I);
1723 if (ArgSVal.getAs<Loc>()) {
1724 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001725 if (!Sym)
1726 continue;
Anton Yartsev55e57a52013-04-10 22:21:41 +00001727 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks66c40402012-02-14 21:55:24 +00001728 return;
1729 }
1730 }
1731}
1732
Anna Zaks91c2a112012-02-08 23:16:56 +00001733void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1734 const Expr *E = S->getRetValue();
1735 if (!E)
1736 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001737
1738 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001739 ProgramStateRef State = C.getState();
1740 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001741 SymbolRef Sym = RetVal.getAsSymbol();
1742 if (!Sym)
1743 // If we are returning a field of the allocated struct or an array element,
1744 // the callee could still free the memory.
1745 // TODO: This logic should be a part of generic symbol escape callback.
1746 if (const MemRegion *MR = RetVal.getAsRegion())
1747 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1748 if (const SymbolicRegion *BMR =
1749 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1750 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001751
Anna Zaks0860cd02012-02-11 21:44:39 +00001752 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001753 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001754 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001755}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001756
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001757// TODO: Blocks should be either inlined or should call invalidate regions
1758// upon invocation. After that's in place, special casing here will not be
1759// needed.
1760void MallocChecker::checkPostStmt(const BlockExpr *BE,
1761 CheckerContext &C) const {
1762
1763 // Scan the BlockDecRefExprs for any object the retain count checker
1764 // may be tracking.
1765 if (!BE->getBlockDecl()->hasCaptures())
1766 return;
1767
1768 ProgramStateRef state = C.getState();
1769 const BlockDataRegion *R =
1770 cast<BlockDataRegion>(state->getSVal(BE,
1771 C.getLocationContext()).getAsRegion());
1772
1773 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1774 E = R->referenced_vars_end();
1775
1776 if (I == E)
1777 return;
1778
1779 SmallVector<const MemRegion*, 10> Regions;
1780 const LocationContext *LC = C.getLocationContext();
1781 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1782
1783 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001784 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001785 if (VR->getSuperRegion() == R) {
1786 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1787 }
1788 Regions.push_back(VR);
1789 }
1790
1791 state =
1792 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1793 Regions.data() + Regions.size()).getState();
1794 C.addTransition(state);
1795}
1796
Anna Zaks14345182012-05-18 01:16:10 +00001797bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001798 assert(Sym);
1799 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001800 return (RS && RS->isReleased());
1801}
1802
1803bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1804 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001805
Anton Yartsevbb369952013-03-13 14:39:10 +00001806 if (isReleased(Sym, C)) {
1807 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1808 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001809 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001810
Anna Zaks91c2a112012-02-08 23:16:56 +00001811 return false;
1812}
1813
Zhongxing Xuc8023782010-03-10 04:58:55 +00001814// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001815void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1816 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001817 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001818 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001819 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001820}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001821
Anna Zaks4fb54872012-02-11 21:02:35 +00001822// If a symbolic region is assumed to NULL (or another constant), stop tracking
1823// it - assuming that allocation failed on this path.
1824ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1825 SVal Cond,
1826 bool Assumption) const {
1827 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001828 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001829 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001830 ConstraintManager &CMgr = state->getConstraintManager();
1831 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1832 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001833 state = state->remove<RegionState>(I.getKey());
1834 }
1835
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001836 // Realloc returns 0 when reallocation fails, which means that we should
1837 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001838 ReallocPairsTy RP = state->get<ReallocPairs>();
1839 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001840 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001841 ConstraintManager &CMgr = state->getConstraintManager();
1842 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001843 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001844 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001845
Anna Zaks9dc298b2012-09-12 22:57:34 +00001846 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1847 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1848 if (RS->isReleased()) {
1849 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001850 state = state->set<RegionState>(ReallocSym,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001851 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks9dc298b2012-09-12 22:57:34 +00001852 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1853 state = state->remove<RegionState>(ReallocSym);
1854 else
1855 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001856 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001857 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001858 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001859 }
1860
Anna Zaks4fb54872012-02-11 21:02:35 +00001861 return state;
1862}
1863
Anna Zaks33708592013-06-08 00:29:29 +00001864bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zakse7a5c822013-05-31 23:47:32 +00001865 const CallEvent *Call,
1866 ProgramStateRef State,
1867 SymbolRef &EscapingSymbol) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001868 assert(Call);
Anna Zaks33708592013-06-08 00:29:29 +00001869 EscapingSymbol = 0;
1870
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001871 // For now, assume that any C++ call can free memory.
1872 // TODO: If we want to be more optimistic here, we'll need to make sure that
1873 // regions escape to C++ containers. They seem to do that even now, but for
1874 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001875 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zakse7a5c822013-05-31 23:47:32 +00001876 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001877
Jordan Rose740d4902012-07-02 19:27:35 +00001878 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001879 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001880 // If it's not a framework call, or if it takes a callback, assume it
1881 // can free memory.
1882 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zakse7a5c822013-05-31 23:47:32 +00001883 return true;
Anna Zaks07d39a42012-02-28 01:54:22 +00001884
Jordan Rose9fe09f32013-03-09 00:59:10 +00001885 // If it's a method we know about, handle it explicitly post-call.
1886 // This should happen before the "freeWhenDone" check below.
1887 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zakse7a5c822013-05-31 23:47:32 +00001888 return false;
Anna Zaks52a04812012-06-20 23:35:57 +00001889
Jordan Rose9fe09f32013-03-09 00:59:10 +00001890 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1891 // about, we can't be sure that the object will use free() to deallocate the
1892 // memory, so we can't model it explicitly. The best we can do is use it to
1893 // decide whether the pointer escapes.
1894 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zakse7a5c822013-05-31 23:47:32 +00001895 return *FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001896
Jordan Rose9fe09f32013-03-09 00:59:10 +00001897 // If the first selector piece ends with "NoCopy", and there is no
1898 // "freeWhenDone" parameter set to zero, we know ownership is being
1899 // transferred. Again, though, we can't be sure that the object will use
1900 // free() to deallocate the memory, so we can't model it explicitly.
1901 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001902 if (FirstSlot.endswith("NoCopy"))
Anna Zakse7a5c822013-05-31 23:47:32 +00001903 return true;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001904
Anna Zaks5f757682012-06-19 05:10:32 +00001905 // If the first selector starts with addPointer, insertPointer,
1906 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1907 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001908 // that the pointers get freed by following the container itself.
1909 if (FirstSlot.startswith("addPointer") ||
1910 FirstSlot.startswith("insertPointer") ||
1911 FirstSlot.startswith("replacePointer")) {
Anna Zakse7a5c822013-05-31 23:47:32 +00001912 return true;
Anna Zaks5f757682012-06-19 05:10:32 +00001913 }
1914
Anna Zakse7a5c822013-05-31 23:47:32 +00001915 // We should escape receiver on call to 'init'. This is especially relevant
1916 // to the receiver, as the corresponding symbol is usually not referenced
1917 // after the call.
1918 if (Msg->getMethodFamily() == OMF_init) {
1919 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
1920 return true;
1921 }
Anna Zaksee1af232013-05-31 22:39:13 +00001922
Jordan Rose740d4902012-07-02 19:27:35 +00001923 // Otherwise, assume that the method does not free memory.
1924 // Most framework methods do not free memory.
Anna Zakse7a5c822013-05-31 23:47:32 +00001925 return false;
Anna Zaks66c40402012-02-14 21:55:24 +00001926 }
1927
Jordan Rose740d4902012-07-02 19:27:35 +00001928 // At this point the only thing left to handle is straight function calls.
1929 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1930 if (!FD)
Anna Zakse7a5c822013-05-31 23:47:32 +00001931 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001932
Jordan Rose740d4902012-07-02 19:27:35 +00001933 ASTContext &ASTC = State->getStateManager().getContext();
1934
1935 // If it's one of the allocation functions we can reason about, we model
1936 // its behavior explicitly.
1937 if (isMemFunction(FD, ASTC))
Anna Zakse7a5c822013-05-31 23:47:32 +00001938 return false;
Jordan Rose740d4902012-07-02 19:27:35 +00001939
1940 // If it's not a system call, assume it frees memory.
1941 if (!Call->isInSystemHeader())
Anna Zakse7a5c822013-05-31 23:47:32 +00001942 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001943
1944 // White list the system functions whose arguments escape.
1945 const IdentifierInfo *II = FD->getIdentifier();
1946 if (!II)
Anna Zakse7a5c822013-05-31 23:47:32 +00001947 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001948 StringRef FName = II->getName();
1949
Jordan Rose740d4902012-07-02 19:27:35 +00001950 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001951 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001952 if (FName.endswith("NoCopy")) {
1953 // Look for the deallocator argument. We know that the memory ownership
1954 // is not transferred only if the deallocator argument is
1955 // 'kCFAllocatorNull'.
1956 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1957 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1958 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1959 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1960 if (DeallocatorName == "kCFAllocatorNull")
Anna Zakse7a5c822013-05-31 23:47:32 +00001961 return false;
Jordan Rose740d4902012-07-02 19:27:35 +00001962 }
1963 }
Anna Zakse7a5c822013-05-31 23:47:32 +00001964 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001965 }
1966
Jordan Rose740d4902012-07-02 19:27:35 +00001967 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001968 // 'closefn' is specified (and if that function does free memory),
1969 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001970 // Currently, we do not inspect the 'closefn' function (PR12101).
1971 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001972 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zakse7a5c822013-05-31 23:47:32 +00001973 return false;
Jordan Rose740d4902012-07-02 19:27:35 +00001974
1975 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1976 // these leaks might be intentional when setting the buffer for stdio.
1977 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1978 if (FName == "setbuf" || FName =="setbuffer" ||
1979 FName == "setlinebuf" || FName == "setvbuf") {
1980 if (Call->getNumArgs() >= 1) {
1981 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1982 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1983 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1984 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zakse7a5c822013-05-31 23:47:32 +00001985 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001986 }
1987 }
1988
1989 // A bunch of other functions which either take ownership of a pointer or
1990 // wrap the result up in a struct or object, meaning it can be freed later.
1991 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1992 // but the Malloc checker cannot differentiate between them. The right way
1993 // of doing this would be to implement a pointer escapes callback.
1994 if (FName == "CGBitmapContextCreate" ||
1995 FName == "CGBitmapContextCreateWithData" ||
1996 FName == "CVPixelBufferCreateWithBytes" ||
1997 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1998 FName == "OSAtomicEnqueue") {
Anna Zakse7a5c822013-05-31 23:47:32 +00001999 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002000 }
2001
Jordan Rose85d7e012012-07-02 19:27:51 +00002002 // Handle cases where we know a buffer's /address/ can escape.
2003 // Note that the above checks handle some special cases where we know that
2004 // even though the address escapes, it's still our responsibility to free the
2005 // buffer.
2006 if (Call->argumentsMayEscape())
Anna Zakse7a5c822013-05-31 23:47:32 +00002007 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00002008
2009 // Otherwise, assume that the function does not free memory.
2010 // Most system calls do not free the memory.
Anna Zakse7a5c822013-05-31 23:47:32 +00002011 return false;
Anna Zaks66c40402012-02-14 21:55:24 +00002012}
2013
Anna Zaks41988f32013-03-28 23:15:29 +00002014static bool retTrue(const RefState *RS) {
2015 return true;
2016}
2017
2018static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2019 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2020 RS->getAllocationFamily() == AF_CXXNew);
2021}
2022
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002023ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2024 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00002025 const CallEvent *Call,
2026 PointerEscapeKind Kind) const {
Anna Zaks41988f32013-03-28 23:15:29 +00002027 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2028}
2029
2030ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2031 const InvalidatedSymbols &Escaped,
2032 const CallEvent *Call,
2033 PointerEscapeKind Kind) const {
2034 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2035 &checkIfNewOrNewArrayFamily);
2036}
2037
2038ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2039 const InvalidatedSymbols &Escaped,
2040 const CallEvent *Call,
2041 PointerEscapeKind Kind,
2042 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00002043 // If we know that the call does not free memory, or we want to process the
2044 // call later, keep tracking the top level arguments.
Anna Zakse7a5c822013-05-31 23:47:32 +00002045 SymbolRef EscapingSymbol = 0;
Jordan Rose374ae322013-05-10 17:07:16 +00002046 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks33708592013-06-08 00:29:29 +00002047 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2048 EscapingSymbol) &&
Anna Zakse7a5c822013-05-31 23:47:32 +00002049 !EscapingSymbol) {
Anna Zaks66c40402012-02-14 21:55:24 +00002050 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00002051 }
Anna Zaks66c40402012-02-14 21:55:24 +00002052
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002053 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks41988f32013-03-28 23:15:29 +00002054 E = Escaped.end();
2055 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00002056 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002057
Anna Zakse7a5c822013-05-31 23:47:32 +00002058 if (EscapingSymbol && EscapingSymbol != sym)
2059 continue;
2060
Anna Zaks5b7aa342012-06-22 02:04:31 +00002061 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks04130232013-04-09 00:30:28 +00002062 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks431e35c2012-08-09 00:42:24 +00002063 State = State->remove<RegionState>(sym);
Anna Zaks04130232013-04-09 00:30:28 +00002064 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2065 }
Anna Zaks5b7aa342012-06-22 02:04:31 +00002066 }
Anna Zaks4fb54872012-02-11 21:02:35 +00002067 }
Anna Zaks66c40402012-02-14 21:55:24 +00002068 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00002069}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002070
Jordy Rose393f98b2012-03-18 07:43:35 +00002071static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2072 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00002073 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2074 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00002075
Jordan Rose166d5022012-11-02 01:54:06 +00002076 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00002077 I != E; ++I) {
2078 SymbolRef sym = I.getKey();
2079 if (!currMap.lookup(sym))
2080 return sym;
2081 }
2082
2083 return NULL;
2084}
2085
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002086PathDiagnosticPiece *
2087MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2088 const ExplodedNode *PrevN,
2089 BugReporterContext &BRC,
2090 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00002091 ProgramStateRef state = N->getState();
2092 ProgramStateRef statePrev = PrevN->getState();
2093
2094 const RefState *RS = state->get<RegionState>(Sym);
2095 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00002096 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002097 return 0;
2098
Anna Zaksfe571602012-02-16 22:26:07 +00002099 const Stmt *S = 0;
2100 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002101 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00002102
2103 // Retrieve the associated statement.
2104 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002105 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002106 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00002107 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002108 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00002109 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00002110 // If an assumption was made on a branch, it should be caught
2111 // here by looking at the state transition.
2112 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00002113 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00002114
Anna Zaksfe571602012-02-16 22:26:07 +00002115 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002116 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002117
Jordan Rose28038f32012-07-10 22:07:42 +00002118 // FIXME: We will eventually need to handle non-statement-based events
2119 // (__attribute__((cleanup))).
2120
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002121 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00002122 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00002123 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002124 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00002125 StackHint = new StackHintGeneratorForSymbol(Sym,
2126 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00002127 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002128 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00002129 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zaks148d9222013-04-16 00:22:55 +00002130 "Returning; memory was released");
Anna Zaks5b7aa342012-06-22 02:04:31 +00002131 } else if (isRelinquished(RS, RSPrev, S)) {
2132 Msg = "Memory ownership is transfered";
2133 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00002134 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002135 Mode = ReallocationFailed;
2136 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00002137 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00002138 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00002139
Jordy Roseb000fb52012-03-24 03:15:09 +00002140 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2141 // Is it possible to fail two reallocs WITHOUT testing in between?
2142 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2143 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00002144 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00002145 FailedReallocSymbol = sym;
2146 }
Anna Zaksfe571602012-02-16 22:26:07 +00002147 }
2148
2149 // We are in a special mode if a reallocation failed later in the path.
2150 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002151 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00002152
Jordy Roseb000fb52012-03-24 03:15:09 +00002153 // Is this is the first appearance of the reallocated symbol?
2154 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002155 // We're at the reallocation point.
2156 Msg = "Attempt to reallocate memory";
2157 StackHint = new StackHintGeneratorForSymbol(Sym,
2158 "Returned reallocated memory");
2159 FailedReallocSymbol = NULL;
2160 Mode = Normal;
2161 }
Anna Zaksfe571602012-02-16 22:26:07 +00002162 }
2163
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002164 if (!Msg)
2165 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002166 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002167
2168 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00002169 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002170 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00002171 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002172}
2173
Anna Zaks93c5a242012-05-02 00:05:20 +00002174void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2175 const char *NL, const char *Sep) const {
2176
2177 RegionStateTy RS = State->get<RegionState>();
2178
Ted Kremenekc37fad62013-01-03 01:30:12 +00002179 if (!RS.isEmpty()) {
2180 Out << Sep << "MallocChecker:" << NL;
2181 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2182 I.getKey()->dumpToStream(Out);
2183 Out << " : ";
2184 I.getData().dump(Out);
2185 Out << NL;
2186 }
2187 }
Anna Zaks93c5a242012-05-02 00:05:20 +00002188}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002189
Anna Zaks148d9222013-04-16 00:22:55 +00002190void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2191 registerCStringCheckerBasic(mgr);
2192 mgr.registerChecker<MallocChecker>()->Filter.CNewDeleteLeaksChecker = true;
2193 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2194 // checker.
2195 mgr.registerChecker<MallocChecker>()->Filter.CNewDeleteChecker = true;
2196}
Anton Yartsev9df151c2013-04-12 23:25:40 +00002197
Anna Zaks231361a2012-02-08 23:16:52 +00002198#define REGISTER_CHECKER(name) \
2199void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002200 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00002201 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002202}
Anna Zaks231361a2012-02-08 23:16:52 +00002203
2204REGISTER_CHECKER(MallocPessimistic)
2205REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00002206REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002207REGISTER_CHECKER(MismatchedDeallocatorChecker)