blob: b000bfae4b6c6cecd81c397b4d3cce75d833b3ca [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 {
Ted Kremenekc37fad62013-01-03 01:30:12 +0000103 static const char *Table[] = {
104 "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
Jordan Rose9fe09f32013-03-09 00:59:10 +0000282 /// Check if the function is known not to free memory, or if it is
283 /// "interesting" and should be modeled explicitly.
284 ///
285 /// We assume that pointers do not escape through calls to system functions
286 /// not handled by this checker.
287 bool doesNotFreeMemOrInteresting(const CallEvent *Call,
288 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000289
Anna Zaks41988f32013-03-28 23:15:29 +0000290 // Implementation of the checkPointerEscape callabcks.
291 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
292 const InvalidatedSymbols &Escaped,
293 const CallEvent *Call,
294 PointerEscapeKind Kind,
295 bool(*CheckRefState)(const RefState*)) const;
296
Anton Yartsev9ae7a922013-04-11 00:05:20 +0000297 ///@{
298 /// Tells if a given family/call/symbol is tracked by the current checker.
299 bool isTrackedByCurrentChecker(AllocationFamily Family) const;
300 bool isTrackedByCurrentChecker(CheckerContext &C,
301 const Stmt *AllocDeallocStmt) const;
302 bool isTrackedByCurrentChecker(CheckerContext &C, SymbolRef Sym) const;
303 ///@}
Ted Kremenek9c378f72011-08-12 23:37:29 +0000304 static bool SummarizeValue(raw_ostream &os, SVal V);
305 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000306 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
307 const Expr *DeallocExpr) const;
Anton Yartsev648cb712013-04-04 23:46:29 +0000308 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartseva3ae9372013-04-05 11:25:10 +0000309 const Expr *DeallocExpr, const RefState *RS,
310 SymbolRef Sym) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000311 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
312 const Expr *DeallocExpr,
313 const Expr *AllocExpr = 0) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000314 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
315 SymbolRef Sym) const;
316 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000317 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000318
Anna Zaksca8e36e2012-02-23 21:38:21 +0000319 /// Find the location of the allocation for Sym on the path leading to the
320 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000321 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
322 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000323
Anna Zaksda046772012-02-11 21:02:40 +0000324 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
325
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000326 /// The bug visitor which allows us to print extra diagnostics along the
327 /// BugReport path. For example, showing the allocation site of the leaked
328 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000329 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000330 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000331 enum NotificationMode {
332 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000333 ReallocationFailed
334 };
335
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000336 // The allocated region symbol tracked by the main analysis.
337 SymbolRef Sym;
338
Anna Zaks88feba02012-05-10 01:37:40 +0000339 // The mode we are in, i.e. what kind of diagnostics will be emitted.
340 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000341
Anna Zaks88feba02012-05-10 01:37:40 +0000342 // A symbol from when the primary region should have been reallocated.
343 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000344
Anna Zaks88feba02012-05-10 01:37:40 +0000345 bool IsLeak;
346
347 public:
348 MallocBugVisitor(SymbolRef S, bool isLeak = false)
349 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000350
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000351 virtual ~MallocBugVisitor() {}
352
353 void Profile(llvm::FoldingSetNodeID &ID) const {
354 static int X = 0;
355 ID.AddPointer(&X);
356 ID.AddPointer(Sym);
357 }
358
Anna Zaksfe571602012-02-16 22:26:07 +0000359 inline bool isAllocated(const RefState *S, const RefState *SPrev,
360 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000361 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000362 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000363 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000364 }
365
Anna Zaksfe571602012-02-16 22:26:07 +0000366 inline bool isReleased(const RefState *S, const RefState *SPrev,
367 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000368 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000369 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000370 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
371 }
372
Anna Zaks5b7aa342012-06-22 02:04:31 +0000373 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
374 const Stmt *Stmt) {
375 // Did not track -> relinquished. Other state (allocated) -> relinquished.
376 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
377 isa<ObjCPropertyRefExpr>(Stmt)) &&
378 (S && S->isRelinquished()) &&
379 (!SPrev || !SPrev->isRelinquished()));
380 }
381
Anna Zaksfe571602012-02-16 22:26:07 +0000382 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
383 const Stmt *Stmt) {
384 // If the expression is not a call, and the state change is
385 // released -> allocated, it must be the realloc return value
386 // check. If we have to handle more cases here, it might be cleaner just
387 // to track this extra bit in the state itself.
388 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
389 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000390 }
391
392 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
393 const ExplodedNode *PrevN,
394 BugReporterContext &BRC,
395 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000396
397 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
398 const ExplodedNode *EndPathNode,
399 BugReport &BR) {
400 if (!IsLeak)
401 return 0;
402
403 PathDiagnosticLocation L =
404 PathDiagnosticLocation::createEndOfPath(EndPathNode,
405 BRC.getSourceManager());
406 // Do not add the statement itself as a range in case of leak.
407 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
408 }
409
Anna Zaks56a938f2012-03-16 23:24:20 +0000410 private:
411 class StackHintGeneratorForReallocationFailed
412 : public StackHintGeneratorForSymbol {
413 public:
414 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
415 : StackHintGeneratorForSymbol(S, M) {}
416
417 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000418 // Printed parameters start at 1, not 0.
419 ++ArgIndex;
420
Anna Zaks56a938f2012-03-16 23:24:20 +0000421 SmallString<200> buf;
422 llvm::raw_svector_ostream os(buf);
423
Jordan Rose615a0922012-09-22 01:24:42 +0000424 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
425 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000426
427 return os.str();
428 }
429
430 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000431 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000432 }
433 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000434 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000435};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000436} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000437
Jordan Rose166d5022012-11-02 01:54:06 +0000438REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
439REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000440
Anna Zaks4141e4d2012-11-13 03:18:01 +0000441// A map from the freed symbol to the symbol representing the return value of
442// the free function.
443REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
444
Anna Zaks4fb54872012-02-11 21:02:35 +0000445namespace {
446class StopTrackingCallback : public SymbolVisitor {
447 ProgramStateRef state;
448public:
449 StopTrackingCallback(ProgramStateRef st) : state(st) {}
450 ProgramStateRef getState() const { return state; }
451
452 bool VisitSymbol(SymbolRef sym) {
453 state = state->remove<RegionState>(sym);
454 return true;
455 }
456};
457} // end anonymous namespace
458
Anna Zaks66c40402012-02-14 21:55:24 +0000459void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000460 if (II_malloc)
461 return;
462 II_malloc = &Ctx.Idents.get("malloc");
463 II_free = &Ctx.Idents.get("free");
464 II_realloc = &Ctx.Idents.get("realloc");
465 II_reallocf = &Ctx.Idents.get("reallocf");
466 II_calloc = &Ctx.Idents.get("calloc");
467 II_valloc = &Ctx.Idents.get("valloc");
468 II_strdup = &Ctx.Idents.get("strdup");
469 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000470}
471
Anna Zaks66c40402012-02-14 21:55:24 +0000472bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000473 if (isFreeFunction(FD, C))
474 return true;
475
476 if (isAllocationFunction(FD, C))
477 return true;
478
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000479 if (isStandardNewDelete(FD, C))
480 return true;
481
Anna Zaks14345182012-05-18 01:16:10 +0000482 return false;
483}
484
485bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
486 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000487 if (!FD)
488 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000489
Jordan Rose5ef6e942012-07-10 23:13:01 +0000490 if (FD->getKind() == Decl::Function) {
491 IdentifierInfo *FunI = FD->getIdentifier();
492 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000493
Jordan Rose5ef6e942012-07-10 23:13:01 +0000494 if (FunI == II_malloc || FunI == II_realloc ||
495 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
496 FunI == II_strdup || FunI == II_strndup)
497 return true;
498 }
Anna Zaks66c40402012-02-14 21:55:24 +0000499
Anna Zaks14345182012-05-18 01:16:10 +0000500 if (Filter.CMallocOptimistic && FD->hasAttrs())
501 for (specific_attr_iterator<OwnershipAttr>
502 i = FD->specific_attr_begin<OwnershipAttr>(),
503 e = FD->specific_attr_end<OwnershipAttr>();
504 i != e; ++i)
505 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
506 return true;
507 return false;
508}
509
510bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
511 if (!FD)
512 return false;
513
Jordan Rose5ef6e942012-07-10 23:13:01 +0000514 if (FD->getKind() == Decl::Function) {
515 IdentifierInfo *FunI = FD->getIdentifier();
516 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000517
Jordan Rose5ef6e942012-07-10 23:13:01 +0000518 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
519 return true;
520 }
Anna Zaks66c40402012-02-14 21:55:24 +0000521
Anna Zaks14345182012-05-18 01:16:10 +0000522 if (Filter.CMallocOptimistic && FD->hasAttrs())
523 for (specific_attr_iterator<OwnershipAttr>
524 i = FD->specific_attr_begin<OwnershipAttr>(),
525 e = FD->specific_attr_end<OwnershipAttr>();
526 i != e; ++i)
527 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
528 (*i)->getOwnKind() == OwnershipAttr::Holds)
529 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000530 return false;
531}
532
Anton Yartsev69746282013-03-28 16:10:38 +0000533// Tells if the callee is one of the following:
534// 1) A global non-placement new/delete operator function.
535// 2) A global placement operator function with the single placement argument
536// of type std::nothrow_t.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000537bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
538 ASTContext &C) const {
539 if (!FD)
540 return false;
541
542 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
543 if (Kind != OO_New && Kind != OO_Array_New &&
544 Kind != OO_Delete && Kind != OO_Array_Delete)
545 return false;
546
Anton Yartsev69746282013-03-28 16:10:38 +0000547 // Skip all operator new/delete methods.
548 if (isa<CXXMethodDecl>(FD))
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000549 return false;
550
551 // Return true if tested operator is a standard placement nothrow operator.
552 if (FD->getNumParams() == 2) {
553 QualType T = FD->getParamDecl(1)->getType();
554 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
555 return II->getName().equals("nothrow_t");
556 }
557
558 // Skip placement operators.
559 if (FD->getNumParams() != 1 || FD->isVariadic())
560 return false;
561
562 // One of the standard new/new[]/delete/delete[] non-placement operators.
563 return true;
564}
565
Anna Zaksb319e022012-02-08 20:13:28 +0000566void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000567 if (C.wasInlined)
568 return;
569
Anna Zaksb319e022012-02-08 20:13:28 +0000570 const FunctionDecl *FD = C.getCalleeDecl(CE);
571 if (!FD)
572 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000573
Anna Zaks87cb5be2012-02-22 19:24:52 +0000574 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000575 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000576
577 if (FD->getKind() == Decl::Function) {
578 initIdentifierInfo(C.getASTContext());
579 IdentifierInfo *FunI = FD->getIdentifier();
580
Anton Yartsev648cb712013-04-04 23:46:29 +0000581 if (FunI == II_malloc || FunI == II_valloc) {
582 if (CE->getNumArgs() < 1)
583 return;
584 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
585 } else if (FunI == II_realloc) {
586 State = ReallocMem(C, CE, false);
587 } else if (FunI == II_reallocf) {
588 State = ReallocMem(C, CE, true);
589 } else if (FunI == II_calloc) {
590 State = CallocMem(C, CE);
591 } else if (FunI == II_free) {
592 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
593 } else if (FunI == II_strdup) {
594 State = MallocUpdateRefState(C, CE, State);
595 } else if (FunI == II_strndup) {
596 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000597 }
Anton Yartsev648cb712013-04-04 23:46:29 +0000598 else if (isStandardNewDelete(FD, C.getASTContext())) {
599 // Process direct calls to operator new/new[]/delete/delete[] functions
600 // as distinct from new/new[]/delete/delete[] expressions that are
601 // processed by the checkPostStmt callbacks for CXXNewExpr and
602 // CXXDeleteExpr.
603 OverloadedOperatorKind K = FD->getOverloadedOperator();
604 if (K == OO_New)
605 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
606 AF_CXXNew);
607 else if (K == OO_Array_New)
608 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
609 AF_CXXNewArray);
610 else if (K == OO_Delete || K == OO_Array_Delete)
611 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
612 else
613 llvm_unreachable("not a new/delete operator");
Jordan Rose5ef6e942012-07-10 23:13:01 +0000614 }
615 }
616
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000617 if (Filter.CMallocOptimistic || Filter.CMismatchedDeallocatorChecker) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000618 // Check all the attributes, if there are any.
619 // There can be multiple of these attributes.
620 if (FD->hasAttrs())
621 for (specific_attr_iterator<OwnershipAttr>
622 i = FD->specific_attr_begin<OwnershipAttr>(),
623 e = FD->specific_attr_end<OwnershipAttr>();
624 i != e; ++i) {
625 switch ((*i)->getOwnKind()) {
626 case OwnershipAttr::Returns:
627 State = MallocMemReturnsAttr(C, CE, *i);
628 break;
629 case OwnershipAttr::Takes:
630 case OwnershipAttr::Holds:
631 State = FreeMemAttr(C, CE, *i);
632 break;
633 }
634 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000635 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000636 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000637}
638
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000639void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
640 CheckerContext &C) const {
641
642 if (NE->getNumPlacementArgs())
643 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
644 E = NE->placement_arg_end(); I != E; ++I)
645 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
646 checkUseAfterFree(Sym, C, *I);
647
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000648 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
649 return;
650
651 ProgramStateRef State = C.getState();
652 // The return value from operator new is bound to a specified initialization
653 // value (if any) and we don't want to loose this value. So we call
654 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
655 // existing binding.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000656 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
657 : AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000658 C.addTransition(State);
659}
660
661void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
662 CheckerContext &C) const {
663
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000664 if (!Filter.CNewDeleteChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000665 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
666 checkUseAfterFree(Sym, C, DE->getArgument());
667
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000668 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
669 return;
670
671 ProgramStateRef State = C.getState();
672 bool ReleasedAllocated;
673 State = FreeMemAux(C, DE->getArgument(), DE, State,
674 /*Hold*/false, ReleasedAllocated);
675
676 C.addTransition(State);
677}
678
Jordan Rose9fe09f32013-03-09 00:59:10 +0000679static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
680 // If the first selector piece is one of the names below, assume that the
681 // object takes ownership of the memory, promising to eventually deallocate it
682 // with free().
683 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
684 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
685 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
686 if (FirstSlot == "dataWithBytesNoCopy" ||
687 FirstSlot == "initWithBytesNoCopy" ||
688 FirstSlot == "initWithCharactersNoCopy")
689 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000690
691 return false;
692}
693
Jordan Rose9fe09f32013-03-09 00:59:10 +0000694static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
695 Selector S = Call.getSelector();
696
697 // FIXME: We should not rely on fully-constrained symbols being folded.
698 for (unsigned i = 1; i < S.getNumArgs(); ++i)
699 if (S.getNameForSlot(i).equals("freeWhenDone"))
700 return !Call.getArgSVal(i).isZeroConstant();
701
702 return None;
703}
704
Anna Zaks4141e4d2012-11-13 03:18:01 +0000705void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
706 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000707 if (C.wasInlined)
708 return;
709
Jordan Rose9fe09f32013-03-09 00:59:10 +0000710 if (!isKnownDeallocObjCMethodName(Call))
711 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000712
Jordan Rose9fe09f32013-03-09 00:59:10 +0000713 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
714 if (!*FreeWhenDone)
715 return;
716
717 bool ReleasedAllocatedMemory;
718 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
719 Call.getOriginExpr(), C.getState(),
720 /*Hold=*/true, ReleasedAllocatedMemory,
721 /*RetNullOnFailure=*/true);
722
723 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000724}
725
Anna Zaks87cb5be2012-02-22 19:24:52 +0000726ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
727 const CallExpr *CE,
728 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000729 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000730 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000731
Sean Huntcf807c42010-08-18 23:23:40 +0000732 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000733 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000734 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000735 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000736 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000737}
738
Anna Zaksb319e022012-02-08 20:13:28 +0000739ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000740 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000741 SVal Size, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000742 ProgramStateRef State,
743 AllocationFamily Family) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000744
745 // Bind the return value to the symbolic value from the heap region.
746 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
747 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000748 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000749 SValBuilder &svalBuilder = C.getSValBuilder();
750 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000751 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
752 .castAs<DefinedSVal>();
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000753 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000754
Anna Zaksb16ce452012-02-15 00:11:22 +0000755 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000756 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000757 return 0;
758
Jordy Rose32f26562010-07-04 00:00:41 +0000759 // Fill the region with the initialization value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000760 State = State->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000761
Jordy Rose32f26562010-07-04 00:00:41 +0000762 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000763 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000764 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000765 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000766 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000767 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000768 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000769 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000770 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000771 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000772 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000773
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000774 State = State->assume(extentMatchesSize, true);
775 assert(State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000776 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000777
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000778 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000779}
780
781ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000782 const Expr *E,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000783 ProgramStateRef State,
784 AllocationFamily Family) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000785 // Get the return value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000786 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000787
788 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000789 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000790 return 0;
791
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000792 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000793 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000794
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000795 // Set the symbol's state to Allocated.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000796 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000797}
798
Anna Zaks87cb5be2012-02-22 19:24:52 +0000799ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
800 const CallExpr *CE,
801 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000802 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000803 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000804
Anna Zaksb3d72752012-03-01 22:06:06 +0000805 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000806 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000807
Sean Huntcf807c42010-08-18 23:23:40 +0000808 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
809 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000810 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000811 Att->getOwnKind() == OwnershipAttr::Holds,
812 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000813 if (StateI)
814 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000815 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000816 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000817}
818
Ted Kremenek8bef8232012-01-26 21:29:00 +0000819ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000820 const CallExpr *CE,
821 ProgramStateRef state,
822 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000823 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000824 bool &ReleasedAllocated,
825 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000826 if (CE->getNumArgs() < (Num + 1))
827 return 0;
828
Anna Zaks4141e4d2012-11-13 03:18:01 +0000829 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
830 ReleasedAllocated, ReturnsNullOnFailure);
831}
832
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000833/// Checks if the previous call to free on the given symbol failed - if free
834/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000835static bool didPreviousFreeFail(ProgramStateRef State,
836 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000837 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000838 if (Ret) {
839 assert(*Ret && "We should not store the null return symbol");
840 ConstraintManager &CMgr = State->getConstraintManager();
841 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000842 RetStatusSymbol = *Ret;
843 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000844 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000845 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000846}
847
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000848AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartsev648cb712013-04-04 23:46:29 +0000849 const Stmt *S) const {
850 if (!S)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000851 return AF_None;
852
Anton Yartsev648cb712013-04-04 23:46:29 +0000853 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000854 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartsev648cb712013-04-04 23:46:29 +0000855
856 if (!FD)
857 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
858
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000859 ASTContext &Ctx = C.getASTContext();
860
Anton Yartsev648cb712013-04-04 23:46:29 +0000861 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000862 return AF_Malloc;
863
864 if (isStandardNewDelete(FD, Ctx)) {
865 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartsev648cb712013-04-04 23:46:29 +0000866 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000867 return AF_CXXNew;
Anton Yartsev648cb712013-04-04 23:46:29 +0000868 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000869 return AF_CXXNewArray;
870 }
871
872 return AF_None;
873 }
874
Anton Yartsev648cb712013-04-04 23:46:29 +0000875 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
876 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
877
878 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000879 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
880
Anton Yartsev648cb712013-04-04 23:46:29 +0000881 if (isa<ObjCMessageExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000882 return AF_Malloc;
883
884 return AF_None;
885}
886
887bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
888 const Expr *E) const {
889 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
890 // FIXME: This doesn't handle indirect calls.
891 const FunctionDecl *FD = CE->getDirectCallee();
892 if (!FD)
893 return false;
894
895 os << *FD;
896 if (!FD->isOverloadedOperator())
897 os << "()";
898 return true;
899 }
900
901 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
902 if (Msg->isInstanceMessage())
903 os << "-";
904 else
905 os << "+";
906 os << Msg->getSelector().getAsString();
907 return true;
908 }
909
910 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
911 os << "'"
912 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
913 << "'";
914 return true;
915 }
916
917 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
918 os << "'"
919 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
920 << "'";
921 return true;
922 }
923
924 return false;
925}
926
927void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
928 const Expr *E) const {
929 AllocationFamily Family = getAllocationFamily(C, E);
930
931 switch(Family) {
932 case AF_Malloc: os << "malloc()"; return;
933 case AF_CXXNew: os << "'new'"; return;
934 case AF_CXXNewArray: os << "'new[]'"; return;
935 case AF_None: llvm_unreachable("not a deallocation expression");
936 }
937}
938
939void MallocChecker::printExpectedDeallocName(raw_ostream &os,
940 AllocationFamily Family) const {
941 switch(Family) {
942 case AF_Malloc: os << "free()"; return;
943 case AF_CXXNew: os << "'delete'"; return;
944 case AF_CXXNewArray: os << "'delete[]'"; return;
945 case AF_None: llvm_unreachable("suspicious AF_None argument");
946 }
947}
948
Anna Zaks5b7aa342012-06-22 02:04:31 +0000949ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
950 const Expr *ArgExpr,
951 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000952 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000953 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000954 bool &ReleasedAllocated,
955 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000956
Anna Zaks4141e4d2012-11-13 03:18:01 +0000957 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000958 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000959 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000960 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000961
962 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000963 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000964 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000965
Anna Zaksb276bd92012-02-14 00:26:13 +0000966 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000967 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000968 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000969 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000970 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000971
Jordy Rose43859f62010-06-07 19:32:37 +0000972 // Unknown values could easily be okay
973 // Undefined values are handled elsewhere
974 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000975 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000976
Jordy Rose43859f62010-06-07 19:32:37 +0000977 const MemRegion *R = ArgVal.getAsRegion();
978
979 // Nonlocs can't be freed, of course.
980 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
981 if (!R) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000982 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000983 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000984 }
985
986 R = R->StripCasts();
987
988 // Blocks might show up as heap data, but should not be free()d
989 if (isa<BlockDataRegion>(R)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000990 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000991 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000992 }
993
994 const MemSpaceRegion *MS = R->getMemorySpace();
995
Anton Yartsevbb369952013-03-13 14:39:10 +0000996 // Parameters, locals, statics, globals, and memory returned by alloca()
997 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +0000998 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
999 // FIXME: at the time this code was written, malloc() regions were
1000 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1001 // This means that there isn't actually anything from HeapSpaceRegion
1002 // that should be freed, even though we allow it here.
1003 // Of course, free() can work on memory allocated outside the current
1004 // function, so UnknownSpaceRegion is always a possibility.
1005 // False negatives are better than false positives.
1006
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001007 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +00001008 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001009 }
Anna Zaks118aa752013-02-07 23:05:47 +00001010
1011 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +00001012 // Various cases could lead to non-symbol values here.
1013 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +00001014 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +00001015 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001016
Anna Zaks118aa752013-02-07 23:05:47 +00001017 SymbolRef SymBase = SrBase->getSymbol();
1018 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001019 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +00001020
Anton Yartsev648cb712013-04-04 23:46:29 +00001021 if (RsBase) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001022
Anna Zaks04130232013-04-09 00:30:28 +00001023 // Check for double free first.
1024 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartsev648cb712013-04-04 23:46:29 +00001025 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1026 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1027 SymBase, PreviousRetStatusSymbol);
1028 return 0;
Anton Yartsev648cb712013-04-04 23:46:29 +00001029
Anna Zaks04130232013-04-09 00:30:28 +00001030 // If the pointer is allocated or escaped, but we are now trying to free it,
1031 // check that the call to free is proper.
1032 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1033
1034 // Check if an expected deallocation function matches the real one.
1035 bool DeallocMatchesAlloc =
1036 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1037 if (!DeallocMatchesAlloc) {
1038 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1039 ParentExpr, RsBase, SymBase);
1040 return 0;
1041 }
1042
1043 // Check if the memory location being freed is the actual location
1044 // allocated, or an offset.
1045 RegionOffset Offset = R->getAsOffset();
1046 if (Offset.isValid() &&
1047 !Offset.hasSymbolicOffset() &&
1048 Offset.getOffset() != 0) {
1049 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1050 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1051 AllocExpr);
1052 return 0;
1053 }
Anton Yartsev648cb712013-04-04 23:46:29 +00001054 }
Anna Zaks118aa752013-02-07 23:05:47 +00001055 }
1056
1057 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +00001058
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001059 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +00001060 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001061
Anna Zaks4141e4d2012-11-13 03:18:01 +00001062 // Keep track of the return value. If it is NULL, we will know that free
1063 // failed.
1064 if (ReturnsNullOnFailure) {
1065 SVal RetVal = C.getSVal(ParentExpr);
1066 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1067 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +00001068 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1069 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +00001070 }
1071 }
1072
Anton Yartseva3989b82013-04-05 19:08:04 +00001073 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1074 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001075 // Normal free.
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001076 if (Hold)
Anna Zaks118aa752013-02-07 23:05:47 +00001077 return State->set<RegionState>(SymBase,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001078 RefState::getRelinquished(Family,
1079 ParentExpr));
1080
1081 return State->set<RegionState>(SymBase,
1082 RefState::getReleased(Family, ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001083}
1084
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001085bool MallocChecker::isTrackedByCurrentChecker(AllocationFamily Family) const {
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001086 switch (Family) {
1087 case AF_Malloc: {
1088 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic)
1089 return false;
Anton Yartsevc8454312013-04-05 02:12:04 +00001090 return true;
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001091 }
1092 case AF_CXXNew:
1093 case AF_CXXNewArray: {
1094 if (!Filter.CNewDeleteChecker)
1095 return false;
Anton Yartsevc8454312013-04-05 02:12:04 +00001096 return true;
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001097 }
1098 case AF_None: {
Anton Yartseva3989b82013-04-05 19:08:04 +00001099 llvm_unreachable("no family");
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001100 }
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001101 }
Anton Yartsevc8454312013-04-05 02:12:04 +00001102 llvm_unreachable("unhandled family");
Anton Yartsev648cb712013-04-04 23:46:29 +00001103}
1104
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001105bool
1106MallocChecker::isTrackedByCurrentChecker(CheckerContext &C,
1107 const Stmt *AllocDeallocStmt) const {
1108 return isTrackedByCurrentChecker(getAllocationFamily(C, AllocDeallocStmt));
Anton Yartsev648cb712013-04-04 23:46:29 +00001109}
1110
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001111bool MallocChecker::isTrackedByCurrentChecker(CheckerContext &C,
1112 SymbolRef Sym) const {
Anton Yartsev648cb712013-04-04 23:46:29 +00001113
Anton Yartseva3989b82013-04-05 19:08:04 +00001114 const RefState *RS = C.getState()->get<RegionState>(Sym);
1115 assert(RS);
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001116 return isTrackedByCurrentChecker(RS->getAllocationFamily());
Anton Yartsev648cb712013-04-04 23:46:29 +00001117}
1118
Ted Kremenek9c378f72011-08-12 23:37:29 +00001119bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001120 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001121 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001122 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001123 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001124 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +00001125 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +00001126 else
1127 return false;
1128
1129 return true;
1130}
1131
Ted Kremenek9c378f72011-08-12 23:37:29 +00001132bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +00001133 const MemRegion *MR) {
1134 switch (MR->getKind()) {
1135 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +00001136 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +00001137 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001138 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +00001139 else
1140 os << "the address of a function";
1141 return true;
1142 }
1143 case MemRegion::BlockTextRegionKind:
1144 os << "block text";
1145 return true;
1146 case MemRegion::BlockDataRegionKind:
1147 // FIXME: where the block came from?
1148 os << "a block";
1149 return true;
1150 default: {
1151 const MemSpaceRegion *MS = MR->getMemorySpace();
1152
Anna Zakseb31a762012-01-04 23:54:01 +00001153 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001154 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1155 const VarDecl *VD;
1156 if (VR)
1157 VD = VR->getDecl();
1158 else
1159 VD = NULL;
1160
1161 if (VD)
1162 os << "the address of the local variable '" << VD->getName() << "'";
1163 else
1164 os << "the address of a local stack variable";
1165 return true;
1166 }
Anna Zakseb31a762012-01-04 23:54:01 +00001167
1168 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001169 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1170 const VarDecl *VD;
1171 if (VR)
1172 VD = VR->getDecl();
1173 else
1174 VD = NULL;
1175
1176 if (VD)
1177 os << "the address of the parameter '" << VD->getName() << "'";
1178 else
1179 os << "the address of a parameter";
1180 return true;
1181 }
Anna Zakseb31a762012-01-04 23:54:01 +00001182
1183 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001184 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1185 const VarDecl *VD;
1186 if (VR)
1187 VD = VR->getDecl();
1188 else
1189 VD = NULL;
1190
1191 if (VD) {
1192 if (VD->isStaticLocal())
1193 os << "the address of the static variable '" << VD->getName() << "'";
1194 else
1195 os << "the address of the global variable '" << VD->getName() << "'";
1196 } else
1197 os << "the address of a global variable";
1198 return true;
1199 }
Anna Zakseb31a762012-01-04 23:54:01 +00001200
1201 return false;
Jordy Rose43859f62010-06-07 19:32:37 +00001202 }
1203 }
1204}
1205
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001206void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1207 SourceRange Range,
1208 const Expr *DeallocExpr) const {
1209
1210 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1211 !Filter.CNewDeleteChecker)
1212 return;
1213
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001214 if (!isTrackedByCurrentChecker(C, DeallocExpr))
Anton Yartsev648cb712013-04-04 23:46:29 +00001215 return;
1216
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001217 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +00001218 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001219 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +00001220
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001221 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +00001222 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001223
Jordy Rose43859f62010-06-07 19:32:37 +00001224 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001225 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1226 MR = ER->getSuperRegion();
1227
1228 if (MR && isa<AllocaRegion>(MR))
1229 os << "Memory allocated by alloca() should not be deallocated";
1230 else {
1231 os << "Argument to ";
1232 if (!printAllocDeallocName(os, C, DeallocExpr))
1233 os << "deallocator";
1234
1235 os << " is ";
1236 bool Summarized = MR ? SummarizeRegion(os, MR)
1237 : SummarizeValue(os, ArgVal);
1238 if (Summarized)
1239 os << ", which is not memory allocated by ";
Jordy Rose43859f62010-06-07 19:32:37 +00001240 else
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001241 os << "not memory allocated by ";
1242
1243 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose43859f62010-06-07 19:32:37 +00001244 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001245
Anna Zakse172e8b2011-08-17 23:00:25 +00001246 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001247 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001248 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001249 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001250 }
1251}
1252
Anton Yartsev648cb712013-04-04 23:46:29 +00001253void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1254 SourceRange Range,
1255 const Expr *DeallocExpr,
Anton Yartseva3ae9372013-04-05 11:25:10 +00001256 const RefState *RS,
1257 SymbolRef Sym) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001258
1259 if (!Filter.CMismatchedDeallocatorChecker)
1260 return;
1261
1262 if (ExplodedNode *N = C.generateSink()) {
Anton Yartsev648cb712013-04-04 23:46:29 +00001263 if (!BT_MismatchedDealloc)
1264 BT_MismatchedDealloc.reset(new BugType("Bad deallocator",
1265 "Memory Error"));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001266
1267 SmallString<100> buf;
1268 llvm::raw_svector_ostream os(buf);
1269
1270 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1271 SmallString<20> AllocBuf;
1272 llvm::raw_svector_ostream AllocOs(AllocBuf);
1273 SmallString<20> DeallocBuf;
1274 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1275
1276 os << "Memory";
1277 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1278 os << " allocated by " << AllocOs.str();
1279
1280 os << " should be deallocated by ";
1281 printExpectedDeallocName(os, RS->getAllocationFamily());
1282
1283 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1284 os << ", not " << DeallocOs.str();
1285
Anton Yartsev648cb712013-04-04 23:46:29 +00001286 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001287 R->markInteresting(Sym);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001288 R->addRange(Range);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001289 R->addVisitor(new MallocBugVisitor(Sym));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001290 C.emitReport(R);
1291 }
1292}
1293
Anna Zaks118aa752013-02-07 23:05:47 +00001294void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001295 SourceRange Range, const Expr *DeallocExpr,
1296 const Expr *AllocExpr) const {
1297
1298 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1299 !Filter.CNewDeleteChecker)
1300 return;
1301
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001302 if (!isTrackedByCurrentChecker(C, AllocExpr))
Anton Yartsev648cb712013-04-04 23:46:29 +00001303 return;
1304
Anna Zaks118aa752013-02-07 23:05:47 +00001305 ExplodedNode *N = C.generateSink();
1306 if (N == NULL)
1307 return;
1308
1309 if (!BT_OffsetFree)
1310 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1311
1312 SmallString<100> buf;
1313 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001314 SmallString<20> AllocNameBuf;
1315 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaks118aa752013-02-07 23:05:47 +00001316
1317 const MemRegion *MR = ArgVal.getAsRegion();
1318 assert(MR && "Only MemRegion based symbols can have offset free errors");
1319
1320 RegionOffset Offset = MR->getAsOffset();
1321 assert((Offset.isValid() &&
1322 !Offset.hasSymbolicOffset() &&
1323 Offset.getOffset() != 0) &&
1324 "Only symbols with a valid offset can have offset free errors");
1325
1326 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1327
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001328 os << "Argument to ";
1329 if (!printAllocDeallocName(os, C, DeallocExpr))
1330 os << "deallocator";
1331 os << " is offset by "
Anna Zaks118aa752013-02-07 23:05:47 +00001332 << offsetBytes
1333 << " "
1334 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001335 << " from the start of ";
1336 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1337 os << "memory allocated by " << AllocNameOs.str();
1338 else
1339 os << "allocated memory";
Anna Zaks118aa752013-02-07 23:05:47 +00001340
1341 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1342 R->markInteresting(MR->getBaseRegion());
1343 R->addRange(Range);
1344 C.emitReport(R);
1345}
1346
Anton Yartsevbb369952013-03-13 14:39:10 +00001347void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1348 SymbolRef Sym) const {
1349
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001350 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1351 !Filter.CNewDeleteChecker)
1352 return;
1353
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001354 if (!isTrackedByCurrentChecker(C, Sym))
Anton Yartsev648cb712013-04-04 23:46:29 +00001355 return;
1356
Anton Yartsevbb369952013-03-13 14:39:10 +00001357 if (ExplodedNode *N = C.generateSink()) {
1358 if (!BT_UseFree)
1359 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1360
1361 BugReport *R = new BugReport(*BT_UseFree,
1362 "Use of memory after it is freed", N);
1363
1364 R->markInteresting(Sym);
1365 R->addRange(Range);
1366 R->addVisitor(new MallocBugVisitor(Sym));
1367 C.emitReport(R);
1368 }
1369}
1370
1371void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1372 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001373 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001374
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001375 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1376 !Filter.CNewDeleteChecker)
1377 return;
1378
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001379 if (!isTrackedByCurrentChecker(C, Sym))
Anton Yartsev648cb712013-04-04 23:46:29 +00001380 return;
1381
Anton Yartsevbb369952013-03-13 14:39:10 +00001382 if (ExplodedNode *N = C.generateSink()) {
1383 if (!BT_DoubleFree)
1384 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1385
1386 BugReport *R = new BugReport(*BT_DoubleFree,
1387 (Released ? "Attempt to free released memory"
1388 : "Attempt to free non-owned memory"),
1389 N);
1390 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001391 R->markInteresting(Sym);
1392 if (PrevSym)
1393 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001394 R->addVisitor(new MallocBugVisitor(Sym));
1395 C.emitReport(R);
1396 }
1397}
1398
Anna Zaks87cb5be2012-02-22 19:24:52 +00001399ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1400 const CallExpr *CE,
1401 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001402 if (CE->getNumArgs() < 2)
1403 return 0;
1404
Ted Kremenek8bef8232012-01-26 21:29:00 +00001405 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001406 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001407 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001408 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001409 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001410 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001411 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001412
Ted Kremenek846eabd2010-12-01 21:28:31 +00001413 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001414
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001415 DefinedOrUnknownSVal PtrEQ =
1416 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001417
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001418 // Get the size argument. If there is no size arg then give up.
1419 const Expr *Arg1 = CE->getArg(1);
1420 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001421 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001422
1423 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001424 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001425 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001426 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001427 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001428
1429 // Compare the size argument to 0.
1430 DefinedOrUnknownSVal SizeZero =
1431 svalBuilder.evalEQ(state, Arg1Val,
1432 svalBuilder.makeIntValWithPtrWidth(0, false));
1433
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001434 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1435 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1436 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1437 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1438 // We only assume exceptional states if they are definitely true; if the
1439 // state is under-constrained, assume regular realloc behavior.
1440 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1441 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1442
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001443 // If the ptr is NULL and the size is not 0, the call is equivalent to
1444 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001445 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001446 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001447 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001448 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001449 }
1450
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001451 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001452 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001453
Anna Zaks30838b92012-02-13 20:57:07 +00001454 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001455 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001456 SymbolRef FromPtr = arg0Val.getAsSymbol();
1457 SVal RetVal = state->getSVal(CE, LCtx);
1458 SymbolRef ToPtr = RetVal.getAsSymbol();
1459 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001460 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001461
Anna Zaks55dd9562012-08-24 02:28:20 +00001462 bool ReleasedAllocated = false;
1463
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001464 // If the size is 0, free the memory.
1465 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001466 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1467 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001468 // The semantics of the return value are:
1469 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001470 // to free() is returned. We just free the input pointer and do not add
1471 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001472 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001473 }
1474
1475 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001476 if (ProgramStateRef stateFree =
1477 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1478
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001479 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1480 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001481 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001482 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001483
Anna Zaks9dc298b2012-09-12 22:57:34 +00001484 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1485 if (FreesOnFail)
1486 Kind = RPIsFreeOnFailure;
1487 else if (!ReleasedAllocated)
1488 Kind = RPDoNotTrackAfterFailure;
1489
Anna Zaks55dd9562012-08-24 02:28:20 +00001490 // Record the info about the reallocated symbol so that we could properly
1491 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001492 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001493 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001494 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001495 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001496 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001497 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001498 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001499}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001500
Anna Zaks87cb5be2012-02-22 19:24:52 +00001501ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001502 if (CE->getNumArgs() < 2)
1503 return 0;
1504
Ted Kremenek8bef8232012-01-26 21:29:00 +00001505 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001506 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001507 const LocationContext *LCtx = C.getLocationContext();
1508 SVal count = state->getSVal(CE->getArg(0), LCtx);
1509 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001510 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1511 svalBuilder.getContext().getSizeType());
1512 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001513
Anna Zaks87cb5be2012-02-22 19:24:52 +00001514 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001515}
1516
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001517LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001518MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1519 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001520 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001521 // Walk the ExplodedGraph backwards and find the first node that referred to
1522 // the tracked symbol.
1523 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001524 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001525
1526 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001527 ProgramStateRef State = N->getState();
1528 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001529 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001530
1531 // Find the most recent expression bound to the symbol in the current
1532 // context.
Anna Zaks27d99dd2013-04-10 21:42:02 +00001533 if (!ReferenceRegion) {
1534 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1535 SVal Val = State->getSVal(MR);
1536 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks8cf91f72013-04-10 22:56:33 +00001537 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks27d99dd2013-04-10 21:42:02 +00001538 // Do not show local variables belonging to a function other than
1539 // where the error is reported.
1540 if (!VR ||
1541 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1542 ReferenceRegion = MR;
1543 }
1544 }
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001545 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001546
Anna Zaks7752d292012-02-27 23:40:55 +00001547 // Allocation node, is the last node in the current context in which the
1548 // symbol was tracked.
1549 if (N->getLocationContext() == LeakContext)
1550 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001551 N = N->pred_empty() ? NULL : *(N->pred_begin());
1552 }
1553
Anna Zaks97bfb552013-01-08 00:25:29 +00001554 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001555}
1556
Anna Zaksda046772012-02-11 21:02:40 +00001557void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1558 CheckerContext &C) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001559
1560 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
Jordan Rosee85deb32013-04-05 17:55:00 +00001561 !Filter.CNewDeleteLeaksChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001562 return;
1563
Jordan Rosee85deb32013-04-05 17:55:00 +00001564 const RefState *RS = C.getState()->get<RegionState>(Sym);
1565 assert(RS && "cannot leak an untracked symbol");
1566 AllocationFamily Family = RS->getAllocationFamily();
Anton Yartsev9ae7a922013-04-11 00:05:20 +00001567 if (!isTrackedByCurrentChecker(Family))
Anton Yartsev418780f2013-04-05 02:25:02 +00001568 return;
1569
Jordan Rosee85deb32013-04-05 17:55:00 +00001570 // Special case for new and new[]; these are controlled by a separate checker
1571 // flag so that they can be selectively disabled.
1572 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
1573 if (!Filter.CNewDeleteLeaksChecker)
1574 return;
1575
Anna Zaksda046772012-02-11 21:02:40 +00001576 assert(N);
1577 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001578 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001579 // Leaks should not be reported if they are post-dominated by a sink:
1580 // (1) Sinks are higher importance bugs.
1581 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1582 // with __noreturn functions such as assert() or exit(). We choose not
1583 // to report leaks on such paths.
1584 BT_Leak->setSuppressOnSink(true);
1585 }
1586
Anna Zaksca8e36e2012-02-23 21:38:21 +00001587 // Most bug reports are cached at the location where they occurred.
1588 // With leaks, we want to unique them by the location where they were
1589 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001590 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001591 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001592 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001593 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1594
1595 ProgramPoint P = AllocNode->getLocation();
1596 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001597 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001598 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001599 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001600 AllocationStmt = SP->getStmt();
Anton Yartsev418780f2013-04-05 02:25:02 +00001601 if (AllocationStmt)
Anna Zaks97bfb552013-01-08 00:25:29 +00001602 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1603 C.getSourceManager(),
1604 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001605
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001606 SmallString<200> buf;
1607 llvm::raw_svector_ostream os(buf);
Jordan Rose919e8a12012-08-08 18:23:36 +00001608 if (Region && Region->canPrintPretty()) {
Anna Zaks68eb4c22013-04-06 00:41:36 +00001609 os << "Potential leak of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001610 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001611 os << '\'';
Anna Zaks68eb4c22013-04-06 00:41:36 +00001612 } else {
1613 os << "Potential memory leak";
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001614 }
1615
Anna Zaks97bfb552013-01-08 00:25:29 +00001616 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1617 LocUsedForUniqueing,
1618 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001619 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001620 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001621 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001622}
1623
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001624void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1625 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001626{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001627 if (!SymReaper.hasDeadSymbols())
1628 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001629
Ted Kremenek8bef8232012-01-26 21:29:00 +00001630 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001631 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001632 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001633
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001634 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001635 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1636 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001637 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001638 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001639 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001640 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001641
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001642 }
1643 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001644
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001645 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001646 ReallocPairsTy RP = state->get<ReallocPairs>();
1647 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001648 if (SymReaper.isDead(I->first) ||
1649 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001650 state = state->remove<ReallocPairs>(I->first);
1651 }
1652 }
1653
Anna Zaks4141e4d2012-11-13 03:18:01 +00001654 // Cleanup the FreeReturnValue Map.
1655 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1656 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1657 if (SymReaper.isDead(I->first) ||
1658 SymReaper.isDead(I->second)) {
1659 state = state->remove<FreeReturnValue>(I->first);
1660 }
1661 }
1662
Anna Zaksca8e36e2012-02-23 21:38:21 +00001663 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001664 ExplodedNode *N = C.getPredecessor();
1665 if (!Errors.empty()) {
1666 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1667 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001668 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001669 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001670 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001671 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001672 }
Anna Zaks54458702012-10-29 22:51:54 +00001673
Anna Zaksca8e36e2012-02-23 21:38:21 +00001674 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001675}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001676
Anton Yartsev55e57a52013-04-10 22:21:41 +00001677void MallocChecker::checkPreCall(const CallEvent &Call,
1678 CheckerContext &C) const {
1679
Anna Zaks14345182012-05-18 01:16:10 +00001680 // We will check for double free in the post visit.
Anton Yartsev55e57a52013-04-10 22:21:41 +00001681 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
1682 const FunctionDecl *FD = FC->getDecl();
1683 if (!FD)
1684 return;
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001685
Anton Yartsev55e57a52013-04-10 22:21:41 +00001686 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1687 isFreeFunction(FD, C.getASTContext()))
1688 return;
Anna Zaks66c40402012-02-14 21:55:24 +00001689
Anton Yartsev55e57a52013-04-10 22:21:41 +00001690 if (Filter.CNewDeleteChecker &&
1691 isStandardNewDelete(FD, C.getASTContext()))
1692 return;
1693 }
1694
1695 // Check if the callee of a method is deleted.
1696 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
1697 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
1698 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
1699 return;
1700 }
1701
1702 // Check arguments for being used after free.
1703 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
1704 SVal ArgSVal = Call.getArgSVal(I);
1705 if (ArgSVal.getAs<Loc>()) {
1706 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001707 if (!Sym)
1708 continue;
Anton Yartsev55e57a52013-04-10 22:21:41 +00001709 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks66c40402012-02-14 21:55:24 +00001710 return;
1711 }
1712 }
1713}
1714
Anna Zaks91c2a112012-02-08 23:16:56 +00001715void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1716 const Expr *E = S->getRetValue();
1717 if (!E)
1718 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001719
1720 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001721 ProgramStateRef State = C.getState();
1722 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001723 SymbolRef Sym = RetVal.getAsSymbol();
1724 if (!Sym)
1725 // If we are returning a field of the allocated struct or an array element,
1726 // the callee could still free the memory.
1727 // TODO: This logic should be a part of generic symbol escape callback.
1728 if (const MemRegion *MR = RetVal.getAsRegion())
1729 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1730 if (const SymbolicRegion *BMR =
1731 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1732 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001733
Anna Zaks0860cd02012-02-11 21:44:39 +00001734 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001735 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001736 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001737}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001738
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001739// TODO: Blocks should be either inlined or should call invalidate regions
1740// upon invocation. After that's in place, special casing here will not be
1741// needed.
1742void MallocChecker::checkPostStmt(const BlockExpr *BE,
1743 CheckerContext &C) const {
1744
1745 // Scan the BlockDecRefExprs for any object the retain count checker
1746 // may be tracking.
1747 if (!BE->getBlockDecl()->hasCaptures())
1748 return;
1749
1750 ProgramStateRef state = C.getState();
1751 const BlockDataRegion *R =
1752 cast<BlockDataRegion>(state->getSVal(BE,
1753 C.getLocationContext()).getAsRegion());
1754
1755 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1756 E = R->referenced_vars_end();
1757
1758 if (I == E)
1759 return;
1760
1761 SmallVector<const MemRegion*, 10> Regions;
1762 const LocationContext *LC = C.getLocationContext();
1763 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1764
1765 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001766 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001767 if (VR->getSuperRegion() == R) {
1768 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1769 }
1770 Regions.push_back(VR);
1771 }
1772
1773 state =
1774 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1775 Regions.data() + Regions.size()).getState();
1776 C.addTransition(state);
1777}
1778
Anna Zaks14345182012-05-18 01:16:10 +00001779bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001780 assert(Sym);
1781 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001782 return (RS && RS->isReleased());
1783}
1784
1785bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1786 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001787
Anton Yartsevbb369952013-03-13 14:39:10 +00001788 if (isReleased(Sym, C)) {
1789 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1790 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001791 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001792
Anna Zaks91c2a112012-02-08 23:16:56 +00001793 return false;
1794}
1795
Zhongxing Xuc8023782010-03-10 04:58:55 +00001796// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001797void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1798 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001799 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001800 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001801 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001802}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001803
Anna Zaks4fb54872012-02-11 21:02:35 +00001804// If a symbolic region is assumed to NULL (or another constant), stop tracking
1805// it - assuming that allocation failed on this path.
1806ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1807 SVal Cond,
1808 bool Assumption) const {
1809 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001810 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001811 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001812 ConstraintManager &CMgr = state->getConstraintManager();
1813 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1814 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001815 state = state->remove<RegionState>(I.getKey());
1816 }
1817
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001818 // Realloc returns 0 when reallocation fails, which means that we should
1819 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001820 ReallocPairsTy RP = state->get<ReallocPairs>();
1821 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001822 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001823 ConstraintManager &CMgr = state->getConstraintManager();
1824 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001825 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001826 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001827
Anna Zaks9dc298b2012-09-12 22:57:34 +00001828 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1829 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1830 if (RS->isReleased()) {
1831 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001832 state = state->set<RegionState>(ReallocSym,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001833 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks9dc298b2012-09-12 22:57:34 +00001834 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1835 state = state->remove<RegionState>(ReallocSym);
1836 else
1837 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001838 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001839 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001840 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001841 }
1842
Anna Zaks4fb54872012-02-11 21:02:35 +00001843 return state;
1844}
1845
Jordan Rose9fe09f32013-03-09 00:59:10 +00001846bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1847 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001848 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001849
1850 // For now, assume that any C++ call can free memory.
1851 // TODO: If we want to be more optimistic here, we'll need to make sure that
1852 // regions escape to C++ containers. They seem to do that even now, but for
1853 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001854 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001855 return false;
1856
Jordan Rose740d4902012-07-02 19:27:35 +00001857 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001858 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001859 // If it's not a framework call, or if it takes a callback, assume it
1860 // can free memory.
1861 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001862 return false;
1863
Jordan Rose9fe09f32013-03-09 00:59:10 +00001864 // If it's a method we know about, handle it explicitly post-call.
1865 // This should happen before the "freeWhenDone" check below.
1866 if (isKnownDeallocObjCMethodName(*Msg))
1867 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001868
Jordan Rose9fe09f32013-03-09 00:59:10 +00001869 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1870 // about, we can't be sure that the object will use free() to deallocate the
1871 // memory, so we can't model it explicitly. The best we can do is use it to
1872 // decide whether the pointer escapes.
1873 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1874 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001875
Jordan Rose9fe09f32013-03-09 00:59:10 +00001876 // If the first selector piece ends with "NoCopy", and there is no
1877 // "freeWhenDone" parameter set to zero, we know ownership is being
1878 // transferred. Again, though, we can't be sure that the object will use
1879 // free() to deallocate the memory, so we can't model it explicitly.
1880 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001881 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001882 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001883
Anna Zaks5f757682012-06-19 05:10:32 +00001884 // If the first selector starts with addPointer, insertPointer,
1885 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1886 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001887 // that the pointers get freed by following the container itself.
1888 if (FirstSlot.startswith("addPointer") ||
1889 FirstSlot.startswith("insertPointer") ||
1890 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001891 return false;
1892 }
1893
Jordan Rose740d4902012-07-02 19:27:35 +00001894 // Otherwise, assume that the method does not free memory.
1895 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001896 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001897 }
1898
Jordan Rose740d4902012-07-02 19:27:35 +00001899 // At this point the only thing left to handle is straight function calls.
1900 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1901 if (!FD)
1902 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001903
Jordan Rose740d4902012-07-02 19:27:35 +00001904 ASTContext &ASTC = State->getStateManager().getContext();
1905
1906 // If it's one of the allocation functions we can reason about, we model
1907 // its behavior explicitly.
1908 if (isMemFunction(FD, ASTC))
1909 return true;
1910
1911 // If it's not a system call, assume it frees memory.
1912 if (!Call->isInSystemHeader())
1913 return false;
1914
1915 // White list the system functions whose arguments escape.
1916 const IdentifierInfo *II = FD->getIdentifier();
1917 if (!II)
1918 return false;
1919 StringRef FName = II->getName();
1920
Jordan Rose740d4902012-07-02 19:27:35 +00001921 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001922 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001923 if (FName.endswith("NoCopy")) {
1924 // Look for the deallocator argument. We know that the memory ownership
1925 // is not transferred only if the deallocator argument is
1926 // 'kCFAllocatorNull'.
1927 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1928 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1929 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1930 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1931 if (DeallocatorName == "kCFAllocatorNull")
1932 return true;
1933 }
1934 }
1935 return false;
1936 }
1937
Jordan Rose740d4902012-07-02 19:27:35 +00001938 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001939 // 'closefn' is specified (and if that function does free memory),
1940 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001941 // Currently, we do not inspect the 'closefn' function (PR12101).
1942 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001943 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1944 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001945
1946 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1947 // these leaks might be intentional when setting the buffer for stdio.
1948 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1949 if (FName == "setbuf" || FName =="setbuffer" ||
1950 FName == "setlinebuf" || FName == "setvbuf") {
1951 if (Call->getNumArgs() >= 1) {
1952 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1953 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1954 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1955 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1956 return false;
1957 }
1958 }
1959
1960 // A bunch of other functions which either take ownership of a pointer or
1961 // wrap the result up in a struct or object, meaning it can be freed later.
1962 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1963 // but the Malloc checker cannot differentiate between them. The right way
1964 // of doing this would be to implement a pointer escapes callback.
1965 if (FName == "CGBitmapContextCreate" ||
1966 FName == "CGBitmapContextCreateWithData" ||
1967 FName == "CVPixelBufferCreateWithBytes" ||
1968 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1969 FName == "OSAtomicEnqueue") {
1970 return false;
1971 }
1972
Jordan Rose85d7e012012-07-02 19:27:51 +00001973 // Handle cases where we know a buffer's /address/ can escape.
1974 // Note that the above checks handle some special cases where we know that
1975 // even though the address escapes, it's still our responsibility to free the
1976 // buffer.
1977 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001978 return false;
1979
1980 // Otherwise, assume that the function does not free memory.
1981 // Most system calls do not free the memory.
1982 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001983}
1984
Anna Zaks41988f32013-03-28 23:15:29 +00001985static bool retTrue(const RefState *RS) {
1986 return true;
1987}
1988
1989static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
1990 return (RS->getAllocationFamily() == AF_CXXNewArray ||
1991 RS->getAllocationFamily() == AF_CXXNew);
1992}
1993
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001994ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1995 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001996 const CallEvent *Call,
1997 PointerEscapeKind Kind) const {
Anna Zaks41988f32013-03-28 23:15:29 +00001998 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
1999}
2000
2001ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2002 const InvalidatedSymbols &Escaped,
2003 const CallEvent *Call,
2004 PointerEscapeKind Kind) const {
2005 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2006 &checkIfNewOrNewArrayFamily);
2007}
2008
2009ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2010 const InvalidatedSymbols &Escaped,
2011 const CallEvent *Call,
2012 PointerEscapeKind Kind,
2013 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00002014 // If we know that the call does not free memory, or we want to process the
2015 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00002016 if ((Kind == PSK_DirectEscapeOnCall ||
2017 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00002018 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00002019 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00002020 }
Anna Zaks66c40402012-02-14 21:55:24 +00002021
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002022 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks41988f32013-03-28 23:15:29 +00002023 E = Escaped.end();
2024 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00002025 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00002026
Anna Zaks5b7aa342012-06-22 02:04:31 +00002027 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks04130232013-04-09 00:30:28 +00002028 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks431e35c2012-08-09 00:42:24 +00002029 State = State->remove<RegionState>(sym);
Anna Zaks04130232013-04-09 00:30:28 +00002030 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2031 }
Anna Zaks5b7aa342012-06-22 02:04:31 +00002032 }
Anna Zaks4fb54872012-02-11 21:02:35 +00002033 }
Anna Zaks66c40402012-02-14 21:55:24 +00002034 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00002035}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002036
Jordy Rose393f98b2012-03-18 07:43:35 +00002037static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2038 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00002039 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2040 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00002041
Jordan Rose166d5022012-11-02 01:54:06 +00002042 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00002043 I != E; ++I) {
2044 SymbolRef sym = I.getKey();
2045 if (!currMap.lookup(sym))
2046 return sym;
2047 }
2048
2049 return NULL;
2050}
2051
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002052PathDiagnosticPiece *
2053MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2054 const ExplodedNode *PrevN,
2055 BugReporterContext &BRC,
2056 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00002057 ProgramStateRef state = N->getState();
2058 ProgramStateRef statePrev = PrevN->getState();
2059
2060 const RefState *RS = state->get<RegionState>(Sym);
2061 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00002062 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002063 return 0;
2064
Anna Zaksfe571602012-02-16 22:26:07 +00002065 const Stmt *S = 0;
2066 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002067 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00002068
2069 // Retrieve the associated statement.
2070 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002071 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002072 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00002073 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002074 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00002075 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00002076 // If an assumption was made on a branch, it should be caught
2077 // here by looking at the state transition.
2078 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00002079 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00002080
Anna Zaksfe571602012-02-16 22:26:07 +00002081 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002082 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002083
Jordan Rose28038f32012-07-10 22:07:42 +00002084 // FIXME: We will eventually need to handle non-statement-based events
2085 // (__attribute__((cleanup))).
2086
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002087 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00002088 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00002089 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002090 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00002091 StackHint = new StackHintGeneratorForSymbol(Sym,
2092 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00002093 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002094 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00002095 StackHint = new StackHintGeneratorForSymbol(Sym,
2096 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00002097 } else if (isRelinquished(RS, RSPrev, S)) {
2098 Msg = "Memory ownership is transfered";
2099 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00002100 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002101 Mode = ReallocationFailed;
2102 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00002103 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00002104 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00002105
Jordy Roseb000fb52012-03-24 03:15:09 +00002106 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2107 // Is it possible to fail two reallocs WITHOUT testing in between?
2108 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2109 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00002110 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00002111 FailedReallocSymbol = sym;
2112 }
Anna Zaksfe571602012-02-16 22:26:07 +00002113 }
2114
2115 // We are in a special mode if a reallocation failed later in the path.
2116 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002117 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00002118
Jordy Roseb000fb52012-03-24 03:15:09 +00002119 // Is this is the first appearance of the reallocated symbol?
2120 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002121 // We're at the reallocation point.
2122 Msg = "Attempt to reallocate memory";
2123 StackHint = new StackHintGeneratorForSymbol(Sym,
2124 "Returned reallocated memory");
2125 FailedReallocSymbol = NULL;
2126 Mode = Normal;
2127 }
Anna Zaksfe571602012-02-16 22:26:07 +00002128 }
2129
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002130 if (!Msg)
2131 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002132 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002133
2134 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00002135 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002136 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00002137 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002138}
2139
Anna Zaks93c5a242012-05-02 00:05:20 +00002140void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2141 const char *NL, const char *Sep) const {
2142
2143 RegionStateTy RS = State->get<RegionState>();
2144
Ted Kremenekc37fad62013-01-03 01:30:12 +00002145 if (!RS.isEmpty()) {
2146 Out << Sep << "MallocChecker:" << NL;
2147 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2148 I.getKey()->dumpToStream(Out);
2149 Out << " : ";
2150 I.getData().dump(Out);
2151 Out << NL;
2152 }
2153 }
Anna Zaks93c5a242012-05-02 00:05:20 +00002154}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002155
Anna Zaks231361a2012-02-08 23:16:52 +00002156#define REGISTER_CHECKER(name) \
2157void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002158 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00002159 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002160}
Anna Zaks231361a2012-02-08 23:16:52 +00002161
2162REGISTER_CHECKER(MallocPessimistic)
2163REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00002164REGISTER_CHECKER(NewDeleteChecker)
Jordan Rosee85deb32013-04-05 17:55:00 +00002165REGISTER_CHECKER(NewDeleteLeaksChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002166REGISTER_CHECKER(MismatchedDeallocatorChecker)